首页 > 解决方案 > 将数组中缺少的连续数字打印为范围

问题描述

我想在范围内显示数组中未显示的数字,该数组包含范围从 1 到 128 的数字。

例如对于数组 [87,89,90,91,92,93,94,95,96,97,99]

我要打印 1-86、88、98、100-128

我写了一个函数,只有在第一个未使用的数字和最后一个数字中间没有数字时才有效

function PrintPorts(ports) {
  var portString = "";
  var open = true;
  let index = 1
  for (; index < 129; index++) {
    for (let j = 0; j < ports.length; j++) {
      if (index == ports[j]) {
        open = false;
        break;
      } else
        open = true;

    }
    if (open) {
      portString += index;
      break;
    }
  }
  for (; index < 129; index++) {
    for (let j = 0; j < ports.length; j++) {
      if (index == ports[j]) {
        open = false;
        break;
      } else
        open = true;
    }
    if (!open) {
      portString += "-" + (index - 1) + ",";
    }
  }
  if (index == 129 && open) portString += "-" + (index - 1);
  return portString;
}

console.log(PrintPorts([87,89,90,91,92,93,94,95,96,97,99]));

这是示例数组的结果 1-86,-88,-89,-90,-91,-92,-93,-94,-95,-96,-98,-128

当我需要的是 1-86, 88, 98, 100-128

任何帮助表示赞赏

标签: javascriptarraysloops

解决方案


首先,通过使用该includes()方法来测试数组是否包含元素来简化您的代码。

然后,用嵌套循环来做。外部循环查找范围的开始。当它找到它时,内部循环会查找范围的结尾。测试 start 和 end 是否相同,以决定是输出一个数字还是输出两个数字-之间的数字。

生成逗号分隔字符串的最佳方法是将结果放入数组中,然后join()在末尾使用将它们连接起来。

function PrintPorts(ports) {
  var openPorts = [];
  for (let index = 1; index < 129; index++) {
    if (!ports.includes(index)) {
      let startPort = index;
      for (index = startPort + 1; index < 129; index++) {
        if (ports.includes(index)) {
          break;
        }
      }
      let endPort = index - 1;
      openPorts.push(startPort == endPort ? startPort : `${startPort}-${endPort}`);
    }
  }
  return openPorts.join(",");
}

console.log(PrintPorts([87, 89, 90, 91, 92, 93, 94, 95, 96, 97, 99]));
console.log(PrintPorts([1, 2, 87, 89, 90, 91, 92, 93, 94, 95, 96, 97, 99, 120, 128]));


推荐阅读