How to recognize a repeating pattern in an array in javascript - javascript

If I have an array like
const arr = [1, 5, 7, 5, 13, 8, 1, 7, 3, 8, 5, 2, 1, 5, 7];
What would be the best way of finding that the array starts to repeat itself? In this instance that the first three numbers and the last three numbers are in a repeating pattern.
This is a random array, the repeating could easily start at index 365 and not necessarily from the first index.
Any ideas?
Thanks in advance

This does what you're looking for...
const arr1 = [1, 5, 7, 5, 13, 8, 1, 7, 3, 8, 5, 2, 1, 5, 7];
const arr2 = [1, 5, 7, 5, 13, 8, 1, 7, 3, 8, 5, 2, 1, 4, 7];
function patternFound(arr) {
var newArray = arr.map(function(o, i) {
if (i < arr.length - 1) {
return arr[i] + "|" + arr[i + 1];
}
})
.sort();
newArray = newArray.filter(function(o, i) {
if (i < arr.length - 1) {
return (o == newArray[i + 1]);
}
});
return newArray.length > 0;
}
console.log(patternFound(arr1));
console.log(patternFound(arr2));
Basically, it creates an array of paired elements from the first array, with a pipe delimiter (["1|5", "5|7", "7|5" etc.]), sorts it and then looks for duplicates by comparing each element to the next.
There's probably a much smaller way of doing this, but I didn't want to spend time making something that was unreadable. This does what you want and does it simply and clearly.
The first array is the one you supplied, and the second has been changed so there's no matching pattern.

You could use a single loop approach with short circuit and a hash table for found pairs like
{
"1|5": true,
"5|7": true,
"7|5": true,
"5|13": true,
"13|8": true,
"8|1": true,
"1|7": true,
"7|3": true,
"3|8": true,
"8|5": true,
"5|2": true,
"2|1": true
}
The iteration stops immediately on index 12 with the other found pair 1|5.
function check(array) {
var hash = Object.create(null);
return array.some(function (v, i, a) {
var pair = [v, a[i + 1]].join('|');
return hash[pair] || !(hash[pair] = true);
});
}
console.log(check([1, 5, 7, 5, 13, 8, 1, 7, 3, 8, 5, 2, 1, 5, 7])); // true
console.log(check([1, 5, 7, 5, 13, 8, 1, 7, 3, 8, 5, 2, 1, 3, 7])); // false

A nested loop seems the simplest approach.
Make sure to offset the nested loop to save calculations:
/**
* Takes array and returns either boolean FALSE or the first index of a pattern
*
* #param {any[]} arr
* #returns {(false | number)}
*/
function findArrayPattern(arr) {
if (arr.length < 2) {
return false;
}
for (var point1 = 0; point1 < arr.length - 2; point1++) {
var p1 = arr[point1];
var p2 = arr[point1 + 1];
for (var point2 = point1 + 2; point2 < arr.length - 1; point2++) {
var p3 = arr[point2];
var p4 = arr[point2 + 1];
if (p1 == p3 && p2 == p4) {
return point1;
}
}
}
return false;
}
//TEST
var arr = [1, 5, 7, 5, 13, 8, 1, 7, 3, 8, 5, 2, 1, 5, 7];
var pattern = findArrayPattern(arr);
if (pattern !== false) {
console.log("a pattern was found at " + pattern);
} else {
console.log("no pattern was found");
}

Related

JS Number of occurences in a sequence is a prime number

