![](/img/trans.png)
[英]check if atleast 4 consecutive array elements are same — javascript
[英]check if elements in array are consecutive — javascript
我有一個數組
arr = [1,2,3,4,6,7,8,9]
現在我想檢查數組中的值是否連續。
更具體地說,我想要這個
First Check 給出第一個和第二個元素是連續的,而下一個元素不連續,那么算法必須從連續數字開始的地方返回第一個元素
喜歡
First Check will give 1
Second Check will give 6
and so on...
請幫助提前致謝
/**
* 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)
);
一個旁注是您想多次調用它,因此每次調用都應該知道它正在處理哪個數組以及該數組中的前一個offset
是多少。 您可以做的一件事是擴展本機Array
對象。 [演示]
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
/**
* 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);
檢查數組中的所有數字是否都是連續的:
const allConsecutives = (arr) =>{
return arr.every((num, i)=> (arr[i+1]||num+1)-num === 1)
}
偽代碼:
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}
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.