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

时间:2018-11-05 02:36:48

标签: javascript

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

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 个答案:

答案 0 :(得分:2)

也许您可以执行以下操作:

gammaincc

答案 1 :(得分:2)

您可以使用Array.prototype.reduce为目标值创建一个序列长度的数组,然后使用Math.max获取该数组中的最大值(这是最长序列的长度):< / p>

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 ) );

答案 2 :(得分: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出色​​的解决方案的启发]

答案 3 :(得分: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))