I have two arrays (X and Y) and I need to create array Z that contains all elements from array X except those, that are present in array Y p times where p is a prime number.
I am trying to write this in JS.
For Example:
Array X:
[2, 3, 9, 2, 5, 1, 3, 7, 10]
Array Y:
[2, 1, 3, 4, 3, 10, 6, 6, 1, 7, 10, 10, 10]
Array Z:
[2, 9, 2, 5, 7, 10]
So far I have this:
const arrX = [2, 3, 9, 2, 5, 1, 3, 7, 10]
const arrY = [2, 1, 3, 4, 3, 10, 6, 6, 1, 7, 10, 10, 10]
const arrZ = []
const counts = [];
// count number occurrences in arrY
for (const num of arrY) {
counts[num] = counts[num] ? counts[num] + 1 : 1;
}
// check if number is prime
const checkPrime = num => {
for (let i = 2; i < num; i++) if (num % i === 0) return false
return true
}
console.log(counts[10]);
// returns 4
Any hint or help appreciated. Thanks!
You're on the right track. counts should be an object mapping elements in arrY to their number of occurrences. It's easily gotten with reduce.
The prime check needs a minor edit, and the last step is to filter arrX. The filter predicate is just a prime check on the count for that element.
// produce an object who's keys are elements in the array
// and whose values are the number of times each value appears
const count = arr => {
return arr.reduce((acc, n) => {
acc[n] = acc[n] ? acc[n]+1 : 1;
return acc;
}, {})
}
// OP prime check is fine, but should handle the 0,1 and negative cases:
const checkPrime = num => {
for (let i = 2; i < num; i++) if (num % i === 0) return false
return num > 1;
}
// Now just filter with the tools you built...
const arrX = [2, 3, 9, 2, 5, 1, 3, 7, 10]
const arrY = [2, 1, 3, 4, 3, 10, 6, 6, 1, 7, 10, 10, 10]
const counts = count(arrY);
const arrZ = arrX.filter(n => checkPrime(counts[n]));
console.log(arrZ)

Count repeated numbers in array and return true (Cognitive Complexity)

I need to check if a number repeats itself at least three times in an array. How can I refactor it to decrease the Cognitive Complexity that Lint keeps complaining about.
Heres my code:
let array11 = [1, 3, 2, 3, 5, 6, 7, 8, 9, 0, 1];
function checkDuplicateNumber (array11) {
for (let i = 0; i < array11.length; i += 1) {
let sameNumberLoop = 0;
for (let i2 = i; i2 < array11.length; i2 += 1) {
if (array11[i] === array11[i2]) {
sameNumberLoop += 1;
if (sameNumberLoop >= 3) {
return true;
}
}
}
}
}
Instead of iterating multiple times, iterate just once, while counting up the number of occurrences in an object or Map:
let array11 = [1, 3, 2, 3, 5, 6, 7, 8, 9, 0, 1];
function checkDuplicateNumber (array) {
const counts = {};
for (const num of array) {
counts[num] = (counts[num] || 0) + 1;
if (counts[num] === 3) return true;
}
return false;
};
console.log(checkDuplicateNumber(array11));
console.log(checkDuplicateNumber([3, 1, 3, 5, 3]));
let array11 = [1, 3, 2, 3, 5, 6, 7, 8, 9, 0, 1]
let array22 = [1, 3, 2, 3, 5, 6, 7, 1, 9, 0, 1]
function checkDuplicateNumber(arr) {
const map = new Map()
return arr.some((v) => (map.has(v) ? (++map.get(v).count === 3) : (map.set(v, { count: 1 }), false)))
}
console.log(checkDuplicateNumber(array11))
console.log(checkDuplicateNumber(array22))

Find all the same numbers in the array

