Find element that appears odd number of times - javascript

I'm trying to solve this exercise of finding the number that appears an odd number of times in an array. I have this so far but the output ends up being an integer that appears an even number of times. For example, the number 2 appears 3 times and the number 4 appears 6 times, but the output is 4 because it counts it as appearing 5 times. How can it be that it returns the first set that it finds as odd? Any help is appreciated!
function oddInt(array) {
var count = 0;
var element = 0;
for(var i = 0; i < array.length; i++) {
var tempInt = array[i];
var tempCount = 0;
for(var j = 0; j <array.length; j++) {
if(array[j]===tempInt) {
tempCount++;
if(tempCount % 2 !== 0 && tempCount > count) {
count = tempCount;
element = array[j];
}
}
}
}
return element;
}
oddInt([1,2,2,2,4,4,4,4,4,4,5,5]);

function findOdd(numbers) {
var count = 0;
for(var i = 0; i<numbers.length; i++){
for(var j = 0; j<numbers.length; j++){
if(numbers[i] == numbers[j]){
count++;
}
}
if(count % 2 != 0 ){
return numbers[i];
}
}
};
console.log(findOdd([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5])); //5
console.log(findOdd([1,1,1,1,1,1,10,1,1,1,1])); //10

First find the frequencies, then find which ones are odd:
const data = [1,2,2,2,4,4,4,4,4,4,5,5]
const freq = data.reduce(
(o, k) => ({ ...o, [k]: (o[k] || 0) + 1 }),
{})
const oddFreq = Object.keys(freq).filter(k => freq[k] % 2)
// => ["1", "2"]

If we are sure only one number will appear odd number of times, We can XOR the numbers and find number occurring odd number of times in n Comparisons.XOR of two bits is 1 if they are different else it will be 0. Truth table is below.
A B A^B
0 0 0
0 1 1
1 0 1
1 1 0
So when we do XOR of all the numbers, final number will be the number appearing odd number of times.
Let's take a number and XOR it with the same number(Appearing two times). Result will be 0 as all the bits will be same. Now let's do XOR of result with same number. Now result will be that number because all the bits of previous result are 0 and only the set bits of same number will be set in the result. Now expanding it to an array of n numbers, numbers appearing even number of times will give result 0. The odd appearance of the number result in that number in the final result.
func oddInt(numbers: [Int]) -> Int {
var result = 0
for aNumber in numbers {
result = result ^ aNumber
}
return result
}

Here is a solution with O(N) or O(N*log(N))
function findOdd(A) {
var count = {};
for (var i = 0; i < A.length; i++) {
var num = A[i];
if (count[num]) {
count[num] = count[num] + 1;
} else {
count[num] = 1;
}
}
var r = 0;
for (var prop in count) {
if (count[prop] % 2 != 0) {
r = prop;
}
}
return parseInt(r); // since object properies are strings
}

#using python
a=array('i',[1,1,2,3,3])
ans=0
for i in a:
ans^=i
print('The element that occurs odd number of times:',ans)
List item
output:
The element that occurs odd number of times: 2
Xor(^)operator when odd number of 1's are there,we can get a 1 in the output
Refer Xor Truth table:
https://www.electronicshub.org/wp-content/uploads/2015/07/TRUTH-TABLE-1.jpg

function oddInt(array) {
// first: let's count occurences of all the elements in the array
var hash = {}; // object to serve as counter for all the items in the array (the items will be the keys, the counts will be the values)
array.forEach(function(e) { // for each item e in the array
if(hash[e]) hash[e]++; // if we already encountered this item, then increments the counter
else hash[e] = 1; // otherwise start a new counter (initialized with 1)
});
// second: we select only the numbers that occured an odd number of times
var result = []; // the result array
for(var e in hash) { // for each key e in the hash (the key are the items of the array)
if(hash[e] % 2) // if the count of that item is an odd number
result.push(+e); // then push the item into the result array (since they are keys are strings we have to cast them into numbers using unary +)
}
return result;
}
console.log(oddInt([1, 2, 2, 2, 4, 4, 4, 4, 4, 4, 5, 5]));
Return only the first:
function oddInt(array) {
var hash = {};
array.forEach(function(e) {
if(hash[e]) hash[e]++;
else hash[e] = 1;
});
for(var e in hash) { // for each item e in the hash
if(hash[e] % 2) // if this number occured an odd number of times
return +e; // return it and stop looking for others
}
// default return value here
}
console.log(oddInt([1, 2, 2, 2, 4, 4, 4, 4, 4, 4, 5, 5]));

