Interval range insert with split into unique ranges - javascript

Looking for algorithm ideas how to insert into interval range value so it won't overlap existing intervals.
Interval range is sorted smallest to larger [[0, 1], [3, 5]].
Now inserting interval range [0, 7] to [[0, 1], [3, 5]] -> [[0, 1], [1, 3], [3, 5], [5, 7]] -> generated two new ranges other remain same.
Here is another example, inserting range [-3, 5] to [[0, 1], [6,7]] -> [[-3, 0], [0, 1], [1, 5], [6, 7]]
All programming languages(especially JavaScript) are welcomed also pseudocode implementations.

in the actual code there is a differentiation between old interval ranges and new ranges after applying certain operation those ranges would be merged together. I wanted to split the question into smaller chunk so the merging part is left out.
Solely: It is easier to merge in the new interval directly, instead of artificially splitting it up. So this is what I propose below (C++):
using DataType = /* whatever appropriate; double, int, unsigned int, ...*/;
using Interval = std::pair<DataType, DataType>;
std::vector<Interval> intervals;
void insert(Interval x)
{
if(intervals.empty() || x.second < intervals.front().first)
{
intervals.insert(intervals.begin(), x); // (1)
}
else if(x.first > intervals.back().second)
{
intervals.push_back(x); // (2)
}
else
{
auto b = intervals.begin();
while(b->second < x.first)
{
std::advance(b, 1);
}
// cannot be END iterator, otherwise would have been caught by (2)
if(x.second < b->first)
{
// this is a new interval in between std::prev(b) and (b)
intervals.insert(b, x);
}
else
{
// b is overlapping with x!
if(b->first > x.first)
{
b->first = x.first;
}
auto e = std::next(b);
while(e != intervals.end() && e->first <= x.second)
{
std::advance(e, 1);
}
// e is the first interval NOT overlapping with x!
auto l = std::prev(e);
b->second = std::max(x.second, l->second);
// drop all subsequent intervals now contained in b (possibly none)
intervals.erase(std::next(b), e);
}
}
}
Algorithm only, spared the design efforts of packing into class, having convenience function accepting begin/end markers (instead of interval), ...
If the data type you intend to use does not provide a back accessor (C++: e. g. std::forward_list): No problem, just drop the second if (containing (2)); then, however, b can be the end iterator, so you'd have to test for and if the test succeeds, you can insert at end. You'd most likely not have an 'insert before' then, so you'd need to track b's and later e's predecessors separately, too...

Related

