我有一个数组
arr = [1,2,3,4,6,7,8,9]
现在我想检查数组中的值是否连续。
更具体,我想要这个
First Check给出第一个和第二个元素是连续的,下一个元素不连续,然后algo必须返回连续数字开始的第一个元素
喜欢
First Check will give 1
Second Check will give 6
and so on...
请帮忙 提前致谢
答案 0 :(得分:5)
/**
* Given an array of number, group algebraic sequences with d=1
* [1,2,5,4,8,11,14,13,12] => [[1,2],[4,5],[8],[11,12,13,14]]
*/
import {reduce, last} from 'lodash/fp';
export const groupSequences = (array) => (
reduce((result, value, index, collection) => {
if (value - collection[index - 1] === 1) {
const group = last(result);
group.push(value);
} else {
result.push([value]);
}
return result;
}, [])(array)
);
答案 1 :(得分:3)
一个侧面是你想多次调用它,所以每个调用应该知道它正在处理哪个数组以及该数组中的前一个offset
是什么。您可以做的一件事是扩展本机Array
对象。的 [Demo] 强>
Array.prototype.nextCons = (function () {
var offset = 0; // remember the last offset
return function () {
var start = offset, len = this.length;
for (var i = start + 1; i < len; i++) {
if (this[i] !== this[i-1] + 1) {
break;
}
}
offset = i;
return this[start];
};
})();
<强>用法强>
var arr = [1,2,3,4,6,8,9];
arr.nextCons(); // 1
arr.nextCons(); // 6
arr.nextCons(); // 8
答案 2 :(得分:1)
/**
* Given an array of number, group algebraic sequences with d=1
* [1,2,3,4,5,6] => true
* [1,2,4,5,6] => false
*/
const differenceAry = arr.slice(1).map(function(n, i) { return n - arr[i]; })
const isDifference= differenceAry.every(value => value == 1)
console.log(isDifference);
答案 3 :(得分:0)
伪代码:
int count = 0
for i = 0 to array.length - 2
if {array[i + 1] - array[i] = 1 then
count+=1
return i
else count=0}
答案 4 :(得分:0)
const array1 = [1,2,3];
const sum = array1.reduce((accumulator, currentValue) =>{
return accumulator + currentValue;
});
const max = Math.max(...array1);
maximum = max
if(sum == maximum * (maximum+1) /2) {
console.log(true);
} else {
console.log(false);
}
答案 5 :(得分:0)
检查数组中的所有数字是否连续:
const allConsecutives = (arr) =>{
return arr.every((num, i)=> (arr[i+1]||num+1)-num === 1)
}