That happens because you are setting the element variable each time it finds an odd number, so you are setting it when it find one, three and five 4.
Let's check the code step by step:
function oddInt(array) {
// Set the variables. The count and the element, that is going to be the output
var count = 0;
var element = 0;
// Start looking the array
for(var i = 0; i < array.length; i++) {
// Get the number to look for and restart the tempCount variable
var tempInt = array[i];
var tempCount = 0;
console.log("");
console.log(" * Looking for number", tempInt);
// Start looking the array again for the number to look for
for(var j = 0; j <array.length; j++) {
// If the current number is the same as the one that we are looking for, sum it up
console.log("Current number at position", j, "is", array[j]);
if(array[j]===tempInt) {
tempCount++;
console.log("Number found. Current count is", tempCount);
// Then, if currently there are an odd number of elements, save the number
// Note that you are calling this altough you don't have looped throgh all the array, so the console will log 3 and 5 for the number '4'
if(tempCount % 2 !== 0 && tempCount > count) {
console.log("Odd count found:", tempCount);
count = tempCount;
element = array[j];
}
}
}
}
return element;
}
oddInt([1,2,2,2,4,4,4,4,4,4,5,5]);
What we want to do is to check for the count AFTER looping all the array, this way:
function oddInt(array) {
// Set the variables. The count and the element, that is going to be the output
var count = 0;
var element = 0;
// Start looking the array
for(var i = 0; i < array.length; i++) {
// Get the number to look for and restart the tempCount variable
var tempInt = array[i];
var tempCount = 0;
console.log("");
console.log(" * Looking for number", tempInt);
// Start looking the array again for the number to look for
for(var j = 0; j <array.length; j++) {
// If the current number is the same as the one that we are looking for, sum it up
console.log("Current number at position", j, "is", array[j]);
if(array[j]===tempInt) {
tempCount++;
console.log("Number found. Current count is", tempCount);
}
}
// After getting all the numbers, then we check the count
if(tempCount % 2 !== 0 && tempCount > count) {
console.log("Odd count found:", tempCount);
count = tempCount;
element = tempInt;
}
}
return element;
}
oddInt([1,2,2,2,4,4,4,4,4,4,5,5]);
By the way, this is only for you to understand where was the problem and learn from it, although this is not the most optimized way of doing this, as you may notice that you are looking for, let's say, number 2 three times, when you already got the output that you want the first time. If performance is part of the homework, then you should think another way :P

This is because your condition if(tempCount % 2 !== 0 && tempCount > count) is true when the 5th 4 is checked. This updates the count and element variables.
When the 6th 4 is checked, the condition is false.
To fix, move the condition outside the innermost loop so that it's checked only after all the numbers in the array are counted.

function oddInt(array, minCount, returnOne) {
minCount = minCount || 1;
var itemCount = array.reduce(function(a, b) {
a[b] = (a[b] || 0) + 1;
return a;
}, {});
/*
itemCount: {
"1": 1,
"2": 3,
"4": 6,
"5": 2,
"7": 3
}
*/
var values = Object.keys(itemCount).filter(function(k) {
return itemCount[k] % 2 !== 0 && itemCount[k]>=minCount;
});
return returnOne?values[0]:values;
}
var input = [1, 2, 2, 2, 4, 4, 4, 4, 4, 4, 5, 5, 7, 7, 7];
console.log(oddInt(input, 3, true));
console.log(oddInt(input, 1, true));
console.log(oddInt(input, 2, false));

"A" is the array to be checked.
function findOdd(A) {
var num;
var count =0;
for(i=0;i<A.length;i++){
num = A[i]
for(a=0;a,a<A.length;a++){
if(A[a]==num){
count++;
}
} if(count%2!=0){
return num;
}
}
}

function oddOne (sorted) {
let temp = sorted[0];
let count = 0;
for (var i = 0; i < sorted.length; i++) {
if (temp === sorted[i]) {
count++;
if (i === sorted.length - 1) {
return sorted[i];
}
} else {
if (count % 2 !== 0) {
return temp;
}
count = 1;
temp = sorted[i];
}
}
}

function oddInt(array) {
let result = 0;
for (let element of array) {
result ^= element
}
return result
}

var oddNumberTimes = (arr) => {
let hashMap = {};
for (let i = 0; i < arr.length; i++) {
hashMap[arr[i]] = hashMap[arr[i]] + 1 || 1;
}
for (let el in hashMap) {
if (hashMap[el] % 2 !== 0) {
return el;
}
}
return -1;
};

