顺子号:1,2,3,4,5或许9,0,1,2,3,4或许7,8,9,0,1之类的
工作中写的谁人另有bug,晚上研讨了下终究写出个没有bug的要领,分享下,假如看到这篇文章另有更好方法的迎接交换,共同进步。
function checkShunzi(arr) {
arr = arr.sort();
if (arr.indexOf(0) != -1 && arr.indexOf(9) != -1) {
let arr0 = []; //0这边的数组比方[0,1,2,3,8,9]->[1,2,3]
let arr9 = []; //9这边的数组比方[0,1,2,3,7,8,9]->[7,8]
//只需arr0和arr9是顺子而且长度总和即是arr.length-2,或许arr9的长度即是arr.length-1那末数组arr就是顺子
for (let i = 0; i < arr.length - 2; i++) {
let j = i + 1;
if (arr[j] - arr[i] == 1) {
arr0.push(arr[j]);
} else {
break;
}
}
for (let i = arr.length - 1; i > -1; i--) {
let j = i - 1;
if (arr[i] - arr[j] == 1) {
arr9.unshift(arr[j]);
} else {
break;
}
}
return isShunNum(arr0) && isShunNum(arr9) && ((arr.length - 2 - arr0.length == arr9.length) || arr9.length == arr.length - 1); //arr0.length==arr.length-1,[0,1,2,3,4,5,6,7,8,9]的状况
}
function isShunNum(arr) {
return arr.every(function (item, index, arr) {
return 0 === index || (Number(item) + 10 - 1) % 10 == arr[index - 1];
})
}
return isShunNum(arr);
}