首页 > 解决方案 > 从数组javascript验证条件序列

问题描述

我有一个数组[1,2,3,4,5,6,7,8,9,10,11,12,13]

现在我正在创建一个函数,如果输入是否为有效序列,则返回该函数,但我有一些需要解决的异常。

  1. 输入将始终以排序方式。
  2. 函数应该返回真或假。
  3. 输入长度应 > 3 且 < 14。从(数字 1 到 13)

例子。

例外。

例外是如果有1并且有序列我想返回true。有1-13的循环,13附在1上

这是我尝试过的,(不适用于异常)

function isvalid(array) {
    if (array.length < 3) return false;
    return array.every((e, i) => i === 0 || (e - 1 === array[i - 1]));
}

console.log(isvalid([1,11,12,13])) // false , should return true

标签: javascriptarraysjson

解决方案


您可以通过查看第一个索引或所有其他索引来采取分阶段的方法,执行与下一个元素或最后一个元素相关的检查。

它检查,如果有

  • 前一项加等于实际项,或
  • 实际项目加一等于下一个项目,或
  • 索引为 0 或 1,第一个元素为0,数组的最后一个为13

function isConsecutive(array) {
    return array.every((v, i, a) =>
        a[i - 1] + 1 === v ||
        v + 1 === a[1] ||
        i < 2 && a[0] === 1 && a[a.length - 1] === 13
    );
}

console.log(isConsecutive([1, 2, 3]));                 //  true
console.log(isConsecutive([1, 2, 3, 4, 5]));           //  true
console.log(isConsecutive([8, 9, 10, 11]));            //  true
console.log(isConsecutive([11, 12, 13]));              //  true
console.log(isConsecutive([1, 11, 12, 13]));           //  true
console.log(isConsecutive([1, 8, 9, 10, 11, 12, 13])); //  true
console.log(isConsecutive([1, 4, 5, 6]));              // false
console.log(isConsecutive([1, 3, 4, 5]));              // false
console.log(isConsecutive([2, 11, 12, 13]));           // false
.as-console-wrapper { max-height: 100% !important; top: 0; }


推荐阅读