Break array into multiple arrays based on threshold - javascript

I have the following graph, which is a representation of an array [2,8,12,5,3,...]. X axis is in seconds. I want to break this array into multiple parts when y values stays 0 for longer than 2 seconds. So the array in this example would break into 3 parts: x = 0 to 8, x = 8 to 13 and x = 13 to 20 because y stays = 0 for more than 2 seconds from 8 to 13. In practice this array could be huge. What would be fastest method to do this in pure javascript (or if needed lodash/underscore)? Currently I am looping through this array to mark 2 second stop times. Is there a better way of doing this?

You could use an iterative approach with one loop while checking the expected zero value and decide if the threshold is reached or not. of not, then delete the last interval and append the length to the array before.
This proposal yields
with threshold = 2:
[
[ 1, 7],
[ 8, 13],
[14, 20]
]
with threshold = 7:
[
[ 1, 20]
]
var y = [2, 8, 12, 5, 3, 2, 0, 0, 3, 4, 8, 10, 8, 10],
x = [1, 2, 4, 5, 6, 7, 8, 13, 14, 15, 16, 18, 19, 20],
threshold = 2,
isZero = false;
result = [];
y.forEach(function (a, i) {
var last = result[result.length - 1];
if ((a === 0) !== isZero) {
if (last) {
last[1] = x[i];
}
return;
}
isZero = !isZero;
if (last && isZero && x[i] - last[0] < threshold) {
result.pop();
if (result[result.length - 1]) {
result[result.length - 1][1] = x[i];
}
return;
}
result.push([x[i]]);
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

You'll always need to look at the values of the array, so you won't be able to get further than an O(n) solution. The most efficient would probably be to run through the array with a variable containing the amount of zeros you've passed through at a certain point.
The function below is a hastily made implementation of this. I've also used a variable to store the previous index. This could also be calculated from the split array, but that would be rather inefficient if you're really talking about huge arrays.
function splitArray(array, treshold) {
var zeros = 0,
previousIdx = 0,
splitArrays = [];
array.forEach(function(point, idx) {
if (point === 0) {
zeros++;
if (zeros == treshold && previousIdx != idx - treshold + 1) {
splitArrays.push(array.slice(previousIdx, idx - treshold + 1));
previousIdx = idx - treshold + 1;
}
} else if (zeros >= treshold) {
splitArrays.push(array.slice(previousIdx, idx));
previousIdx = idx;
zeros = 0;
}
});
if (previousIdx != array.length -1) {
splitArrays.push(array.slice(previousIdx));
}
return splitArrays;
}
I've created a JSFiddle that shows this function in action with some test data: https://jsfiddle.net/Glodenox/La8m3du4/2/
I don't doubt this code can still be improved though.
If you just want to get the indices of the sections instead of an array with all data in separate arrays, you can replace the three array.slice(a, b) statements with [a, b-1].

Related

Get 5 closest elements to an element in array including that element

I am trying to get 5 closest elements to given element, including that element, in array. For example, if we have:
const arr = [1, 2, 3, 4, 7, 11, 12, 13, 15, 17]
and I want to get 5 closest elements to 11, it should return [4, 7, 11, 12, 13]. If i pass 1 it should return [1, 2, 3, 4, 7]. If I pass 15 it should return [11, 12, 13, 15, 17].
I'm not sure what you meant;
You might've meant a code to find the element and return the five nearest elements to it by place in the array;
Or you might've meant a code to find the 5 numbers closest to a number you say.
IF you meant the first case
There are two ways to do so,
A value as a parameter
Use this code:
function closestNByValue(arr, value, n) {
let ind = arr.indexOf(value);
let finalArr = [];
if (n > arr.length) {
finalArr = Array.from(arr);
} else if (ind == -1) {
finalArr = [];
} else if (ind <= n/2 - 0.5) {
finalArr = arr.slice(0, n);
} else if (ind >= (arr.length - n/2) - 0.5) {
finalArr = arr.slice(-n);
} else if (n%2 == 0) {
finalArr = arr.slice(ind-(n/2), ind+(n/2));
} else {
finalArr = arr.slice(ind-(n/2 - 0.5), ind+(n/2 + 0.5));
}
return finalArr;
}
console.log(closestNByValue([1, 2, 3, 4, 7, 11, 12, 13, 15, 17], 11, 5))
How does it do the job?
Okay first we need to find the index of the value and save it in ind (short form of 'index') and we check multiple different situations for what the ind is so we'd be able to output the best answer as finalArr.
There are two exceptions; what if there was no such value in our array? then ind = -1 and we'd return an empty array; or what if the number of elements nearby that we seek is larger than or equal to the arr.length? then we'd return all of the arr.
But if there were no exceptions, there are three different situations for the ind; first, ind is a number that makes us have all of the finalArr values from the first of arr, second, ind be a number that makes us have all of the finalArr values from the last of arr, and third, ind being a number that we have to select half from the indexes smaller than ind and half, larger.
If it is the third way, the way we select we'd be different depending on the oddity of the numbers we want to select.
And we'll have a conditional statement for each situation and return the finalArr.
An index as a parameter
function closestNByIndex(arr, ind, n) {
let finalArr = [];
if (n > arr.length) {
finalArr = Array.from(arr);
} else if (ind == -1) {
finalArr = [];
} else if (ind <= n/2 - 0.5) {
finalArr = arr.slice(0, n);
} else if (ind >= (arr.length - n/2) - 0.5) {
finalArr = arr.slice(-n);
} else if (n%2 == 0) {
finalArr = arr.slice(ind-(n/2), ind+(n/2));
} else {
finalArr = arr.slice(ind-(n/2 - 0.5), ind+(n/2 + 0.5));
}
return finalArr;
}
console.log(closestNByIndex([1, 2, 3, 4, 7, 11, 12, 13, 15, 17], 5, 5))
Similar to the first code it works, though we have the index and we don't search for it.
The point is, if you use the function with value, it'd do the nearest 5 elements of the first value that equals the entry but such confusion is not being tolerated in the second code.
IF you meant the second case
This is a code I coded:
const arr = [1, 2, 3, 4, 7, 11, 12, 13, 15, 17];
function allDiff(arr, num1, num2) {
const finalArr = [];
const x = Math.abs(num2 - num1);
for (let y = 0; y < arr.length; y++) {
if (Math.abs(arr[y] - num1) == x) {
finalArr.push(arr[y]);
}
}
return finalArr;
}
function deleteArr(arr, delet) {
for (let x = 0; x < arr.length; x++) {
if (delet.includes(arr[x])) {
delete arr[x];
}
}
return arr;
}
function closest(arr, num) {
const map = new Map()
arr2 = Array.from(arr);
let key, value;
for (let x = 0; x < arr2.length; x++) {
key = Math.abs(arr2[x] - num);
value = allDiff(arr2, num, arr2[x]);
arr2 = deleteArr(arr2, value);
map.set(key, value);
}
return map;
}
function closestN(arr, num, n) {
const map = closest(arr, num);
const mapKeys = Array.from(map.keys());
const mapKeysSorted = mapKeys.sort(function(a, b) {
return a - b
});
let finalArr = [];
let y;
for (let i = 0; i < mapKeysSorted.length; i++) {
if (n <= 0) {
break;
}
y = map.get(mapKeysSorted[i]);
if (n < y.length) {
finalArr = finalArr.concat(y.slice(0, n + 1));
break;
}
finalArr = finalArr.concat(y);
n -= y.length;
}
return finalArr;
}
console.log(closestN(arr, 11, 5));
It might be a little too long, but I have programmed it as you can give it any array (arr) with integer values, an integer (num) that you'd like it to be the base and another integer (n) for the number of the size of the output array, 5 in this case.
Explaining the code
The function closest would return a map of (the difference between the numbers, a list of the numbers in the arr that differs the number equal to their key).
The main function, closestN, calls the closest function and saves the map in the map variable.
Then it sorts the keys of the map in mapKeysSorted.
Now, a for loop loops through the mapKeySorted array and pushes new elements to the finalArr until the size of the finalArr reaches the number of elements we seek.
The main function is the closestN.
Here's a way to get to your goal:
To start, first thing to do is finding the index of the wanted number in the array. Example index of 1 in your array arr is 0. The index will help in extracting the numbers later on. The method findIndex will help us in finding the index.
Then, we need to find the position at which will start extaracting the closest numbers (in terms of position not value). As seen from the desired output you have provided, usually you want the returned array to be in the following structure:
output: [
2 nearest numbers (from N left),
the wanted number,
2 nearest numbers (from N right)
]
This can get tricky so we should make sure to deal with some edge case like when the wanted element is sitting at position 0.
Extract the numbers and return them as an array as described by your desired output. The use of slice method will come in handy here which allow us to extract the numbers just as we need.
Here's a live demo demonstrating solution:
const arr = [1, 2, 3, 4, 7, 11, 12, 13, 15, 17],
/** a function that returns an array containing the "5" (depending on "arr" length that could be less) nearest numbers (in terms of position) in "arr" array to the supplied number "n" */
findClosestNumbers = n => {
/** make sure we don't exceed the array length */
const toTake = 5 > arr.length ? arr.length : 5,
/** find the index of the wanted nulber "n", if "-1" is returned then "n" cannot be found ion the array "arr" */
idx = arr.findIndex(el => n == el),
/**
* from where we should start returning the nearest numbers (the position of the first number to extract from "arr"
* the below condition help deal with some edge cases like when "n" is the last element in "arr"
*/
startIdx = idx + toTake / 2 > arr.length ?
arr.length - 5 :
(idx - 2 >= 0 ?
idx - 2 :
0);
/** return the nearest numbers or return an empty array "[]" if the number "n" is not found on the array "arr" */
return idx == -1 ? [] : arr.slice(startIdx, startIdx + 5);
};
/** run for various scenarios */
console.log('For 1 =>', findClosestNumbers(1));
console.log('For 11 =>', findClosestNumbers(11));
console.log('For 15 =>', findClosestNumbers(15));
console.log('For 17 =>', findClosestNumbers(17));
.as-console-wrapper {
max-height: 100%!important;
}
The demo above is meant to help you understand how things could work and it is not the only way to get to your goal. Also, because I kept it as simple as possible, the above demo is wide open for improvements.

Determine if array is in order AND the last element is 0 [duplicate]

This question already has answers here:
Check array in JS - is list sorted? [duplicate]
(9 answers)
Closed 7 months ago.
how can I determine when the first X numbers of an array is in order AND the last element in 0? i.e the array is
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0
I currently have this, but this relies on the array always being the same, which isn't very flexibile
const sorted = (array) => {
const solved = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0]
return (JSON.stringify(array) == JSON.stringify(solved))
}
You could do something as simple as this:
const checkArray = (arr) => {
if(arr[arr.length-1] != 0){
return false;
}
const nums = arr.slice(0, arr.length - 1);
const sortedArr = [...nums].sort((a, b) => a - b);
for (let i = 0; i < nums.length; i++) {
if(nums[i] != sortedArr[i]){
return false;
}
}
return true;
}
console.log(checkArray([1,2,3,0])); // true
console.log(checkArray([1,2,3,4])); // false
console.log(checkArray([1,3,2,0])); // false
Basically the steps are:
Check if last element is 0, else do an early return.
Create a sorted version of the first part of the array (the one with the numbers)
Check if the numbers part is equal to the sorted array. If any element is different return false
In the end you return true only if every condition is verified.
This is generic enough so that if in the future you want to change the sorting type you can just act on the sort function (for example if you want to make it descending).
First define a generic function to verify that a segment of an array is sorted, then define a second function that uses the first to see the first values are sorted, and add a check for the final value:
function isSegmentSorted(array, start=0, end=array.length) {
for (let i = start + 1; i < end; i++) {
if (array[i - 1] > array[i]) return false;
}
return true;
}
function isSortedWithExtraZero(array) {
return array.at(-1) === 0 &&
isSegmentSorted(array, 0, array.length - 1);
}
var array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0];
console.log(isSortedWithExtraZero(array));
We can use every function for that. With !idx we exclude the first index 0, then we check if idx is less than the length of your array. If so, check if it is sorted, else check it it equals to zero.
const solutions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0];
const sorted = solutions.every((val, idx, arr) =>
!idx || (idx < solutions.length - 1 ? arr[idx - 1] <= val : val === 0)
);
console.log(sorted);