Recursion Issue(I just can't understand what it is doing)

I have been reading multiple articles and as soon as I go to do something recursively I just don't get it, I understand the base case, but I don't get the recursive step. so I have this code which is a solution I found.
function range (start, end) {
if (end < start) return [];
if(start == end) {
return [start];
}
else {
const numbers = range(start , end - 1);
numbers.push(end)
return numbers;
}
}
so, I understand the start == end, here is what I do not get.
why is numbers an array? I don't see anywhere that range is an array, I also don't understand if I use start + 1 and push start, the numbers are backward. I have spent 3 weeks so far trying to get a better grasp on recursion and just can not do it, if someone could please help explain to me and maybe offer some resources I have not found? I watched Al Sweigarts recursion video, and thought I understood it until I went to do something, I found it its the recursive step that is just destroying me, I am trying everything I can to understand and get an idea of how this works but I am just super frustrated with myself at this point. thank you for any help.
The only possible thing range is returning here is [] which is an array and [start] which is also an array. So when youre calling range recursively from the else block then you'll always end up with an array since there arent any other paths the code can go.
See comments inline:
function range (start, end) {
console.log("range function is running with arguments of: ", start, end);
// If end < start, exit function and return an empty array
if (end < start) return [];
// If not, check if start and end are equal (with conversion)
if(start == end) {
// If so, return an array that only contains the start parameter value and exit
return [start];
} else {
// If the above tests are false, call the function again
// but with end being one less than before and assign either
// array from above as the value of numbers.
const numbers = range(start , end - 1);
numbers.push(end); // Add end to the end of the array
return numbers; // Return this array instead of the other 2
}
}
console.log("Final array is: ",range(10,20)); // Display the final returned array
domain and codomain
A function's inputs are known as its domain and the function's return type is known as its codomain. These types can effectively guide us when writing our implementation -
range : (number, number) -> number array
fill in the blanks
This helpful template can get you started on almost any recursive function. It may seem challenging at first, but things become easier as we fill in the pieces. According to the types for range, we already know 2 and 3 must return some array -
// range : (number, number) -> number array
function range(start, end) {
if (...) // 1
return ... // 2 (must return array)
else
return ... // 3 (must return array)
}
1. base case
Each recursive function needs a base case, which does not result in a recursive call, allowing the function to eventually exit. Under what conditions does the range function exit?
// range : (number, number) -> number array
function range(start, end) {
if (end < start) // 1 ✅ when end subceeds start, exit
return ... // 2
else
return ... // 3
}
2. base value
When the exit condition is met, we need to return the base value. Typically it is the empty value of our function's return type, or codomain. Since we must return an array, what is the empty value for arrays?
// range : (number, number) -> number array
function range(start, end) {
if (end < start) // 1 ✅
return [] // 2 ✅ an empty array is []
else
return ...
}
3. inductive case(s)
We must specify what happens when the exit condition is not met in the else branch, known as the inductive cases. If end < start is not true, by induction we know that end >= start. In this case we solve the problem for the current start and end, and append it to the result of the smaller sub-problem. In other words, if I have range(P,Q) the answer is -
append Q to the result of range(P, Q - 1)
Remember the type for range gives us a hint. When range is called with new arguments, the first and second arguments are both number. The return value will be an array of numbers, or number array.
In JavaScript we write that as -
// range : (number, number) -> number array
function range(start, end) {
if (end < start) // 1 ✅
return [] // 2 ✅
else
return [...range(start, end - 1), end] // 3 ✅ minus and append
}
substitution model
Recursion is a functional heritage and so using it with functional style yields the best results. This means writing functions with referential transparency, meaning there are no observable side-effects and the function will always return the same value when the same inputs are used. Using the substitution model we can substitute any function call for its return value -
range(3,6)
[...range(3, 6 - 1), 6]
[...range(3, 5), 6]
[...[...range(3, 5 - 1), 5], 6]
[...[...range(3, 4), 5], 6]
[...[...[...range(3, 4 - 1), 4], 5], 6]
[...[...[...range(3, 3), 4], 5], 6]
[...[...[...[...range(3, 3 - 1), 3], 4], 5], 6]
[...[...[...[...range(3, 2), 3], 4], 5], 6]
[...[...[...[...[], 3], 4], 5], 6] // base case
[...[...[...[3], 4], 5], 6]
[...[...[3, 4], 5], 6]
[...[3, 4, 5], 6]
[3, 4, 5, 6]
using plus instead of minus
It should be helpful for us to see that we can solve range using + and prepend instead of - and append -
// range : (number, number) -> number array
function range(start, end) {
if (start > end) // ✅ when start exceeds end, exit
return []
else
return [start, ...range(start + 1, end)] // ✅ plus and prepend
}
range(3,6)
[3, ...range(3 + 1, 6)]
[3, ...range(4, 6)]
[3, ...[4, ...range(4 + 1, 6)]]
[3, ...[4, ...range(5, 6)]]
[3, ...[4, ...[5, ...range(5 + 1, 6)]]]
[3, ...[4, ...[5, ...range(6, 6)]]]
[3, ...[4, ...[5, ...[6, ...range(6 + 1, 6)]]]]
[3, ...[4, ...[5, ...[6, ...range(7, 6)]]]]
[3, ...[4, ...[5, ...[6, ...[]]]]] // base case
[3, ...[4, ...[5, ...[6]]]]
[3, ...[4, ...[5, 6]]]
[3, ...[4, 5, 6]]
[3, 4, 5, 6]
demo
function rangeplus(start, end) {
if (start > end)
return []
else
return [start, ...rangeplus(start + 1, end)]
}
function rangeminus(start, end) {
if (end < start)
return []
else
return [...rangeminus(start, end - 1), end]
}
console.log(rangeplus(3,6))
// [3, 4, 5, 6]
console.log(rangeminus(3,6))
// [3, 4, 5, 6]
You cannot understand a recursive algorithm ( not your own ) by reading its lines only.. so, you need to apply a simple example to get the right result and understand where it's goes to, this is my example :
First call
start = 1
end = 0
=>start > start
Algorithm result : return []; ===> an empty array
First call
start = 1
end = 1
=> start = end
Algorithm result : return [start]; ===> array of ONE element (start value)
First call
start = 1
end = 5
=> start < end
in this case the algorithm will call itself const numbers = range(start , end - 1); by changing the end value and storing it in array called numbers
Second call :
numbers = []
range(1,5-1)
(don't forget, "end" (4) is still greater than "start" so it will go to the recall iteration )
Third call :
numbers []
range(1,4-1)
=>"end" is still greater (3)
Fourth call :
numbers []
range(1,3-1)
=>"end" is still greater (2)
Fifth call :
numbers []
range(1,2-1)
=>now, "end"(1) is equals to "start" (1),the next iteration will act differently
Sixth call :
start = end ==> this call will return start value (1) and push it to the constant number
so, now, the algorithm will continue the execution of not executed lines after the previous calls (I mean numbers push() ):
Result of sixth call = 1
it will push it to numbers, and return numbers (array of one element [1])
Result of fifth call = 2
push to numbers ==> numbers is [1,2]
etc. Until it reaches the first call.
Final Result : [1,2,3,4,5]
I hope that it can help.

Javascript recursion related question about push() and unshift() methods working opposite

function countup(n) {
if (n < 1) {
return [];
} else {
const countArray = countup(n - 1);
countArray.push(n);
return countArray;
}
}
console.log(countup(5));
After running the above code it returns an array: [1, 2, 3, 4, 5], but push() adds new values at the end of an array so when value of n was 5 it should push 5 to the end of the array and when value of n got 4 it should push 4 at the end of the array like [5,4].
So why not it is returning [5,4,3,2,1] ? It is hard to understand what is happening in this code probably because of this recursion. Isn’t unshift() (which add new values to start of the array) should return [1,2,3,4,5] and push() [5,4,3,2,1] why opposite is happening?
As #Joseph stated in a comment the second to last function call would get pushed to the array first, then it would return that array, where it immediately adds the next number up the call stack.
Here are the steps being taken.
Initial call enters itself recursively n times, where the bottom call returns [] and then [1], [1, 2] ... [1, 2, ..., n] all the way up the call stack where upon the first function call ends and the program does something else.
To get [n, ..., 2, 1] you need to use the Array.prototype.unshift() method, which takes any javascript primitive type, ie String, Number, Boolean, and Symbols, in a comma separated format, like countArray.unshift(4, 5) or countArray.unshift(...anotherArray), and adds them to the beginning of the array.
ie
let someArr = [3, 2, 1];
someArr.unshift(5, 4);
console.log(JSON.stringify(someArr));
// outputs [5, 4, 3, 2, 1]
or
let someArr = [1, 2, 3];
let anotherArr = [5, 4]
someArr.unshift(...anotherArr);
console.log(someArr);
// outputs [5, 4, 1, 2, 3]
Where the output of
function countup(n) {
if (n < 1) {
return [];
} else {
const countArray = countup(n - 1);
countArray.unshift(n);
return countArray;
}
}
console.log(countup(5));
will be [5, 4, 3, 2, 1] tested with node in Vscode.
One useful way to think about this is to start by imagining you already had a function that does what you want for lower values, and then see how you would write one that works for higher values. That imaginary function should be a black box. All we should know is that it does what we want in the case of lower values. We don't care about its implementation details.
So lets say we had a function imaginaryBlackBox, and we knew that it returned the correct countUp values that we want. So, for instance, we know that imaginaryBlackBox (4) returns [1, 2, 3, 4].
Now, knowing that, how might we write a function that works for an input of 5 as well? How about something like this:
function countup(n) {
if (n < 1) {
return [];
} else {
const countArray = imaginaryBlackBox(n - 1);
countArray.push(n);
return countArray;
}
}
Again, we don't know how imaginaryBlackBox works. We just know that it returns the correct result for lower values of n. Our base case remains obvious. For another case, some n greater than 0, we call imaginaryBlackBox(n - 1), and by our basic assumption, we know that will return [1, 2, 3, ..., (n - 1)], which we store in countArray. Then we push n onto that array, to end up with [1, 2, 3, ..., (n - 1), n]. We return that value and we're done.
Now here's the trick. We know an implementation of imaginaryBlackBox -- it's the function we're writing! So we can simply replace it with countUp and know it will work.
function countup(n) {
if (n < 1) {
return [];
} else {
const countArray = countUp(n - 1);
countArray.push(n);
return countArray;
}
}
This required a few assumptions, and they are important to all recursive functions:
There is at least one base case whose value we can calculate without any recursive call. Here, when n is < 1, we simply return [].
For other cases, we can break down our problem into one or more recursive cases, where the input is in some clear and measurable way closer to a base case, so that subsequent steps will hit a base case in a finite number of calls. Here we reduce n by 1 on every step, so eventually it will be below 1.
Our function is effectively pure: its outputs depend only on its inputs. That means we can't count on changing a global variable or reading from one that might be changed elsewhere. Note that I use the qualifier "effectively" here; it doesn't matter if this function has observable side-effects such as logging to the console, so long as its output is dependent only on its input.
Anytime you have those conditions, you have the makings of a good recursive function.

what to do? javascript array exercise

Find the correct passcode in the array and we'll do the rest. We can't disclose more information on this one, sorry.
Each entry in the first array represents a passcode
- Find the passcode that has no odd digits.
- For each passcode, show us the amount of even digits.
- If it has no odd digits, show us that you've found it and increase the number of terminals by one.
var passcodes = [
[1, 4, 4, 1],
[1, 2, 3, 1],
[2, 6, 0, 8],
[5, 5, 5, 5],
[4, 3, 4, 3],
];
so, i've tried almost everything i could think of. modulo, function, for loop and i can't seem to get it. i'm a beginner and this is an important exercise i have to do. but what do i do? it asks for the amount of even digits in each passcode, so i have to get the array within the array and then code something that i don't know to find even values. i'm stuck
Your question is not really suitable for StackOverflow, you should at least try to write something and see how far you get.
Anyhow, you seem to want to iterate over the elements in passcodes to find the array with no odd numbers.
The first task is to how to determine if a number is even. That is as simple as looking for the remainder from modulus 2. If the remainder is zero, then the number is even, otherwise it's odd.
So a simple test is:
var isEven;
if (x % 2 == 0) {
isEven = true;
} else {
isEven = false;
}
Since 0 type converts to false, and the not (!) operator reverses the truthiness of values and converts the result to boolean, the above can be written:
var isEven = !(x % 2);
There are many ways to iterate over an array, if your task was just to find the element with no odd numbers, I'd use Array.prototype.every, which returns as soon as the test returns false, or Array.prototype.some, which returns as soon as the test returns true.
However, in this case you want to count the number of even numbers in each element and find the first with all even numbers. One way is to iterate over the array and write out the number of even numbers in the element, and also note if its all even numbers. You haven't said what the output is expected to be, so I've just made a guess.
var passcodes = [
[1, 4, 4, 1],
[1, 2, 3, 1],
[2, 6, 0, 8],
[5, 5, 5, 5],
[4, 3, 4, 3], // this last comma affects the array length in some browsers, remove it
];
// Set flag for first element with all even numbers
var foundFirst = false;
// Iterate over each element in passcodes
passcodes.forEach(function(code) {
// Count of even numbers in current array
var evenCount = 0;
// Test each element of code array and increment count if even
code.forEach(function(num) {
if (!(num % 2)) ++evenCount;
});
// If all elements are even and haven't found first yet, write out elements
if (code.length == evenCount && !foundFirst) {
console.log('Passcode (first all even): ' + code.join());
// Set flag to remember have found first all even array
foundFirst = true;
}
// Write count of even numbers in this array
console.log('Even number count: ' + evenCount + ' of ' + code.length + ' numbers.');
});
I have no idea what you meant ...but it does all what i could understand from your question. Hope it will help :)
var passcodes = [
[1, 4, 4, 1],
[1, 2, 3, 1],
[2, 6, 0, 8],
[5, 5, 5, 5],
[4, 3, 4, 3],
];
var aPassCode;
while(aPassCode = passcodes.shift()){
for(var i=0,evenCount=0,totalCount=aPassCode.length;i<totalCount;i++){
if(aPassCode[i] % 2 == 0)evenCount++;
}
if(evenCount == totalCount){
console.log('all digits even here: ' + aPassCode.join(','));
}else{
console.log(aPassCode.join(',') + ' contains ' + evenCount + ' even digits.');
}
}

What is faster - merge 2 sorted arrays into a sorted array w/o duplicate values

I was trying to figure out which is the fastest way to do the following task:
Write a function that accepts two arrays as arguments - each of which is a sorted, strictly ascending array of integers, and returns a new strictly ascending array of integers which contains all values from both of the input arrays.
Eg. merging [1, 2, 3, 5, 7] and [1, 4, 6, 7, 8] should return [1, 2, 3, 4, 5, 6, 7, 8].
Since I don't have formal programming education, I fint algorithms and complexity a bit alien :) I've came with 2 solutions, but I'm not sure which one is faster.
solution 1 (it actually uses the first array instead of making a new one):
function mergeSortedArrays(a, b) {
for (let i = 0, bLen = b.length; i < bLen; i++) {
if (!a.includes(b[i])) {
a.push(b[i])
}
}
console.log(a.sort());
}
const foo = [1, 2, 3, 5, 7],
bar = [1, 4, 6, 7, 8];
mergeSortedArrays(foo, bar);
and solution 2:
function mergeSortedArrays(a, b) {
let mergedAndSorted = [];
while(a.length || b.length) {
if (typeof a[0] === 'undefined') {
mergedAndSorted.push(b[0]);
b.splice(0,1);
} else if (a[0] > b[0]) {
mergedAndSorted.push(b[0]);
b.splice(0,1);
} else if (a[0] < b[0]) {
mergedAndSorted.push(a[0]);
a.splice(0,1);
} else {
mergedAndSorted.push(a[0]);
a.splice(0,1);
b.splice(0,1);
}
}
console.log(mergedAndSorted);
}
const foo = [1, 2, 3, 5, 7],
bar = [1, 4, 6, 7, 8];
mergeSortedArrays(foo, bar);
Can someone help me with time complexity of both solutions? Also, is there another, faster solution? Should I be using reduce()?
Your first function modifying passed argument and this is bad practice.
You can do it in the following way:
function mergeSortedArrays(a, b) {
return a.concat(b.filter(el => !a.includes(el))).sort();
}
The complexity also depends on the methods that you use in your code.
1) An algorithm commonly used for sorting is Quicksort (introsort as a variation of quicksort).
It has O(n log n) complexity however the worst case may still be O(n^2) in case the input is already sorted. So your solution has O( length(b) + length(a)+length(b) log (length(a)+length(b)) ) runtime complexity.
2) According to this question on the complexity of splice() the javascript function needs O(n) steps at worst (copying all elements to the new array of size n+1). So your second solution takes length of array b multiplied by n steps needed to copy the elements during splice plus the time to push().
For a good solution that works in linear time O(n+m) refer to this Java example and port it (i.e. create an array of size length(a) + length(b) and step via the indeces as shown). Or check out the very tight and even a littler faster implementation below of the answer.

