首页 > javascript > 查找数组中连续数字的所有范围

查找数组中连续数字的所有范围 (Find all ranges of consecutive numbers in array)

问题

给定一组排序的数字,你如何获得连续数字的范围?该函数应将范围和单个数字作为字符串返回。例:

function findRanges(arrayOfSortedNumbers) {
  // logic here
}

findRanges([1, 3, 4, 5, 7]) => (expected output: "1, 3-5, 7")

findRanges([1, 2, 3, 5]) => (expected output: "1-3, 5")

findRanges([2, 3, 4, 5, 6]) => (expected output: "2-6")

很抱歉无法更好地解释问题。

解决方法

你可以Array.reduce()用来做:

  1. 对阵列进行排序(安全)
  2. 迭代数组,reduce创建一个包含ranges活动范围(rangeStart)的起始对象的对象。
  3. 在第一次迭代中,推送范围中的第一个元素并将此元素另存为 rangeStart
  4. 在连续迭代中,如果值等于最后一个值+ 1,则我们处于相同的范围内,因此我们通过更改ranges数组中的最后一个值来更新它。否则,我们将ranges数组中的元素推送并更新rangeStart为此元素。
  5. 返回ranges对象输出的属性,reduce并使用逗号连接它。

function findRanges(numbers) {
  return [...numbers].sort((a, b) => a - b).reduce((acc, x, i) => {
    if (i === 0) {
      acc.ranges.push(x);
      acc.rangeStart = x;
    } else {
      if (x === acc.last + 1) {
        acc.ranges[acc.ranges.length-1] = acc.rangeStart + '-' + x;
      } else {
        acc.ranges.push(x);
        acc.rangeStart = x;
      }
    }
    acc.last = x;
    return acc;
  }, { ranges: [] }).ranges.join(', ');
}

console.log(findRanges([1, 3, 4, 5, 7]));
console.log(findRanges([1, 2, 3, 5]));
console.log(findRanges([2, 3, 4, 5, 6]));


问题

Given a sorted array of numbers, how do you get ranges of consecutive numbers? The function should return ranges and single numbers as a string. Example:

function findRanges(arrayOfSortedNumbers) {
  // logic here
}

findRanges([1, 3, 4, 5, 7]) => (expected output: "1, 3-5, 7")

findRanges([1, 2, 3, 5]) => (expected output: "1-3, 5")

findRanges([2, 3, 4, 5, 6]) => (expected output: "2-6")

Sorry for not being able to explain the problem better.

解决方法

You can use Array.reduce() to do it:

  1. Sort the array (safety)
  2. Iterate over the array with reduce to create an object containing the ranges and the start of the active range (rangeStart).
  3. On the first iteration, push the first element in the ranges and save this element as the rangeStart
  4. On the successive iterations, if the value equals the last value + 1, we are in the same range, so we update it by changing the last value in the ranges array. Otherwise, we push the element in the ranges array and update rangeStart to be this element.
  5. Return the ranges property of the object output by reduce and join it using commas.

function findRanges(numbers) {
  return [...numbers].sort((a, b) => a - b).reduce((acc, x, i) => {
    if (i === 0) {
      acc.ranges.push(x);
      acc.rangeStart = x;
    } else {
      if (x === acc.last + 1) {
        acc.ranges[acc.ranges.length-1] = acc.rangeStart + '-' + x;
      } else {
        acc.ranges.push(x);
        acc.rangeStart = x;
      }
    }
    acc.last = x;
    return acc;
  }, { ranges: [] }).ranges.join(', ');
}

console.log(findRanges([1, 3, 4, 5, 7]));
console.log(findRanges([1, 2, 3, 5]));
console.log(findRanges([2, 3, 4, 5, 6]));

相似信息