javascript - 从数组javascript验证条件序列
问题描述
我有一个数组[1,2,3,4,5,6,7,8,9,10,11,12,13]
。
现在我正在创建一个函数,如果输入是否为有效序列,则返回该函数,但我有一些需要解决的异常。
- 输入将始终以排序方式。
- 函数应该返回真或假。
- 输入长度应 > 3 且 < 14。从(数字 1 到 13)
例子。
- [1,2,3] - 真
- [1,2,3,4,5] - 真
- [8,9,10,11] - 真
- [11,12,13] - 真
例外。
[1,11,12,13] - 真
[1,8,9,10,11,12,13] - 真
[1,4,5,6] - 错误
[1,3,4,5] - 错误
例外是如果有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
解决方案
您可以通过查看第一个索引或所有其他索引来采取分阶段的方法,执行与下一个元素或最后一个元素相关的检查。
它检查,如果有
- 前一项加一等于实际项,或
- 实际项目加一等于下一个项目,或
- 索引为 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; }
推荐阅读
- autohotkey - 如何使用 AHK 检测用户输入的所有特殊按钮:
- r - 在忽略 NA 的同时合并列
- python - os.system 直到在 python 中输入才起作用
- python - 为什么standardscaler在不同数量的特征下效果不同
- java - java - 如何在java removeIf中流式传输已删除的项目?
- json - JSON解析器允许字符串中的换行符?
- python - Python - 如何四舍五入到指定的小数
- python - 如果多个实例处于活动状态,Python 子进程命令不会等待
- spring-batch - 我的弹簧批处理步骤在达到构建后一直循环
- python - 通知时未从喙回调中获取所有字节