I have an array with numbers in the range of 0 - 100. I need to find all the same numbers and add 1 to them.
my code worked well with arrays like [100, 2, 1, 1, 0]
const findAndChangeDuplicates = (arr: any) => {
for (let i = arr.length - 1; i >= 0; i--) {
if (arr[i + 1] === arr[i] && arr[i] <= 5) {
arr[i] += 1;
} else if (arr[i - 1] === arr[i] && arr[i] >= 5) {
arr[i] -= 1;
findAndChangeDuplicates(arr);
}
}
return arr;
};
but when I came across this
[100, 6, 6, 6, 5, 5, 5, 5, 5, 4, 4, 4, 3, 3, 2, 2, 2, 2, 1, 1, 0, 0]
my code let me down.
Expected Result:
[100, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Have any ideas?
An approach by using at least one loop from the end to adjust the values and if necessary another loop from the beginning to set the largest value to 100.
Both loops feature a value variable v. In the first loop, it starts with the last value of the array and increments its value and check is the item is smaller than this value.
If smaller, then the value is assigned, otherwise the actual value is taken for the next item.
if necessary, the other loop works in opposite direction and with a start value of 100 and checks if the item is greater than wanted and takes the smaller value, or the value is taken from the item.
The result is an array which has a gereatest value of 100 at start and goes until zero or greater to the end of the array.
function update(array) {
var i = array.length,
v = array[--i];
while (i--) if (array[i] < ++v) array[i] = v; else v = array[i];
if (array[0] > 100) {
v = 100;
for (i = 0; i < array.length; i++) {
if (array[i] > v) array[i] = v; else v = array[i];
v--;
}
}
return array;
}
console.log(update([100, 2, 1, 1, 0]));
console.log(update( [100, 100, 99, 86, 6, 5, 5, 5, 5, 5, 4, 4, 4, 3, 3, 2, 2, 2, 2, 1, 1, 0, 0]))
.as-console-wrapper { max-height: 100% !important; top: 0; }
The following assumes you want them ordered from highest to lowest, if not this might ba as well as useless to you.
The idea is to first create an Object to keep track of how many of each number exist. We then map each value by first checking whether it's unique and if not increasing it until we can't find any value inside the Object anymore. This will not neatly order the numbers by itself so we will have to sort afterwards.
let arr1 = [100, 6, 6, 6, 5, 5, 5, 5, 5, 4, 4, 4, 3, 3, 2, 2, 2, 2, 1, 1, 0, 0],
arr2 = [100, 2, 1, 1, 0];
const f = (arr) => arr.reduce((a,c) => (a[c] = (a[c] || 0) + 1, a),{}),
g = (arr, obj) => arr.map(v => {
if (obj[v] > 1) {
let i = 1;
obj[v] = obj[v] - 1;
while (obj[v + i]) {
i++;
}
obj[v + i] = (obj[v + i] || 0) + 1;
return v + i;
} else {
return v;
}
}).sort((a,b) => +b - +a);
console.log(g(arr1, f(arr1)))
console.log(g(arr2, f(arr2)))
Here is a verbose solution that will work with unordered arrays as well.
It's not efficient, neither brilliant, but it takes care of unordered arrays as well.
Basically, it takes advantage of reduce to collect all the occurrences of each element. Each time it finds more than one, it increases all the occurrences by 1 except the last one.
Next, it checks whether there still are duplicates. If there are, it repeats the process until none is found. Of course, it's not the cleverest approach, but it works.
// Increases all duplicates until there are no more duplicates.
const increaseDuplicates = (arr, index) => {
// Repeat the code until no duplicate is found
while (!noDuplicates(arr)) {
// Acquire all the occurrences of each item, keeping track of the index.
Object.entries(arr.reduce((acc, next, i) => {
acc[next] = acc[next] || [];
return acc[next].push(i), acc;
}, {})).forEach(([n, indexes]) => {
// for each value found, check whether it appears at least twice.
if (indexes.length > 1) {
// if it does, increase the value of every item but the last one.
for (var i = 0; i < indexes.length - 1; i++) {
arr[indexes[i]]++;
}
}
});
}
return arr;
};
// Asserts an array has no duplicates.
const noDuplicates = (arr) => [...new Set(arr)].length === arr.length;
const input = [100, 6, 6, 6, 5, 5, 5, 5, 5, 4, 4, 4, 3, 3, 2, 2, 2, 2, 1, 1, 0, 0];
console.log(increaseDuplicates(input));
const unorderedInput = [6,4,5,6,6,6,6,5,6,3,1,2,3,99,403,100, 6, 6, 6, 5, 5, 5, 5, 5, 4, 4, 4, 3, 3, 2, 2, 2, 2, 1, 1, 0, 0];
console.log(increaseDuplicates(unorderedInput));
You can use a forEach on your array to do this, using the 3rd parameter of the callback, the array itself, and a bit of recursivity
const increment_to_unicity = (value, index, self) => {
if (self.indexOf(value) !== index) {
self[index]++
increment_to_unicity(self[index], index, self)
}
return self[index];
}
arr = arr.map(increment_to_unicity).sort((a, b) => b - a);

Have a big array of integers need to return an array that has 1 added to the value represented by the array

It is for a studying purpose. Have a big array of integers need to return an array that has 1 added to the value represented by the array.
Tried to convert the array into an integer, but after using
parseInt('9223372036854775807', 10) received 9223372036854776000, instead of 9223372036854775807
What is going wrong here?
var arr = [ 9, 2, 2, 3, 3, 7, 2, 0, 3, 6, 8, 5, 4, 7, 7, 5, 8, 0, 7 ];
function upArray(arr){
var numb = arr.join('');
numb = parseInt(numb, 10);
var result = numb + 1;
console.log(result);
result = result.toString(10).split('').map(Number);
return result;
}
You are exceeding the capacity of JavaScript's number type
IEEE-754 double-precision floating point (the kind of number JavaScript uses) can't precisely represent all numbers
Beyond Number.MAX_SAFE_INTEGER + 1 (9007199254740992), the IEEE-754 floating-point format can no longer represent every consecutive integer
also you dont need to use a second argument to parseInt unless you are looking to use a different base than decimal
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
If you use the code with an array of numbers that when joined is within this limit your code will work
var arr = [ 9, 2, 2, 3, 3, 7, 2, 0, 3, 6, 8, 5 ];
function upArray(arr){
var numb = arr.join('');
numb = parseInt(numb);
var result = numb + 1;
console.log(result)
result = result.toString(10).split('').map(Number);
return result;
}
console.log(upArray(arr))
As you're exceeding the MAX_SAFE_INTEGER.
If you just want to display you can go this way
var arr = [ 9, 2, 2, 3, 3, 7, 2, 0, 3, 6, 8, 5, 4, 7, 7, 5, 8, 0, 7 ];
function addone(arr){
let carry = 0;
for(let i=arr.length-1; i>=0; i--){
if(i === arr.length-1) {
if( arr[i]+1 > 9){
arr[i] = 10-(arr[i] + 1);
carry = 1;
} else {
arr[i] +=1;
carry= 0;
}
}
if( i !== arr.length-1 ){
if( carry === 0) break;
if( arr[i]+1+carry > 9){
arr[i] = 10-(arr[i] + carry);
carry = 1;
} else {
arr[i] +=carry;
carry= 0;
}
}
}
if(carry === 1)
arr.unshift(1)
return arr;
}
console.log(addone(arr).join(''))
console.log(addone([1,2,9]).join(''))
console.log(addone([9,9,9]).join(''))
The value is going beyond the max number value.
Here is recursive appproch for the problem:
function upArray(arr, lastIndex){
if(lastIndex == undefined){
lastIndex = arr.length - 1;
}
if(lastIndex < 0){
return;
}
if(arr[lastIndex] == 9){
arr[lastIndex] = 0;
upArray(arr, lastIndex - 1);
}
else {
arr[lastIndex] = arr[lastIndex] + 1;
}
return arr;
}
var arr = [ 9, 2, 2, 3, 3, 7, 2, 0, 3, 6, 8, 5, 4, 7, 7, 5, 8, 0, 9];
var result = upArray(arr);
console.log(result);
Another solution so you can choice =)
var arr = [9,9,9];//[ 9, 2, 2, 3, 3, 7, 2, 0, 3, 6, 8, 5, 4, 7, 7, 5, 8, 0, 7 ];
var i = arr.length;
var append = true;
while(append){
if(--i < 0){
arr.unshift(1);
break;
}
var v = arr[i];
if(++v >= 10)
v -= 10;
else
append = false;
arr[i] = v;
}
var r = arr.join('');
console.log(r);
it means the maximum range for an Intiger number has reached, here is a link
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
to solve this split the array value and add one to it and then combine then back and display the entire array as a String (don't parse it).
function upArray(arr){
var temp = arr;
var len = arr.length;
var temp2 = arr;
temp2 = temp2.slice(0,len/2).join('');
temp2 = parseInt(temp2);
temp = temp.slice(len/2).join('');
numb = parseInt(temp) +1;
if(numb.toString().length > (len/2 + len%2))
{
numb = numb.toString().slice(1);
temp2++;
}
var result = temp2.toString() + numb.toString();
console.log(result);
result = result.split('').map(Number);
return result;
}
hope it helps and have pass through every test...
As everybody would agree that the issue here is having a value that is exceeding the capacity of JavaScript's number type, we can expect that there'll be proposed workarounds like having to split the array into multiple array and work from there.
We can actually solve this on another approach. Since your representation of a number is splitting it into single digits stored as an array, and you want to perform a simple addition on it, we can observe a representation of a simple/elementary addition. The one where we add a value digit by digit from the bottom and make use of the "Carry Over" concept. We can actually do it that way.
It will look somewhat like this (A bit longer code for readability):
var x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var y = [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9];
var add1 = (arr) => {
var hasCarryOver = true;
for (var index = arr.length - 1; index >= 0; index--) {
if (!hasCarryOver) {
break;
}
if (arr[index] < 9) {
arr[index] = arr[index] + 1;
hasCarryOver = false;
} else {
arr[index] = 0;
}
}
if (hasCarryOver) {
arr.unshift(1);
}
return arr;
};
x = add1(x);
y = add1(y);
console.log('result x add 1', x);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 9, 0]
console.log('result y add 1', y);
// [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