Iterate through array backwards from index in JavaScript

I have a bit of Python code that does what I want very nicely, but trying to port that across to JavaScript is proving difficult to do cleanly.
jsonLine = [[0,1],[2,4],[4,8],[9,12],[11,16],[12,13]]
[firstX, firstY] = [9,12]
if [firstX, firstY] in jsonLine:
index = jsonLine.index([firstX, firstY])
lineArray.append(jsonLine[index:])
lineArray.append(jsonLine[index::-1])
jsonLine is an array of coordinates which make up a line, and [firstX, firstY] is the starting point on a line, defined by a user. I'm creating a script that creates two lines, one in either direction from the point the user chooses, which will later be cut shorter based on distance from the user's point.
The desired output in this case will be:
[[[9,12],[11,16],[12,13]],[[9,12],[4,8],[2,4],[0,1]]]
Below is the JavaScript I have, which gets the first of the desired arrays, but using a for loop doesn't feel right, and if I use jsonLine.reverse().slice(featureArray.length-vertex), it seems to duplicate the arrays pushed to lineArray. Is there a cleaner way to slice an array and reverse it?
for (var vertex = 0; vertex < featureArray.length; vertex++){
if (jsonLine[vertex][0] === firstX && jsonLine[vertex][1] === firstY) {
console.log(jsonLine.slice(vertex))
}
You can create a find method to find out the index of the coordinates you're interested in. After that, apply slice and reverse to get the format you're looking for:
var jsonLine = [
[0, 1],
[2, 4],
[4, 8],
[9, 12],
[11, 16],
[12, 13]
],
el = [9, 12],
index, res;
function findElement() {
var i = 0;
for (; i < jsonLine.length; i += 1) {
if (jsonLine[i][0] === el[0] && jsonLine[i][1] === el[1]) {
return i;
}
}
return -1;
}
index = findElement();
res = [
[jsonLine.slice(index)],
[jsonLine.reverse().slice(index - 1)]// -1 because you want to repeat the element.
];
console.log(res);
Fiddle
Note: As #RobG points out in the comments of this answer, if you want to keep the array intact, substitute the second part by jsonLine.slice(0, index + 1).reverse(). Reverse modifies the original array and that might be undesired behaviour (though it wasn't clear in the question whether it was or not).

Categories

Resources