Javascript - 如何检查 3 个数字是否连续并返回起点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10744537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:53:26  来源:igfitidea点击:

Javascript - How Do I Check if 3 Numbers Are Consecutive and Return Starting Points?

javascriptarrayssequences

提问by Yasir

If I have an array of [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7]and wanted to find each case of 3 consecutive numbers (whether ascending or descending), how would I do that?

如果我有一个数组,[1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7]并想找到 3 个连续数字的每个案例(无论是升序还是降序),我该怎么做?

Second part would be then to alert an array with the index of each of these sequences.

第二部分是用这些序列中的每一个的索引来提醒一个数组。

For ex. the previous array would return [0,4,6,7].

例如。前一个数组将返回[0,4,6,7].

So far I have this... which is a rough start

到目前为止,我有这个......这是一个艰难的开始

var arr = [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7];
var results = [];

for (var i = 1; i < arr.length; i++) {
    if ((arr[i] - arr[i-1] != 1) && (arr[i] - arr[i+1] != 1)) {
        results.push(arr[i]);
    }

}
alert(results);

Thanks for the help!

谢谢您的帮助!

Thanks for the math.abs pointer. This is what I ended up doing:

感谢 math.abs 指针。这就是我最终做的:

var array = [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7];
var indexes = [];

for(var i=0; i < array.length; i++) {
    var diff = array[i+1] - array[i];
    if(Math.abs(diff)==1 && array[i+1]+diff == array[i+2]) {
        indexes.push(i);
    }
}
alert(indexes);

采纳答案by raina77ow

It'd be interesting to know the context of this task as well... Anyway, here's my solution:

了解这项任务的上下文也会很有趣......无论如何,这是我的解决方案:

var arr     = [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7];
var results = [];
var limit   = arr.length - 1; 

var sequence = 0;
for (var i = 0; i < limit; ++i) {
  var diff = arr[i+1] - arr[i];
  if (sequence && sequence === diff) {
    results.push(i-1);
    continue;
  }
  sequence = (diff === 1 || diff === -1) // or ... Math.abs(diff) === 1
           ? diff
           : 0;
}
console.log(results);

The idea is simple: we don't need to compare two neighbors twice. ) It's enough to raise a kind of sequence flag if this comparation starts a sequence, and lower it if no sequence is there.

这个想法很简单:我们不需要两次比较两个邻居。) 如果这个比较开始一个序列,就足以提高一种序列标志,如果没有序列,则降低它。

回答by Billy Moon

This is a very literal approach to your question - I have only checked forwards numbers, but adding reverse would be done almost in the same way

这是对您的问题的一种非常直接的方法 - 我只检查了正向数字,但添加反向几乎以相同的方式完成

var arr = [1, 2, 3, 4, 10, 9, 8, 9, 10, 11, 7];
var results = [];

for (var i = 0; i < arr.length; i++) {

    // if next element is one more, and one after is two more
    if (arr[i+1] == arr[i]+1 && arr[i+2] == arr[i]+2){

        // store the index of matches
        results.push(i);

        // loop through next numbers, to prevent repeating longer sequences
        while(arr[i]+1 == arr[i+1])
            i++;
    }

}
console.log(results);

回答by Billy Moon

This is I think a simpler way to do it. First check the average of the left and right number is equal to the middle, then check that the absolute value of either neighbor is one.

这是我认为更简单的方法。首先检查左右数的平均值是否等于中间数,然后检查任一邻居的绝对值是否为1。

var arr = [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7];
var indexes = [];

for(var i=1; i < arr.length; i++) {
    if((arr[i-1]+arr[i+1]) / 2 == arr[i] && Math.abs(arr[i]-arr[i-1]) == 1) {
        indexes.push(i-1);
    }
}
alert(indexes);

回答by Dancrumb

You need to look closely at your expression in your if statement.

您需要仔细查看 if 语句中的表达式。

It currently says:

它目前说:

  • If the difference between the current element and previous element is not1, and
  • If the difference between the current element and next element is not1
  • 如果当前元素与前一个元素的差值不为1,并且
  • 如果当前元素与下一个元素的差值不为1

then it's a result.

那么就是结果。

So, on the face of it, that's an incorrect logical statement to determine if the current element is in the middle of a consecutive set of three.

因此,从表面上看,这是一个不正确的逻辑语句,用于确定当前元素是否位于连续三个集合的中间。

In addition, this doesn't account for an ascending or descending set of three either.

此外,这也不包括三个的升序或降序集合。

Try figuring out, in words, what the condition would look like and go from there.

试着用语言弄清楚情况会是什么样子,然后从那里开始。

Some things to consider

需要考虑的一些事项

  • I suggest you start going through the list from i = 2
  • Research Math.abs
  • 我建议你从 i = 2
  • 研究 Math.abs

回答by robrich

var arr = [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7];
var results = [];

for (var i = 0; i < arr.length - 2; i++) {
    if ((arr[i+1] - arr[i] === 1) && (arr[i+2] - arr[i+1] === 1)) {
        results.push({
            i:i,
            mode:'up',
            arr:[arr[i],arr[i+1],arr[i+2]
        });
    }
    if ((arr[i+1] - arr[i] === -1) && (arr[i+2] - arr[i+1] === -1)) {
        results.push({
            i:i,
            mode:'down',
            arr:[arr[i],arr[i+1],arr[i+2]
        });
    }

}
alert(results);