How to remove repeated entries from an array while preserving non-consecutive duplicates?

I have an array like var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4, 5, 5, 5]; I really want the output to be [5,2,9,4,5]. My logic for this was:
Go through all the element one by one.
If the element is the same as the prev element, count the element and do something like newA = arr.slice(i, count)
New array should be filled with just identical elements.
For my example input, the first 3 elements are identical so newA will be like arr.slice(0, 3) and newB will be arr.slice(3,5) and so on.
I tried to turn this into the following code:
function identical(array){
var count = 0;
for(var i = 0; i < array.length -1; i++){
if(array[i] == array[i + 1]){
count++;
// temp = array.slice(i)
}else{
count == 0;
}
}
console.log(count);
}
identical(arr);
I am having problems figuring out how to output an element that represents a group of element that are identical in an array. If the element isn't identical it should be outputted in the order that it is in in the original array.
Using array.filter() you can check if each element is the same as the one before it.
Something like this:
var a = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4, 5, 5, 5];
var b = a.filter(function(item, pos, arr){
// Always keep the 0th element as there is nothing before it
// Then check if each element is different than the one before it
return pos === 0 || item !== arr[pos-1];
});
document.getElementById('result').innerHTML = b.join(', ');
<p id="result"></p>
if you are looking purely by algorithm without using any function
var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4, 5, 5, 5];
function identical(array){
var newArray = [];
newArray.push(array[0]);
for(var i = 0; i < array.length -1; i++) {
if(array[i] != array[i + 1]) {
newArray.push(array[i + 1]);
}
}
console.log(newArray);
}
identical(arr);
Fiddle;
Yet another way with reduce
var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4, 5, 5, 5];
var result = arr.reduce(function(acc, cur) {
if (acc.prev !== cur) {
acc.result.push(cur);
acc.prev = cur;
}
return acc;
}, {
result: []
}).result;
document.getElementById('d').innerHTML = JSON.stringify(result);
<div id="d"></div>
A bit hackey, but, hell, I like it.
var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4, 5, 5, 5];
var arr2 = arr.join().replace(/(.),(?=\1)/g, '').split(',');
Gives you
[5,2,9,4,5]
Admittedly this will fall down if you're using sub-strings of more than one character, but as long as that's not the case, this should work fine.
Try this:
var a = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4, 5, 5, 5];
uniqueArray = a.filter(function(item, pos) {
return a.indexOf(item) == pos;
});
See Remove Duplicates from JavaScript Array

Categories

Resources