在Javascript数组中找到特定的连续数字集合

3

我想找出一个整数在数组中连续出现的次数。我找到了一个相似的例子:

const numbers = [0,0,0,296,296,0,0,296,296,296,0,0,0,0,0,293,293,293,293,293,293,293,293];

let chunks = [];

let prev = 0;
numbers.forEach((current) => {
  if ( current - prev != 1 ) chunks.push([]);

  // Now we can add our number to the current chunk!
  chunks[chunks.length - 1].push(current);
  prev = current;
});

chunks.sort((a, b) => b.length - a.length);

console.log('Longest consecutive set:', chunks[0]);
console.log('Size of longest consecutive set:', chunks[0].length);

我只想获取连续的最长0的数量,例如:

result: {
  key: 0
  longestConsecutive: 5
}

有什么好的解决方案吗?谢谢!
4个回答

4
你可以使用Array.prototype.reduce来创建一个目标值序列长度的数组,然后使用Math.max来获取该数组中最大的值(即最长序列的长度):

const numbers = [0,0,0,296,296,0,0,296,296,296,0,0,0,0,0,293,293,293,293,293,293,293,293];

function max_consecutive ( arr, value ) {
  return Math.max( ...numbers.reduce( (sequence_lengths, x) => {
      x === value ? sequence_lengths[0]++ : sequence_lengths.unshift(0);
      return sequence_lengths;
    }, [0]
  ) );
}

console.log( max_consecutive(  numbers, 0 ) );
console.log( max_consecutive(  numbers, 1 ) );
console.log( max_consecutive(  numbers, 293 ) );
console.log( max_consecutive(  numbers, 296 ) );


很棒的解决方案。示例中有一个错别字 - 你将arr作为参数,但在函数体中使用了numbers - kbo

2
也许你可以尝试以下操作:

const numbers = [0,0,0,296,296,0,0,296,296,296,0,0,0,0,0,293,293,293,293,293,293,293,293,91];

function findConsecCount(value) {
  
  var startIndex = -1
  var result = 0
  
  for(var i = 0; i < numbers.length; i++) {
    
    if(numbers[i] === value) {
      if(startIndex === -1) {
        startIndex = i
      }
    }
    
    if(numbers[i] !== value) {
      if(startIndex !== -1) {
        result = Math.max(result, i - startIndex)
        startIndex = -1;
      }
    }
  }
      
  if(numbers[numbers.length - 1] === value) {
    if(startIndex !== -1) {
      result = Math.max(result, i - startIndex)
      startIndex = -1;
    }
  }
  
  return {
    key : value, 
    longestConsecutive : result
  }
}

console.log( findConsecCount(0) )
console.log( findConsecCount(293) )
console.log( findConsecCount(296) )
console.log( findConsecCount(91) )


@YukwongTsang 不用谢 - 很高兴我能帮到你 :-) - Dacre Denny

2

您还可以使用reduce按键组合“块”长度,然后对每个键进行sort

const numbers = [0, 0, 0, 296, 296, 0, 0, 296, 296, 296, 0, 0, 0, 0, 0, 293, 293, 293, 293, 293, 293, 293, 293];

let consecutiveGroups = numbers.reduce((acc, curr, i, arr) => {
  if (!(curr in acc)) acc[curr] = [];
  if (arr[i - 1] != curr) acc[curr].push(1);
  else acc[curr][acc[curr].length - 1] += 1;
  return acc;
}, {});

Object.values(consecutiveGroups)
      .forEach(g => g.sort((a, b) => b - a));

console.log(consecutiveGroups);
console.log('longest consecutive 0s', consecutiveGroups[0][0]);
console.log('longest consecutive 296s', consecutiveGroups[296][0]);

[使用长度而不是数字数组的更新灵感来自@Paulpro的绝妙解决方案]


1
我觉得这可能是一个简单的while循环的情况,最容易理解并且应该非常快。它只在数组中运行两个索引,跟踪找到的最长序列:

const numbers = [0, 0, 0, 296, 296, 0, 0, 296, 296, 296, 0, 0, 0, 0, 0, 293, 293, 293, 293, 293, 293, 293, 293];


function longestConsecutive(searchedFor, numbers) {
  let start = stop = longest = 0

  while (start < numbers.length + 1) {
    if (numbers[start] !== searchedFor) {
      longest = start - stop > longest ? start - stop : longest
      stop = start + 1
    }
    start++
  }
  return longest
}

console.log(longestConsecutive(0, numbers))
console.log(longestConsecutive(296, numbers))
console.log(longestConsecutive(293, numbers))


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接