return "even" if others numbers are odd and "odd" the others number are even javascript

I have 2 questions, how can I get value instead of value inside array and how can I make this code shorter and declarative.
arr = [16, 4, 11, 20, 2]
arrP = [7, 4, 11, 3, 41]
arrTest = [2, 4, 0, 100, 4, 7, 2602, 36]
function findOutlier(arr) {
const isPair = (num) => num % 2 === 0
countEven = 0
countOdd = 0
arr1 = []
arr2 = []
const result = arr.filter((ele, i) => {
if (isPair(ele)) {
countEven++
arr1.push(ele)
} else {
countOdd++
arr2.push(ele)
}
})
return countEven > countOdd ? arr2 : arr1
}
console.log(findOutlier(arrTest))
Filtering twice may be more readable.
even = arr.filter((x) => x % 2 == 0);
odd = arr.filter((x) => x % 2 == 1);
if (even.length > odd.length) {
return even;
} else {
return odd;
}
If you're looking to do this with one loop, consider using the array reduce method to put each number into an even or odd bucket, and then compare the length of those buckets in your return:
function findOutlier(arr) {
const sorted = arr.reduce((acc, el) => {
acc[el % 2].push(el);
return acc;
},{ 0: [], 1: [] })
return sorted[0].length > sorted[1].length ? sorted[1] : sorted[0];
}
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(findOutlier(arr));
Note that this does not handle when the arrays are the same length gracefully (right now it'll just return the odd array).
You could take an object with the wanted part for collecting and add a short circuit if one of the types has a count of one and the others have a count greater than one.
const
isPair = num => num % 2 === 0,
findOutlier = array => {
count = { true: [], false: [] };
for (const value of array) {
count[isPair(value)].push(value);
if (count.true.length === 1 && count.false.length > 1) return count.true[0];
if (count.false.length === 1 && count.true.length > 1) return count.false[0];
}
};
console.log(...[[16, 4, 11, 20, 2], [7, 4, 11, 3, 41], [2, 4, 0, 100, 4, 7, 2602, 36]].map(findOutlier));
Here is an solution that selects the even or odd array based on the modulo result.
function findOutlier(integers) {
const even = [], odd = [], modulos = [even, odd];
for (const integer of integers) {
modulos[Math.abs(integer % 2)].push(integer);
}
return even.length > odd.length ? odd : even;
}
console.log(findOutlier([2, 4, 0, 100, 4, 7, 2602, 36]));
You unfortunately do need Math.abs() to handle negative values, because -3 % 2 == -1.
See: JavaScript % (modulo) gives a negative result for negative numbers
However the name findOutlier lets me assume there is only a single outlier within the provided list. If this is the case you can optimize the algorithm.
function findOutlier(integers) {
// With less than 3 integers there can be no outlier.
if (integers.length < 3) return;
const isEven = (integer) => integer % 2 == 0;
const isOdd = (integer) => !isEven(integer);
// Determine the outlire based on the first 3 elements.
// If there are 0 or 1 integers even, the outlire is even.
// if there are 2 or 3 integers even, the outlier is odd.
const outlier = integers.slice(0, 3).filter(isEven).length < 2
? isEven
: isOdd;
return integers.find(outlier);
}
console.log(findOutlier([2, 4, 0, 100, 4, 7, 2602, 36]));
You can do this without creating intermediate arrays by simply comparing each element to its neighbors and returning that element if it is different to both, or undefined if no outliers are found. This returns in the same iteration in which the outlier is first encountered, and returns the value itself and not an array.
function findOutlier(array) {
const
len = array.length,
isEven = (n) => n % 2 === 0;
for (const [i, value] of array.entries()) {
let
prev = array[(i-1+len)%len], // loop around if < 0 (first element)
next = array[(i+1)%len]; // loop around if >= length (last element)
if (isEven(value) !== isEven(prev) && isEven(value) !== isEven(next)) {
return value;
}
}
return undefined;
}
const arrays = [[16, 4, 11, 20, 2], [7, 4, 11, 3, 41], [2, 4, 0, 100, 4, 7, 2602, 36]]
console.log(...arrays.map(findOutlier));
Now that OP clarified the requirements (at least in a comment) this allows a different approach:
function findOutlier(array) {
let odd = undefined, even = undefined;
for (let i of array) {
let isEven = i % 2 == 0;
if (odd !== undefined && even !== undefined)
return isEven ? odd : even;
if (isEven) even = i;
else odd = i;
}
if (odd !== undefined && even !== undefined)
return array[array.length-1];
}
console.log(findOutlier([2,4,6,8,10,5]))
The algorithm will iterate the array, and store the lastest found odd and even numbers, respectively.
If we discovered both an odd and an even number already, with the current number we can decide, which of them is the outlier: If the current number is even, it's at least the second even number we found. Thus, the found odd number must be the outlier. The same applies vice versa if the current number is odd. The special case, if the outlier is the last element of the array, is checked with an additional condition after the loop.
If all numbers are odd or even (ie there is no outlier) this function will return undefined. This algorithm does not throw an error, if the preconditions are not met, ie if there is more than one outlier.

How do I merge consecutive numbers in a sorted list of numbers? [duplicate]

This question already has answers here:
How to reduce consecutive integers in an array to hyphenated range expressions?
(13 answers)
Closed 2 years ago.
I want to concatenate a sequence of numbers in a readable string. Consecutive numbers should be merged like this '1-4'.
I'm able to concatenate an array with all the numbers into a complete string but I'm having trouble combining / merging consecutive numbers.
I tried comparing the previous and next values with the current one in the loop with several if-conditions but I couldn't seem to find the right ones to make it work properly.
Examples:
if(ar[i-1] === ar[i]-1){}
if(ar[i+1] === ar[i]+1){}
My code looks like this:
var ar = [1,2,3,4,7,8,9,13,16,17];
var pages = ar[0];
var lastValue = ar[0];
for(i=1; i < ar.length; i++){
if(ar[i]-1 === lastValue){
pages = pages + ' - ' + ar[i];
}else{
pages = pages + ', ' + ar[i];
}
}
alert(pages);
Result is: 1 - 2, 3, 4, 7, 8, 9, 13, 16, 17
In the end it should look like this: 1-4, 7-9, 13, 16-17.
EDIT:
I used the first answer at #CMS' link for my Script. Looks pretty much like a shorter version of #corschdi's snippet:
var ar = [1,2,3,4,7,8,9,13,16,17];
var getRanges = function(array) {
var ranges = [], rstart, rend;
for (var i = 0; i < array.length; i++) {
rstart = array[i];
rend = rstart;
while (array[i + 1] - array[i] == 1) {
rend = array[i + 1]; // increment the index if the numbers sequential
i++;
}
ranges.push(rstart == rend ? rstart+'' : rstart + '-' + rend);
}
return ranges;
}
alert(getRanges(ar));
In your code, lastValue never changes in the loop, so you're forever comparing against the first element in the array. Also, when you do find a match, you aren't yet ready to append to the pages result just yet--there might be more numbers to come.
One approach might be to keep a run of the current sequence of numbers (or just the first and last numbers in a run), and only append this run to the result string whenever we find a break in the sequence or hit the end of the string.
There are many ways to approach this, and I recommend checking other folks' answers at the Codewars: Range Extraction kata, which is (almost) identical to this problem.
Here's my solution:
const rangeify = a => {
const res = [];
let run = []
for (let i = 0; i < a.length; i++) {
run.push(a[i]);
if (i + 1 >= a.length || a[i+1] - a[i] > 1) {
res.push(
run.length > 1 ? `${run[0]}-${run.pop()}` : run
);
run = [];
}
}
return res.join(", ");
};
[
[1,2,3,4,7,8,9,13,16,17],
[],
[1],
[1, 2],
[1, 3],
[1, 2, 3, 8],
[1, 3, 4, 8],
[1, 1, 1, 1, 2, 3, 4, 5, 5, 16],
[-9, -8, -7, -3, -1, 0, 1, 2, 42]
].forEach(test => console.log(rangeify(test)));
This should work:
var array = [1, 2, 3, 4, 7, 8, 9, 13, 16, 17];
var ranges = [];
var index = 0;
while (index < array.length) {
var rangeStartIndex = index;
while (array[index + 1] === array[index] + 1) {
// continue until the range ends
index++;
}
if (rangeStartIndex === index) {
ranges.push(array[index]);
} else {
ranges.push(array[rangeStartIndex] + " - " + array[index]);
}
index++;
}
console.log(ranges.join(", "));

JS check if items in an array are consecutive BUT WITHOUT SORTING

I've found several posts about this topic here on stackoverflow, like this one.
... but the main assumption in the suggested solutions is that the array is sorted or ascending or descending...
My problem is that I want to check if there is the sequence of 3 or more consecutive numbers in the array but without sorting the array because it consists of points' coordinates (in the coordinate system) - points are randomly added to the stage during the game... (I'm working in GeoGebra which applet is the stage that I'm adding points to...)
For example, I have the next array:
var array = [0, 4, 6, 5, 9, 8, 9, 12];
The code should only count numbers 4, 6 and 5 as consecutive (although the array isn't sorted), but not 9 and 9 or 9 and 8. Explanation: I've created the code in JS but it works only with sorted array and, besides that, the problem is also that it counts two equal values as well as only two consecutive numbers (like 8 and 9)... My code:
function findConsecutive(array) {
var nmbOfSeq = 0;
for(var i=0; i<array.length; i++) {
for(var j=0; j<array.length; j++) {
if(array[j]==array[i]+1) {
nmbOfSeq+=1;
}
}
}
return nmbOfSeq;
}
Thanks everybody in advance... I'm really stuck with this...
I suggest to get first the index of a group of three and then build an array with the groups of the indices.
var array = [0, 4, 6, 5, 9, 8, 9, 12, 1, 2, 3, 4],
indices = [],
result = [];
array.forEach(function (a, i, aa) {
var temp;
if (i < 2) { return; }
temp = aa.slice(i - 2, i + 1);
temp.sort(function (a, b) { return a - b; });
temp[0] + 1 === temp[1] && temp[1] + 1 === temp[2] && indices.push(i);
});
indices.forEach(function (a, i, aa) {
if (aa[i - 1] + 1 === a) {
result[result.length - 1].push(array[a]);
return;
}
result.push(array.slice(a - 2, a + 1));
});
console.log(indices);
console.log(result);

Categories