You can use bitwise XOR:
function oddInt(array) {
return array.reduce(function(c, v) {
return c ^ v;
}, 0);
}
console.log(oddInt([20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5]) == 5);
console.log(oddInt([1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 1]) == 10);

Had to implement a solution for a similar problem and here it is:
function findtheOddInt(A) {
let uniqueValues = [...new Set(A)]; // Get the unique values from array A
const odds = [];
uniqueValues.forEach(element => {
const count = A.reduce((acc, cur) => cur === element ? acc + 1: acc, 0) // count the occurrences of the element in the array A
if (count % 2 === 1) {
odds.push(element);
}
});
return odds[0]; // Only the first odd occurring element
}

var arr=[1,2,2,2,2,3,4,3,3,3,4,5,5,9,9,10];
var arr1=[];
for(let i=0;i
{
var count=0;
for(let j=0;j<arr.length;j++)
{
if(arr[i]==arr[j])
{
count++;
}
}
if(count%2 != 0 )
{
arr1.push(arr[i]);
}
}
console.log(arr1);

Related

Javascript codewars : Tribonacci Sequence

function tribonacci(signature, n) {
var myArray = [];
var lenArray = 0;
var i = 0;
var outPut = 0;
var x = 0;
if (n > 0) {
while (i < 3) {
myArray.push(signature[i]);
i++;
}
lenArray = myArray.length - 1;
i = 0;
while (lenArray < n) {
while (x < 3) {
var v = x + i;
outPut += myArray[v];
x++;
}
i++;
lenArray = myArray.length - 1;
myArray.push(outPut);
}
return myArray;
} else {
return [];
};
}
console.log(tribonacci([1, 1, 1], 10));
First, I tried to push first 3 items into "myArray".
Second, in the "while" loop, while it's less than "n" (number of items needed to be in the array), add the last 3 items in "myArray" until "myArray" reaches the needed "n" amount.
e.g. tribonacci([1,1,1],10)
Return should be [1,1,1,3,5,9,17,31,57,105]
Adding the last 3 items continuously until it reaches 10 items in an array.
Instead I get as result:
[1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3]
I have no idea why it's stuck on 3s.
I tried "i++" below the 2nd "while" loop so that it can start adding the last 3 items every time "myArray" grows by one, but that doesn't seem to be the issue. Is the "outPut" being stuck on 3?
var v = x + i; uses x to calculate the correct index.
After adding those 3 numbers, x needs to be reset.
Also, outPut is reused in the next iteration, but it keeps adding values, so your output will get to high. This needs to be reset to 0 after the 3-loop.
Add outPut = x = 0 after pushing outPut into myArray
function tribonacci(signature, n) {
var myArray = [];
var lenArray = 0;
var i = 0;
var outPut = 0;
var x = 0;
if (n > 0) {
while (i < 3) {
myArray.push(signature[i]);
i++;
}
lenArray = myArray.length - 1;
i = 0;
while (lenArray < n) {
while (x < 3) {
var v = x + i;
outPut += myArray[v];
x++;
}
i++;
lenArray = myArray.length - 1;
myArray.push(outPut);
outPut = x = 0
}
return myArray;
} else {
return [];
};
}
console.log(tribonacci([1, 1, 1], 10));
[
1,
1,
1,
3,
5,
9,
17,
31,
57,
105,
193,
355
]
Some bonus-tips to improve the readabilty:
Use (...) spread operator to replace the first while:
var myArray = [ ...signature ];
Use myArray.length - 1 instead off defining a variable with the same value
Use myArray[x + i] instead off defining another varible
Return on n < 0 to you don't need to intent that much
Applying those will give:
function tribonacci(signature, n) {
var myArray = [ ...signature ];
var i = 0;
var x = 0;
var outPut = 0;
if (n < 0) {
return [];
}
while ((myArray.length - 1) < n) {
while (x < 3) {
outPut += myArray[x + i];
x++;
}
i++;
myArray.push(outPut);
outPut = x = 0;
}
return myArray;
}
Hey there are you doing this for homework on while loops? If so refer to #0stone0 's answer which solves it right!
If on the other hand you want to dive into JS a little more, I'd suggest you a more coincise solution with some cool Array function:
function tribonacci(signature, size) {
const output = signature;
while(output.length < size) {
output.push(output.slice(-3).sum());
}
return output;
}
console.log({ result: tribonacci([1, 1, 1], 10) });
Some version of JS don't include the Array.sum function which would be something like this:
Array.prototype.sum = function() {
return this.reduce((sum, curr) => sum + curr, 0);
}

Max consecutive items of numbers in array with +1 difference

I am trying to return the max number of consecutive numbers or same numbers which difference is no more than + 1.
Example*
const array = [1,2,3,5,5,6,6,6,6,7,8]
solution= 556666
const array2 = [2,2,3,4,4,5,5]
solution= 4455
I am a new coder and seems like there should be a simpler way to solve this but I am stuck at this point.
function getMaximumNumberItems(arr) {
let initial = {'0': 0, '1':0, '2':0, '3':0, '4':0, '5':0, '6':0, '7':0, '8':0, '9':0 }
let counts = {}
arr.forEach((element) => {
counts[element] = (counts[element] || 0) + 1
})
const numbers = {...initial,...counts}
const arrValues = Object.values(numbers)
let sum = []
for (let i = 0; i < arrValues.length; i++) {
arrValues[i] === arrValues[arrValues.length - 1] ? null : sum.push(arrValues[i] + arrValues[i + 1])
}
console.log(sum)
let maxIndex = sum.indexOf(Math.max(...sum))
}
What I have done is set a count for each number which is numbers, then I add each element with next element to see the max number of elements that are consecutive and add them to an array which is sum. The index of this maximum number should also be the index of the first element that should be returned from counts.
Mi idea was to return key from object and access how many times this number has appeared and add it some way and then use next element of numbers the same way to get the solution.
Obviously I see that this is the worst way of doing it, so would appreciate any help.
Thanks!
You can do it in O(n) time. Take number, match all numbers after that, which difference with it is 1 or smaller. If you find number, which difference is bigger, than 1, then you need to remember the current result and repeat the previous steps, fixing the number of the element from which the best sequence begins and its length.
function maxSubsequence(array) {
let ind = 0;
let bestInd = 0;
let cnt = 1;
let maxCnt = 0;
for (let i = 1; i < array.length; i++) {
if (Math.abs(array[ind] - array[i]) <= 1) {
cnt++;
} else {
if(cnt > maxCnt) {
bestInd = ind;
maxCnt = cnt;
}
cnt = 1;
ind = i;
}
}
if (cnt > maxCnt) {
bestInd = ind;
maxCnt = cnt;
}
return array.slice(bestInd, bestInd + maxCnt);
}
Output:
maxSubsequence(array)
[5, 5, 6, 6, 6, 6]
maxSubsequence(array2)
[4, 4, 5, 5]

how do i find the mode of an array of integers

it is a scenario where a use inputs an array of integers and it returns the most frequent integer.
it is tested 3 times but will fail once, whether its the 1st 2nd or 3rd test.
function arrayMode(array) {
if (array.length === 0) {
return null;
}
var sequence = {};
var maxNo = array[3],
maxCount = 3;
for (var i = 0; i < array.length; i++) {
var Entry = array[i];
if (sequence[Entry] === null)
sequence[Entry] = -1;
else
sequence[Entry]++;
if (sequence[Entry] > maxCount) {
maxNo = Entry;
maxCount = sequence[Entry];
} else if (sequence[Entry] == maxCount) {
maxNo += '&' + Entry;
maxCount = sequence[Entry - 1];
}
return maxNo;
}
}
console.log(arrayMode([1, 3, 3, 3, 1])) // output = 3
console.log(arrayMode([1, 2, 3, 1, 1])) // output = 1
console.log(arrayMode([2, 2, 2, 1])) // output = 2
I think there are several mistakes, if you find an entry not seen previously you set the sequence for that entry to -1, why not 1?
And you initialize maxNo to array[3] and maxCount to 3, why?
Does this make more sense to you?
function arrayMode(arr)
{
var mode = null;
var frequencies = [];
var maxFrequency = 0;
for (var i in arr)
{
var value = arr[i];
// if we haven't seen this value before, init its frequency to 0
if (frequencies[value]===undefined) frequencies[value] = 0;
// increase this value's frequency
frequencies[value]++;
// if this value's frequency is bigger than the max we've seen
// so far, this value is now the new mode.
if (frequencies[value] > maxFrequency)
{
maxFrequency = frequencies[value];
mode = value;
}
}
return mode;
}
If you want to return all modi in case there are more than one entries with the max number of frequencies (for example if for [1,1,2,3,3] you want the mode to be 1 & 3) then you can do so by a simple extra loop at the end.

Find indexes of those elements that would equal to the x after adding their values

So I've got an array that looks something like this:
var x = 17;
var arr = [{ value:2, quantity: 4 }, { value:8, quantity: 1 }, { value:3, quantity: 3 }];
My question is how can I find indexes of those elements that would equal to the x number after adding their values. In this case the return would be:
[1, 3, 3, 3]
Of course it could be also done with [0, 0, 0, 1, 2] or [0, 0, 0, 0, 2, 2, 2] but the lower length of returned array the better.
There's more efficient ways of doing this but this is a very obvious / clean solution. We're going to treat this like a linear equation where combo contains the coefficients for each value in arr:
// your initial x and arr
var x = 17;
var arr = [{ value:2, quantity: 4 }, { value:8, quantity: 1 }, { value:3, quantity: 3 }];
// maximums[i] is the maximum amount of arr[i]'s you can ever
// have in any combination
var maximums = arr.map(function(item){ return Math.floor(x / item.value) });
// an array of the current coefficients we're trying. combo[i]
// corresponds to the coefficient for arr[i]
// we will start off with all coefficients set to 0 and
// increase each one by 1 as we go along
var combo = arr.map(function(){ return 0 });
// the sum we get with the current coefficients
var sum = 0;
// take the current coefficients in combo and try the next
// coefficient from left-to-right, we know when to stop
// trying to increase a given coefficient when it exceeds
// its corresponding value in the maximums array
function next() {
for(var i = 0; i < combo.length; i++) {
combo[i]++;
// we increased the coeff. so increase the sum
sum += arr[i].value;
if(combo[i] <= maximums[i]) {
// the coefficient is smaller/equal to its max size, so we're done
break;
}else{
// we've maxed out the right most coeff. so bail
if(i == combo.length-1) return false;
// reset this coefficient, remove it from sum & cont. loop
sum -= arr[i].value * combo[i];
combo[i] = 0;
}
}
return true;
}
// now we just enumerate all combinations until the sum equals x
while(next()) {
if(sum == x) break;
}
// if no combination is found, abort
if(sum != x) {
console.log('not possible');
// otherwise print the combination that works
}else{
for(var i = 0; i < combo.length; i++) {
if(combo[i] == 0) continue;
console.log(combo[i] + ' of (' + JSON.stringify(arr[i]) + ')');
}
}
and if you always want the smallest possible combination, you can do this:
function coeffsUsed() {
var count = 0;
for(var i = 0; i < combo.length; i++) {
if(combo[i] > 0) count++;
}
return count;
}
// now we just enumerate all combinations until the sum equals x
var smallestCombo = {};
var smallest = -1;
while(next()) {
if(sum == x) {
var count = coeffsUsed();
if(smallest == -1 || count < smallest) {
smallest = count;
smallestCombo = combo.slice(0); // clones the array
}
}
}
// if no combination is found, abort
if(smallest == -1) {
console.log('not possible');
// otherwise print the combination that works
}else{
for(var i = 0; i < smallestCombo.length; i++) {
if(smallestCombo[i] == 0) continue;
console.log(smallestCombo[i] + ' of (' + JSON.stringify(arr[i]) + ')');
}
}

Find if Array Contains 5 consecutive Numbers with Javascript

I have a sorted Array that contains numbers. I want to be able to check if this Array(or similar Array), contains 5 numbers in consecutive order.
NOTE: Array may contain duplicate and double digit numbers.
I am trying this, but failing epically.
var array = [1,3,5,7,7,8,9,10,11]
var current = null;
var cnt = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] != current) {
if (cnt > 4) {
return true;
}
current = array[i];
cnt = 1;
} else {
cnt++;
}
}
if (cnt > 4) {
return true;
}
}
An iterative, straightforward approach would be:
var should_be_true = [1,3,5,7,7,8,9,10,11];
var should_be_false = [1,3,5,7,9,11,13,15,17];
var testArray = function(array) {
var conseq = 1;
for (var idx = 1; idx < array.length ; idx++) {
if (array[idx] == array[idx-1] + 1)
conseq++;
else
conseq = 1;
if (conseq == 5)
return true;
}
return false;
}
console.log(testArray(should_be_true)); //true
console.log(testArray(should_be_false)); //false
But for bonus fun, here's one variation on a functional approach, returning the position where the sequence starts, or -1 if no sufficiently long sequence exists:
should_be_true.map(function(curr,idx,arr) {
return (curr == arr[idx-1] +1) ? 1 : 0;
}).join('').search(/1{4}/);
A functional approach would be
function fiveInARow(array) {
// compare if one element is greater than or equal to the previous one
function compare(elt, i, arr) { return !i || elt >= arr[i-1]; });
// check if at a given position, every one of the last five comparisons is true
function check (_, i, greaters) {
return i >= 4 && greaters.slice(i-4, i) . every(Boolean);
}
return array . map(compare) . some(check);
}
The logic here is to first create an array of booleans using map, showing whether each element is greater than or equal to the previous. That yields an array such as [true, true, true, false, true].
The some part asks, for any element, is it the case that that element and every one of the preceding four elements are true? If so, it returns true.
Recursive solution
A recursive solution might be a bit easier to read.
function fiveInARow(array) {
return function _five(array, prev, n) {
if (n >= 5) return true;
if (!array.length) return false;
var next = array.shift();
return _five(array, next, next === prev ? n : next >= prev ? n+1 : 0);
}(array, -999999, 5);
}
var array = [1,3,5,7,7,8,9,10,11];
var cons=false;
var count=0;
for(i=0;i<array.length;i++){
if(array[i]+1==array[i+1]){
count++;
}
else{
count=0;
}
if(count==4){
cons=true;
}
}
if(cons){
//do what you want with it
}
DEMO
a more elegant way would be to define this whole thing in a function as below:
function checkCons(array){
var cons=false;
var count=0;
for(i=0;i<array.length;i++){
if(array[i]+1==array[i+1]){
count++;
}
else{
count=0;
}
if(count==4){
cons=true;
}
}
return cons;
}
and then using it like this:
var array = [1,3,5,7,7,8,9,10,11];
if(checkCons(array)){
//do what you want with it
}
DEMO
function fiveStraight() {
var array = [1, 3, 5, 7, 7, 8, 9, 10, 12];
var prev = array[0];
var numberOfStraight = 1;
for (var i = 1; i < array.length; i++) {
numberOfStraight = array[i] === prev + 1 ? numberOfStraight + 1 : 1;
prev = array[i];
if (numberOfStraight === 5) return true;
}
return false;
}
JSFIDDLE.
Here is what I found out to be the most straight forwards approach. Both descending and ascending values count as consecutive (if that's not your case, then fiddle with the Math.abs() call).
function consecutiveValuesCount(array) {
// sort the values if not pre-sorted
var sortedValues = array.sort();
// the result variable / how many consecutive numbers did we find?
// there's always atleast 1 consecutive digit ...
var count = 1;
for (var i = 0; i < sortedValues.length - 1; i++) {
// both descending and ascending orders count as we are using Math.abs()
if (Math.abs(sortedValues[i] - sortedValues[i+1]) == 1) {
++count;
}
}
return count;
}
//input
var array = [1,2,4,5,3];
// output
5
with this code you can find the highest number of consecutives for a given number or find the highest number of consecutives in general
var findMaxConsecutiveOnes = function (arr, number) {
//check for boundries
if(!number || !arr.length) return;
// maximum number of consectuives
let max = 0;
// count homy many consecutives before it ends (why it's 1 ? because a lonely number is still counted)
let counter = 1;
// you can ignore the next 2 variable if you want to use for loop instead of while
let length = arr.length;
let i = 1; // counting from index 1 because we are checking against index-1
while (i < length) {
if (arr[i] == arr[i - 1]) {
// boom, we have a consecutive, count it now
counter++;
} else {
// rest to 1
counter = 1;
}
// always update the max variable to the new max value
max = Math.max(counter, max);
//for the sake of iteration
i++;
}
return max== number;
};
console.log(findMaxConsecutiveOnes([5, 5, 5, 1, 1, 1, 1, 1]));
cnt will only increase once, when it hits the two 7s.
Put the incrementing line in the truthy condition, and the reset line in the else statement.
// Put into a function for testing.
function foo() {
var array = [1, 3, 5, 7, 7, 8, 9, 10, 11]
var current = null;
var cnt = 0;
for (var i = 0; i < array.length; i++) {
// Also need to make sure the next array item is a consecutive increase.
if (array[i] != current && array[i] === array[i-1] + 1) {
if (cnt > 4) {
return true;
}
current = array[i];
cnt++;
} else {
cnt = 1;
}
}
if (cnt > 4) {
return true;
} else {
return false;
}
};
// Call function.
alert(foo());

Categories