The task:
You are given 3 sorted arrays. You should find the smallest number
that is common in all 3 arrays and return it. If such a number doesn't
exist, return -1
My approach:
Use early exit: If one of the array is empty, then we know there won't be a common number in all arrays
Create pointer that points to the first element of the corresponding array
In the outer loop, loop through all elements of the first array. If any of the pointer over reaches the end of the array, then break the loop because we have reached the end and haven't found a common number
In the first inner loop check the second array for the element the pointer of the first array is pointing to
If you found it then set a flag. Otherwise remember the running index to the second pointer so we can continue at this element in the next iteration
If the flag is set, then loop through the second inner loop. In here it's analogous to the first inner loop: Search for the current element in the 3rd array.
If you find it, then immediately return the value. If not go to the next element until you find an element bigger than the current one
Increment the pointer of the first array
Do this until you reach either one of the array
My Solution:
let findLeastCommonNumber = function(a, b, c) {
if (a.length === 0 || b.length === 0 || c.length === 0) {
return -1;
}
let aPointer = 0;
let bPointer = 0;
let cPointer = 0;
while (aPointer < a.length ||
bPointer < b.length ||
cPointer < c.length) {
const aValue = a[aPointer];
let bFound = false;
for (let i = bPointer; i < b.length; i++) {
if (b[i] === aValue) {
bPointer = i;
bFound = true;
break;
}
if (b[i] > aValue) {
bPointer = i;
break;
}
}
if (bFound) {
for (let i = cPointer; i < c.length; i++) {
if (c[i] === aValue) {
return a[aPointer];
}
if (c[i] > aValue) {
cPointer = i;
break;
}
}
}
aPointer++;
}
return -1;
};
Sample solution:
let find_least_common_number = function(a, b, c) {
let i = 0;
let j = 0;
let k = 0;
while (i < a.length
&& j < b.length
&& k < c.length) {
// Finding the smallest common number
if (a[i] === b[j]
&& b[j] === c[k]) {
return a[i];
}
// Let's increment the iterator
// for the smallest value.
if (a[i] <= b[j]
&& a[i] <= c[k]) {
i++;
} else if (b[j] <= a[i]
&& b[j] <= c[k]) {
j++;
} else if (c[k] <= a[i]
&& c[k] <= b[j]) {
k++;
}
}
return -1;
};
I like the fact that the sample solution has less nesting. But the sample solution doesn't take advantage of an early exit and I think my solution is more scalable. Let's say the requirements changes, and 27 arrays more are now included. In my solution, I'd just copy the inner loops and change the pointer names only. I don't need to touch existing code. In the sample solution, however, I'd have touch every line of code that refers to one of the arrays and I would add the new arrays there. What do you think?
You could a completely dynamic approach for an infinite (sort of) count of arrays.
function findLeastCommonNumber(...array) {
var indices = array.map(_ => 0),
smallest = Math.max(...array.map((a, i) => a[indices[i]])),
next;
while (indices.every((i, j) => i < array[j].length)) {
next = smallest;
array.forEach((a, i) => {
while (indices[i] < a.length && a[indices[i]] < smallest)
next = Math.max(next, a[++indices[i]]);
});
if (array.every((a, i) => a[indices[i]] === smallest)) return smallest;
smallest = next;
}
return -1;
}
console.log(findLeastCommonNumber([1, 2, 3, 4, 5, 7], [8, 9, 10], [1, 2, 3, 5, 6, 7, 9]));
console.log(findLeastCommonNumber([1, 2, 3, 4, 5, 7, 9, 10], [1, 2, 3, 5, 6, 7, 9, 10], [4, 6, 7, 8, 9, 10, 11, 12]));
console.log(findLeastCommonNumber([1, 5, 6, 7, 8, 10], [5, 6, 9, 10], [1, 2, 3, 4, 5, 6, 9, 10]));
For the more readable solution, you can use this:
const findLeastCommonNumber = function() {
const total = [].concat(...arguments).sort((a,b) => a > b ? 1 : -1);
let index = 0;
let commonNumber = -1;
while(total.length - 2 > index && commonNumber === -1){
if(total[index] === total[index + 1] && total[index] === total[index + 2]){
commonNumber = total[index];
}
index++;
}
return commonNumber;
};
console.log(findLeastCommonNumber([1,5,6,7,8,10],[5,6,9,10],[1,2,3,4,5,6,9,10]));
An alternative solution - Take the 1st array, and convert the other arrays to Sets. Now use Array.find() on the 1st array, and check with Array.every() if the current number is found in all sets.
const findLeastCommonNumber = (main, ...array) => {
const sets = array.map(o => new Set(o));
const common = main.find(n => sets.every(s => s.has(n)));
return common === undefined ? -1 : common;
};
console.log(findLeastCommonNumber([1, 2, 3, 4, 5, 7], [8, 9, 10], [1, 2, 3, 5, 6, 7, 9]));
console.log(findLeastCommonNumber([1, 2, 3, 4, 5, 7, 9, 10], [1, 2, 3, 5, 6, 7, 9, 10], [4, 6, 7, 8, 9, 10, 11, 12]));
console.log(findLeastCommonNumber([1, 5, 6, 7, 8, 10], [5, 6, 9, 10], [1, 2, 3, 4, 5, 6, 9, 10]));
The arrays are sorted in ascending order. We will use three
iterators simultaneously to traverse each of the arrays. We can
start traversing each array from the 0^{th}index, which always has
the smallest value.
If the values pointed to by the three iterators are equal, that is
the solution. Since the arrays are sorted in ascending order, that
value must be the smallest value present in all of the arrays.
Otherwise, we see which of the three iterators points to the
smallest value and increment that iterator so that it points to the
next index.
If any of the three iterators reaches the end of the array before
we find the common number, we return -1.
let findLeastCommonNumber = function(arr1, arr2, arr3) {
// Initialize starting indexes for arr1, arr2 and arr3
let i = 0;
let j = 0;
let k = 0;
// Iterate through three arrays
while (i < arr1.length && j < arr2.length && k < arr3.length) {
// Finding the smallest common number
if (arr1[i] === arr2[j] && arr2[j] === arr3[k]) {
return arr1[i];
}
// Let's increment the iterator
// for the smallest value.
if (arr1[i] <= arr2[j] && arr1[i] <= arr3[k]) {
i++;
}
else if (arr2[j] <= arr1[i] && arr2[j] <= arr3[k]) {
j++;
}
else if (arr3[k] <= arr1[i] && arr3[k] <= arr2[j]) {
k++;
}
}
return -1;
};
let v1 = [6, 7, 10, 25, 30, 63, 64];
let v2 = [0, 4, 5, 6, 7, 8, 50];
let v3 = [1, 6, 10, 14];
console.log("Least Common Number: " + findLeastCommonNumber(v1, v2, v3));
Related
Say I have 2 arrays like this:let x = [1,3,4,7,10] and another array like this let y = [0,4,6,9,12]
How would I check if there's any value in the arrays separated by a 1? For example, 3 from the first array, and 4 from the second array. These are separated by one, so it returns true. I'm looking for it to return a boolean value. To clear up any doubts, the Array IS sorted but not always the same length or sometimes even empty, and the other values also count, I just used one of the values.
This approach iterates both arrays but needs sorted arrays.
On iterating it takes the smaller values first, despite of the array.
If two values are found who have a delta of one, the function check returns true otherwise false.
function check(a, b) {
let i = 0,
j = 0;
do {
console.log(a[i], b[j]);
if (a[i] + 1 === b[j] || a[i] === b[j] + 1) return true;
if (a[i] <= b[j] && i + 1 < a.length) i++;
else j++;
} while (j < b.length)
return false;
}
console.log(check([1, 3, 4, 7, 10], [0, 4, 6, 9, 12])); // true
console.log(check([1, 2, 3, 4, 5], [6, 9, 12, 13, 14])); // true
console.log(check([6, 9, 12, 13, 14], [1, 2, 3, 4, 5])); // true
console.log(check([1, 2, 3, 4, 5], [7, 9, 12, 13, 14])); // false
console.log(check([7, 9, 12, 13, 14], [1, 2, 3, 4, 5])); // false
console.log(check([3, 4], [3]));
console.log(check([3], [3, 4]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
The best I can think of is
Eliminate all duplicates in both arrays (not worth it if you're iterating over small arrays)
For each item of the first array check if there is an item in the second array, whose value's absolute difference from the item selected from the first array is 1.
If there is such an item, you straight away return true
If no items follow those conditions, return false
An implementation of that in JS should look something like that:
function eliminateDuplicates(arr) {
return arr.filter((v, i) => arr.indexOf(v) === i);
// Removes every single item that has a different indexOf index than its own
// This is a clever technique i found on https://medium.com/dailyjs/how-to-remove-array-duplicates-in-es6-5daa8789641c
}
function anyItemsWithDiffrence1(arr1, arr2, eliminateDuplicates) {
if (eliminateDuplicates) {
arr1 = eliminateDuplicates(arr1);
arr2 = eliminateDuplicates(arr2);
}
for (let i = 0; i < arr1.length; i++) {
for (let j = 0; j < arr2.length; j++) {
if (Math.abs(arr[i] - arr[j]) === 1) return true;
// We check if the absolute difference between the two items is 1
}
}
return false;
}
Question has been moved to CodeReview: https://codereview.stackexchange.com/questions/154804/find-a-list-of-objects-in-an-array-with-javascript
Having an array of objects - such as numbers - what would be the most optimal (Memory and CPU efficiency) way if finding a sub group of objects? As an example:
demoArray = [1,2,3,4,5,6,7]
Finding [3,4,5] would return 2, while looking for 60 would return -1.
The function must allow for wrapping, so finding [6,7,1,2] would return 5
I have a current working solution, but I'd like to know if it could be optimized in any way.
var arr = [
1,
5,2,6,8,2,
3,4,3,10,9,
1,5,7,10,3,
5,6,2,3,8,
9,1]
var idx = -1
var group = []
var groupSize = 0
function findIndexOfGroup(g){
group = g
groupSize = g.length
var beginIndex = -2
while(beginIndex === -2){
beginIndex = get()
}
return beginIndex
}
function get(){
idx = arr.indexOf(group[0], idx+1);
if(idx === -1 || groupSize === 1){
return idx;
}
var prevIdx = idx
for(var i = 1; i < groupSize; i++){
idx++
if(arr[getIdx(idx)] !== group[i]){
idx = prevIdx
break
}
if(i === groupSize - 1){
return idx - groupSize + 1
}
}
return -2
}
function getIdx(idx){
if(idx >= arr.length){
return idx - arr.length
}
return idx
}
console.log(findIndexOfGroup([4,3,10])) // Normal
console.log(findIndexOfGroup([9,1,1,5])) // Wrapping
You could use the reminder operator % for keeping the index in the range of the array with a check for each element of the search array with Array#every.
function find(search, array) {
var index = array.indexOf(search[0]);
while (index !== -1) {
if (search.every(function (a, i) { return a === array[(index + i) % array.length]; })) {
return index;
}
index = array.indexOf(search[0], index + 1);
}
return -1;
}
console.log(find([3, 4, 5], [1, 2, 3, 4, 5, 6, 7])); // 2
console.log(find([6, 7, 1, 2], [1, 2, 3, 4, 5, 6, 7])); // 5
console.log(find([60], [1, 2, 3, 4, 5, 6, 7])); // -1
console.log(find([3, 4, 5], [1, 2, 3, 4, 6, 7, 3, 4, 5, 9])); // 6
.as-console-wrapper { max-height: 100% !important; top: 0; }
My take on the problem is to use slice() and compare each subarray of length equal to the group's length to the actual group array. Might take a bit long, but the code is short enough:
// The array to run the tests on
var arr = [
1,
5, 2, 6, 8, 2,
3, 4, 3, 10, 9,
1, 5, 7, 10, 3,
5, 6, 2, 3, 8,
9, 1
];
// Check arrays for equality, provided that both arrays are of the same length
function arraysEqual(array1, array2) {
for (var i = array1.length; i--;) {
if (array1[i] !== array2[i])
return false;
}
return true;
}
// Returns the first index of a subarray matching the given group of objects
function findIndexOfGroup(array, group) {
// Get the length of both arrays
var arrayLength = array.length;
var groupLength = group.length;
// Extend array to check for wrapping
array = array.concat(array);
var i = 0;
// Loop, slice, test, return if found
while (i < arrayLength) {
if (arraysEqual(array.slice(i, i + groupLength), group))
return i;
i++;
}
// No index found
return -1;
}
// Tests
console.log(findIndexOfGroup(arr,[4,3,10])); // Normal
console.log(findIndexOfGroup(arr,[9,1,1,5])); // Wrapping
console.log(findIndexOfGroup(arr,[9,2,1,5])); // Not found
If the group is longer than the array, some errors might occur, but I leave it up to you to extend the method to deal with such situations.
I need to find first two numbers and show index like:
var arrWithNumbers = [2,5,5,2,3,5,1,2,4];
so the first repeated number is 2 so the variable firstIndex should have value 0. I must use for loop.
var numbers = [7, 5, 7, 6, 6, 4, 9, 10, 2, 11];
var firstIndex
for (i = numbers[0]; i <= numbers.length; i++) {
firstIndex = numbers[0]
if (numbers[i] == firstIndex) {
console.log(firstIndex);
break;
}
}
You can use Array#indexOf method with the fromIndex argument.
var numbers = [7, 5, 7, 6, 6, 4, 9, 10, 2, 11];
// iterate upto the element just before the last
for (var i = 0; i < numbers.length - 1; i++) {
// check the index of next element
if (numbers.indexOf(numbers[i], i + 1) > -1) {
// if element present log data and break the loop
console.log("index:", i, "value: ", numbers[i]);
break;
}
}
UPDATE : Use an object to refer the index of element would make it far better.
var numbers = [7, 5, 7, 6, 6, 4, 9, 10, 2, 11],
ref = {};
// iterate over the array
for (var i = 0; i < numbers.length; i++) {
// check value already defined or not
if (numbers[i] in ref) {
// if defined then log data and brek loop
console.log("index:", ref[numbers[i]], "value: ", numbers[i]);
break;
}
// define the reference of the index
ref[numbers[i]] = i;
}
Many good answers.. One might also do this job quite functionally and efficiently as follows;
var arr = [2,5,5,2,3,5,1,2,4],
frei = arr.findIndex((e,i,a) => a.slice(i+1).some(n => e === n)); // first repeating element index
console.log(frei)
If might turn out to be efficient since both .findIndex() and .some() functions will terminate as soon as the conditions are met.
You could use two for loops an check every value against each value. If a duplicate value is found, the iteration stops.
This proposal uses a labeled statement for breaking the outer loop.
var numbers = [1, 3, 6, 7, 5, 7, 6, 6, 4, 9, 10, 2, 11],
i, j;
outer: for (i = 0; i < numbers.length - 1; i++) {
for (j = i + 1; j < numbers.length; j++) {
if (numbers[i] === numbers[j]) {
console.log('found', numbers[i], 'at index', i, 'and', j);
break outer;
}
}
}
Move through each item and find if same item is found on different index, if so, it's duplicate and just save it to duplicate variable and break cycle
var numbers = [7, 5, 7, 6, 6, 4, 9, 10, 2, 11];
var duplicate = null;
for (var i = 0; i < numbers.length; i++) {
if (numbers.indexOf(numbers[i]) !== i) {
duplicate = numbers[i];
break; // stop cycle
}
}
console.log(duplicate);
var numbers = [7, 5, 7, 6, 6, 4, 9, 10, 2, 11];
var map = {};
for (var i = 0; i < numbers.length; i++) {
if (map[numbers[i]] !== undefined) {
console.log(map[numbers[i]]);
break;
} else {
map[numbers[i]] = i;
}
}
Okay so let's break this down. What we're doing here is creating a map of numbers to the index at which they first occur. So as we loop through the array of numbers, we check to see if it's in our map of numbers. If it is we've found it and return the value at that key in our map. Otherwise we add the number as a key in our map which points to the index at which it first occurred. The reason we use a map is that it is really fast O(1) so our overall runtime is O(n), which is the fastest you can do this on an unsorted array.
As an alternative, you can use indexOf and lastIndexOf and if values are different, there are multiple repetition and you can break the loop;
function getFirstDuplicate(arr) {
for (var i = 0; i < arr.length; i++) {
if (arr.indexOf(arr[i]) !== arr.lastIndexOf(arr[i]))
return arr[i];
}
}
var arrWithNumbers = [2, 5, 5, 2, 3, 5, 1, 2, 4];
console.log(getFirstDuplicate(arrWithNumbers))
var numbers = [1, 3, 6, 7, 5, 7, 6, 6, 4, 9, 10, 2, 11]
console.log(getFirstDuplicate(numbers))
I have the same task and came up with this, pretty basic solution:
var arr = [7,4,2,4,5,1,6,8,9,4];
var firstIndex = 0;
for(var i = 0; i < arr.length; i++){
for( var j = i+1; j < arr.length; j++){
if(arr[i] == arr[j]){
firstIndex = arr[i];
break;
}
}
}
console.log(firstIndex);
First for loop takes the first element from array (number 7), then the other for loop checks all other elements against it, and so on.
Important here is to define j in second loop as i+1, if not, any element would find it's equal number at the same index and firstIndex would get the value of the last one after all loops are done.
To reduce the time complexity in the aforementioned answers you can go with this solution:
function getFirstRecurringNumber(arrayOfNumbers) {
const hashMap = new Map();
for (let number of arrayOfNumbers) { // Time complexity: O(n)
const numberDuplicatesCount = hashMap.get(number);
if (numberDuplicatesCount) {
hashMap.set(number, numberDuplicatesCount + 1);
continue;
}
hashMap.set(number, 1); // Space complexity: O(n)
}
for (let entry of hashMap.entries()) { // Time complexity: O(i)
if (entry[1] > 1) {
return entry[0];
}
}
}
// Time complexity: O(n + i) instead of O(n^2)
// Space complexity: O(n)
Using the code below, I am able to get just the first '5' that appears in the array. the .some() method stops looping through once it finds a match.
let james = [5, 1, 5, 8, 2, 7, 5, 8, 3, 5];
let onlyOneFives = [];
james.some(item => {
//checking for a condition.
if(james.indexOf(item) === 0) {
//if the condition is met, then it pushes the item to a new array and then
//returns true which stop the loop
onlyOneFives.push(item);
return james.indexOf(item) === 0;
}
})
console.log(onlyOneFives)
Create a function that takes an array with numbers, inside it do the following:
First, instantiate an empty object.
Secondly, make a for loop that iterates trough every element of the array and for each one, add them to the empty object and check if the length of the object has changed, if not, well that means that you added a element that already existed so you can return it:
//Return first recurring number of given array, if there isn't return undefined.
const firstRecurringNumberOf = array =>{
objectOfArray = {};
for (let dynamicIndex = 0; dynamicIndex < array.length; dynamicIndex ++) {
const elementsBeforeAdding = (Object.keys(objectOfArray)).length;0
objectOfArray[array[dynamicIndex]] = array[dynamicIndex]
const elementsAfterAdding = (Object.keys(objectOfArray)).length;
if(elementsBeforeAdding == elementsAfterAdding){ //it means that the element already existed in the object, so it didnt was added & length doesnt change.
return array[dynamicIndex];
}
}
return undefined;
}
console.log(firstRecurringNumberOf([1,2,3,4])); //returns undefined
console.log(firstRecurringNumberOf([1,4,3,4,2,3])); //returns 4
const arr = [1,9,5,2,3,0,0];
const copiedArray = [...arr];
const index = arr.findIndex((element,i) => {
copiedArray.splice(0,1);
return copiedArray.includes(element)
})
console.log(index);
var addIndex = [7, 5, 2, 3, 4, 5, 7,6, 2];
var firstmatch = [];
for (var i = 0; i < addIndex.length; i++) {
if ($.inArray(addIndex[i], firstmatch) > -1) {
return false;
}
firstmatch.push(addIndex[i]);
}
I wanted to write a function to find a contiguous subarray within a given array from a given starting index and return the index of the subarray within the array if it's found, and -1 if it's not found. This is similar to String.indexOf, but for arrays and subarrays instead of strings and substrings.
This is my working code:
var find_csa = function (arr, subarr, from_index) {
if (typeof from_index === 'undefined') {
from_index = 0;
}
var i, found, j;
for (i = from_index; i < 1 + (arr.length - subarr.length); ++i) {
found = true;
for (j = 0; j < subarr.length; ++j) {
if (arr[i + j] !== subarr[j]) {
found = false;
break;
}
}
if (found) return i;
}
return -1;
};
And these are my tests and their expected values:
console.log(find_csa([1, 2, 3, 4, 5], [2, 3, 4]) === 1);
console.log(find_csa([1, 2, 3, 4, 5], [5]) === 4);
console.log(find_csa([1, 2, 3, 4, 5], [1, 3]) === -1);
console.log(find_csa([1, 2, 3, 4, 5], [42]) === -1);
console.log(find_csa([1, 2, 3, 4, 5], []) === 0);
console.log(find_csa([3, 4, 3, 4, 3, 4], [3, 4, 3], 1) === 2);
console.log(find_csa([6, 6, 6, 7], [6, 6, 7]) === 1);
console.log(find_csa([12, 9, 16, 42, 7, 866, 3], [16, 42, 7, 866]) === 2);
My code passes the tests, but as you can see, it uses a boolean value found in the inner loop which is just my messy, ad-hoc way of continuing an outer loop from a nested loop. is there a cleaner way of writing it? I looked into Array.prototype.findIndex but it is an experimental technology at the moment so I can't use it. I want a method that works in most browsers. I know there is a "polyfill" code snippet written on the Mozilla page, but that is even longer than my current code and it will be slower due to the function calls, so I'd rather avoid it.
My primary goal for this function is performance (the subarrays will be very small, so I believe that using Boyer-Moore string search algorithm or tries is a tad overkill), and then my secondary goal is elegance of my implementation. With those two goals in mind, I would like to know if there is a better way of writing this code, or if there are any JavaScript features or functions that I'm missing that could help me avoid the found boolean.
JSFiddle if it helps anyone: http://jsfiddle.net/qc4zxq2p/
Are there any JavaScript features or functions that I'm missing that could help me avoid the found boolean
Yes, you can use a label on your outer loop:
function find_csa(arr, subarr, from_index) {
var i = from_index >>> 0,
sl = subarr.length,
l = arr.length + 1 - sl;
loop: for (; i<l; i++) {
for (var j=0; j<sl; j++)
if (arr[i+j] !== subarr[j])
continue loop;
return i;
}
return -1;
}
This is the same as yours, just prettified a bit (at least to my aesthetics):
var find_csa = function (arr, subarr, from_index) {
from_index = from_index || 0;
var i, found, j;
var last_check_index = arr.length - subarr.length;
var subarr_length = subarr.length;
position_loop:
for (i = from_index; i <= last_check_index; ++i) {
for (j = 0; j < subarr_length; ++j) {
if (arr[i + j] !== subarr[j]) {
continue position_loop;
}
}
return i;
}
return -1;
};
The inner loop can be reduced to a single line using the array method every:
if(subarr.every(function(e, j) { return (e === arr[i + j]); })
return i;
or (ES6 proposal):
if(subarr.every( (e, j) => (e === arr[i + j]) ))
return i;
But this may be just a curiosity or educational example, unless you don't care about performance.
Inside your loop, you can eliminate the found variable and avoid continue like this:
for (j = 0; j < subarr.length; ++j) {
if (arr[i + j] !== subarr[j]) break;
}
/*
* the above loop breaks in two cases:
* normally: j === subarr.length
* prematurely: array items did not match
* we are interested in kowing if loop terminated normally
*/
if (j === subarr.length) return i;
Having said that, here is my solution using Array.join and String.indexOf. This is only good for array of Numbers:
function find_csa(arr, subarr, from_index) {
from_index |= 0;
if (subarr.length === 0) {
return from_index;
}
var haystack = "," + arr.slice(from_index).join(",") + ",",
needle = "," + subarr.join(",") + ",",
pos = haystack.indexOf(needle);
if (pos > 0) {
pos = haystack.substring(1, pos).split(",").length + from_index;
}
return pos;
}
console.log("All tests should return true");
console.log(find_csa([1, 2, 3, 4, 5], [1, 2, 3]) === 0);
console.log(find_csa([1, 2, 3, 4, 5], [2, 3, 4]) === 1);
console.log(find_csa([1, 2, 3, 4, 5], [5]) === 4);
console.log(find_csa([1, 2, 3, 4, 5], [6]) === -1);
console.log(find_csa([1, 2, 3, 4, 5], [1, 3]) === -1);
console.log(find_csa([6, 6, 6, 7], [6, 6, 7]) === 1);
console.log(find_csa([1, 2, 3, 4, 5], []) === 0);
console.log(find_csa([3, 4, 3, 4, 3, 4], [3, 4, 3], 1) === 2);
console.log(find_csa([1, 2, 3, 4, 5], [], 1) === 1);
Reading initial discussion based on zerkms proposition, I was interested to try a solution using JSON.stringify, despite the unfavorable opinions.
Then I finally got a solution, which passes all tests properly.
Probably not the faster method, but surely the shortest one:
var find_csa = function (arr, subarr, from_index) {
var start=from_index|0,
needle=JSON.stringify(subarr),
matches=JSON.stringify(arr.slice(start)).
match(new RegExp('^\\[(.*?),?'+
needle.substr(1,needle.length-2).replace(/([\[\]])/g,'\\$1')
));
return !!matches?(matches[1].length?matches[1].split(',').length:0)+start:-1;
}
The above code accepts arrays of arrays, as suggested by Shashank, but fails to process items containing commas.
So I developped another solution which also accepts commas (thanks to Steven Levithan for the elegant tip about while(str!=(str=str.replace(regexp,replacement)));).
But it is only for fun, since:
the code is not so short, now... Sigh!
it probably consumes a lot of CPU time
it doesn't properly work with empty items (they are ignored)
I suspect (and didn't dig deeper :-) it might fail with complex objects as items
Anyway, here is it:
var find_csa = function (arr, subarr, from_index) {
var start=from_index|0,
commas=new RegExp('(?:(\')([^,\']+),([^\']+)\'|(")([^,"]+),([^"]+))"'),
strip_commas='$1$2$3$1$4$5$6$4',
haystack=JSON.stringify(arr.slice(start)),
needle=JSON.stringify(subarr).replace(/^\[(.*)\]$/,'$1');
while(haystack!=(haystack=haystack.replace(commas,strip_commas)));
while(needle!=(needle=needle.replace(commas,strip_commas)));
matches=haystack.match(new RegExp('^\\[(.*?),?'+needle.replace(/([\[\]])/g,'\\$1')));
return !!matches?(matches[1].length?matches[1].split(',').length:0)+start:-1;
}
i fixed this question with this code:
getCount(arr)
{
const chunked = [];
for(let i=0; i<arr.length; i++) chunked[i] = [];
let sub = 0;
for (let i = 1; i < arr.length; i++) {
if (arr[i]>arr[i-1]) {
chunked[sub].push(...[arr[i-1],arr[i]]);
} else {
sub++
}
}
const chunked2 = [...chunked.filter(k=>k.length).map(k => [...new Set(k)])];
for (let i = 0; i < chunked2.length; i++) {
if (chunked2[i+1])
if( chunked2[i][chunked2[i].length - 1] > chunked2[i+1][0]) {
chunked2[i+1].shift();
}
}
return [].concat.apply([], chunked2).lenght;
}
If I have an array of [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7] and wanted to find each case of 3 consecutive numbers (whether ascending or descending), how would I do that?
Second part would be then to alert an array with the index of each of these sequences.
For ex. the previous array would return [0,4,6,7].
So far I have this... which is a rough start
var arr = [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7];
var results = [];
for (var i = 1; i < arr.length; i++) {
if ((arr[i] - arr[i-1] != 1) && (arr[i] - arr[i+1] != 1)) {
results.push(arr[i]);
}
}
alert(results);
Thanks for the help!
Thanks for the math.abs pointer. This is what I ended up doing:
var array = [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7];
var indexes = [];
for(var i=0; i < array.length; i++) {
var diff = array[i+1] - array[i];
if(Math.abs(diff)==1 && array[i+1]+diff == array[i+2]) {
indexes.push(i);
}
}
alert(indexes);
It'd be interesting to know the context of this task as well... Anyway, here's my solution:
var arr = [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7];
var results = [];
var limit = arr.length - 1;
var sequence = 0;
for (var i = 0; i < limit; ++i) {
var diff = arr[i+1] - arr[i];
if (sequence && sequence === diff) {
results.push(i-1);
continue;
}
sequence = (diff === 1 || diff === -1) // or ... Math.abs(diff) === 1
? diff
: 0;
}
console.log(results);
The idea is simple: we don't need to compare two neighbors twice. ) It's enough to raise a kind of sequence flag if this comparation starts a sequence, and lower it if no sequence is there.
This is a very literal approach to your question - I have only checked forwards numbers, but adding reverse would be done almost in the same way
var arr = [1, 2, 3, 4, 10, 9, 8, 9, 10, 11, 7];
var results = [];
for (var i = 0; i < arr.length; i++) {
// if next element is one more, and one after is two more
if (arr[i+1] == arr[i]+1 && arr[i+2] == arr[i]+2){
// store the index of matches
results.push(i);
// loop through next numbers, to prevent repeating longer sequences
while(arr[i]+1 == arr[i+1])
i++;
}
}
console.log(results);
You need to look closely at your expression in your if statement.
It currently says:
If the difference between the current element and previous element is not 1, and
If the difference between the current element and next element is not 1
then it's a result.
So, on the face of it, that's an incorrect logical statement to determine if the current element is in the middle of a consecutive set of three.
In addition, this doesn't account for an ascending or descending set of three either.
Try figuring out, in words, what the condition would look like and go from there.
Some things to consider
I suggest you start going through the list from i = 2
Research Math.abs
This is I think a simpler way to do it. First check the average of the left and right number is equal to the middle, then check that the absolute value of either neighbor is one.
var arr = [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7];
var indexes = [];
for(var i=1; i < arr.length; i++) {
if((arr[i-1]+arr[i+1]) / 2 == arr[i] && Math.abs(arr[i]-arr[i-1]) == 1) {
indexes.push(i-1);
}
}
alert(indexes);
var arr = [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7];
var results = [];
for (var i = 0; i < arr.length - 2; i++) {
if ((arr[i+1] - arr[i] === 1) && (arr[i+2] - arr[i+1] === 1)) {
results.push({
i:i,
mode:'up',
arr:[arr[i],arr[i+1],arr[i+2]
});
}
if ((arr[i+1] - arr[i] === -1) && (arr[i+2] - arr[i+1] === -1)) {
results.push({
i:i,
mode:'down',
arr:[arr[i],arr[i+1],arr[i+2]
});
}
}
alert(results);