查找Array是否包含Javascript的5个连续数字

时间:2015-04-15 04:24:40

标签: javascript

我有一个包含数字的排序数组。我想能够检查这个数组(或类似的数组)是否包含连续顺序的5个数字。

注意:数组可能包含重复和双位数字。

我正在尝试这个,但是没有出现过失败。

var array = [1,3,5,7,7,8,9,10,11]
var current = null;
var cnt = 0;
for (var i = 0; i < array.length; i++) {
    if (array[i] != current) {
        if (cnt > 4) {
            return true;
        }
        current = array[i];
        cnt = 1;
    } else {
        cnt++;
    }

}
if (cnt > 4) {
    return true;
}

}

7 个答案:

答案 0 :(得分:3)

功能方法是

function fiveInARow(array) {

  // compare if one element is greater than or equal to the previous one
  function compare(elt, i, arr) { return !i || elt >= arr[i-1]; });

  // check if at a given position, every one of the last five comparisons is true
  function check (_, i, greaters) { 
    return i >= 4 && greaters.slice(i-4, i) . every(Boolean);                         
  }

  return array . map(compare) . some(check);
}

这里的逻辑是首先使用map创建一个布尔数组,显示每个元素是否大于或等于前一个元素。这会产生一个数组,例如[true, true, true, false, true]

some部分询问,对于任何元素,该元素和前四个元素中的每一个都是真的吗?如果是,则返回true

递归解决方案

递归解决方案可能更容易阅读。

function fiveInARow(array) {

  return function _five(array, prev, n) {
    if (n >= 5)        return true;
    if (!array.length) return false;

    var next = array.shift();
    return _five(array, next, next === prev ? n : next >= prev ? n+1 : 0);
  }(array, -999999, 5);

}

答案 1 :(得分:2)

一种迭代,直接的方法是:

var should_be_true = [1,3,5,7,7,8,9,10,11];
var should_be_false = [1,3,5,7,9,11,13,15,17];

var testArray = function(array) {
    var conseq = 1;
    for (var idx = 1; idx < array.length ; idx++) {
        if (array[idx] == array[idx-1] + 1)
            conseq++;
        else
            conseq = 1;
        if (conseq == 5)
            return true;
    }
    return false;
}

console.log(testArray(should_be_true)); //true
console.log(testArray(should_be_false)); //false

但是对于奖励乐趣,这里是功能方法的一个变体,返回序列开始的位置,如果不存在足够长的序列,则返回-1:

should_be_true.map(function(curr,idx,arr) {
    return (curr == arr[idx-1] +1) ? 1 : 0;
}).join('').search(/1{4}/); 

答案 2 :(得分:0)

var array = [1,3,5,7,7,8,9,10,11];
var cons=false;
var count=0;
for(i=0;i<array.length;i++){
    if(array[i]+1==array[i+1]){
        count++;
    }
    else{
        count=0;
    }
    if(count==4){
        cons=true;
    }
}
if(cons){
    //do what you want with it
}

<强> DEMO

更优雅的方法是在函数中定义整个事物,如下所示:

function checkCons(array){
    var cons=false;
    var count=0;
    for(i=0;i<array.length;i++){
        if(array[i]+1==array[i+1]){
            count++;
        }
        else{
            count=0;
        }
        if(count==4){
            cons=true;
        }
    }
    return cons;
}

然后像这样使用它:

var array = [1,3,5,7,7,8,9,10,11];
if(checkCons(array)){
    //do what you want with it
}

<强> DEMO

答案 3 :(得分:0)

   function fiveStraight() {
       var array = [1, 3, 5, 7, 7, 8, 9, 10, 12];
       var prev = array[0];
       var numberOfStraight = 1;

       for (var i = 1; i < array.length; i++) {
           numberOfStraight = array[i] === prev + 1 ? numberOfStraight + 1 : 1;
           prev = array[i];
           if (numberOfStraight === 5) return true;
       }

       return false;
   }

JSFIDDLE

答案 4 :(得分:0)

以下是我发现最直接的方法。降序和升序值都计为连续值(如果不是这种情况,则调整Math.abs()调用)。

function consecutiveValuesCount(array) {
    // sort the values if not pre-sorted
    var sortedValues = array.sort();

    // the result variable / how many consecutive numbers did we find?
    // there's always atleast 1 consecutive digit ...
    var count = 1;
    for (var i = 0; i < sortedValues.length - 1; i++) {
        // both descending and ascending orders count as we are using Math.abs()
        if (Math.abs(sortedValues[i] - sortedValues[i+1]) == 1) {
          ++count;
        }
    }
    return count;
}
//input
var array = [1,2,4,5,3];
// output
5

答案 5 :(得分:0)

使用此代码,您可以找到给定数字的最高连续数或一般情况下找到最高连续数

var findMaxConsecutiveOnes = function (arr, number) {
   //check for boundries
   if(!number || !arr.length) return;

  // maximum number of consectuives
  let max = 0;

  // count homy many consecutives before it ends (why it's 1 ? because a lonely number is still counted)
  let counter = 1;

  // you can ignore the next 2 variable if you want to use for loop instead of while
  let length = arr.length;
  let i = 1; // counting from index 1 because we are checking against index-1
  while (i < length) {

    if (arr[i] == arr[i - 1]) {

      // boom, we have a consecutive, count it now
      counter++;
    } else {

      // rest to 1
      counter = 1;
    }

    // always update the max variable to the new max value
    max = Math.max(counter, max);

    //for the sake of iteration
    i++;
  }
  return max== number;
};
console.log(findMaxConsecutiveOnes([5, 5, 5, 1, 1, 1, 1, 1]));

答案 6 :(得分:-3)

cnt只会增加一次,当它达到两个7时。

将增量线置于真实状态,并将重置线放在else语句中。

&#13;
&#13;
// Put into a function for testing.
function foo() {
  var array = [1, 3, 5, 7, 7, 8, 9, 10, 11]
  var current = null;
  var cnt = 0;

  for (var i = 0; i < array.length; i++) {
    // Also need to make sure the next array item is a consecutive increase.
    if (array[i] != current && array[i] === array[i-1] + 1) {
      if (cnt > 4) {
        return true;
      }

      current = array[i];
      cnt++;
    } else {
      cnt = 1;
    }
  }

  if (cnt > 4) {
    return true;
  } else {
    return false;
  }
};

// Call function.
alert(foo());
&#13;
&#13;
&#13;