计算相同元素的连续对

时间:2019-10-27 22:05:51

标签: javascript arrays

给定一个数组arr[],如果数组中连续存在 5个或更多连续true,则任务是返回1

let arr = [0,0,0,0,0,0,1,1,0,1,1,1,1] // returns false => 4 consecutive 1
let arr = [0,0,0,0,0,1,1,0,1,1,1,1,1,0,0] // returns true => 5 consecutive 1

注意:数组仅包含0和1

3 个答案:

答案 0 :(得分:2)

您可以用柜台检查它。

const check5 = array => array.some((c => v => !(v ? ++c : (c = -5)))(-5));

console.log(check5([0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1]));
console.log(check5([0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0]));

答案 1 :(得分:0)

您可以使用for循环执行此操作,迭代数组的每个条目,如果计数器为1,则增加一个计数器,如果计数器为0,则将其重置

let arr1 = [0,0,0,0,0,0,1,1,0,1,1,1,1] // returns false => 4 consecutive 1
let arr2 = [0,0,0,0,0,1,1,0,1,1,1,1,1,0,0] // returns true => 5 consecutive 1
let arr3 = [0,0,0,0,0,1,1,0,0,0,1,1,1,1,1] // returns true => 5 consecutive 1

function hasConsecutiveOnes(arr) {
  let counter = 0;
  
  for(i = 0; i < arr.length; i++) {
    if (arr[i] !== 1) {
      counter = 0;
    } else if (arr[i] === 1) {
      if(counter + 1 === 5) {
       return true
      }
      counter++
    } else {
      counter = 0;
    }
  }
  
  return false
  
}

console.log(hasConsecutiveOnes(arr1))
console.log(hasConsecutiveOnes(arr2))
console.log(hasConsecutiveOnes(arr3))

答案 2 :(得分:0)

您可以尝试以下方法:

const fiveOnes = (arr) => {
  let oneCount = 0;
  for(let a of arr){
    if(a===0){
      oneCount = 0;
    }
    else{
      oneCount++;
      if(oneCount>=5) break;
    }
  }

  return (oneCount >= 5);
}

编辑:每当您获得“ 1”时就递增计数器,并在数组中获得“ 0”时将计数器重置为0。当连续的“ 1”的总数等于5时,退出循环以节省时间并返回结果。