Javascript fill in the missing ranges (integers) [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a sorted array of objects, each with start and end coordinates, stated relative to a larger range that encompasses all of these coordinates. I would like to create new objects and put them into the array.
JsFiddle link is at the bottom.
Here's a visual representation:
before:
|---------------------------------------|
|-----| |----------| |------|
after:
|---------------------------------------|
|---|-----|-----|----------|---|------|-|
I was trying to use a for loop to find the missing ranges and then splice in the appropriate object as I found them. This creates an infinite loop.
I think that I could feasibly create a temporary array with the filled-in objects, then concatenate that with my original array and sort by start coordinate, but I'd like to do it without having to sort the array again.
Here is a link to a jsFiddle

I think your problem is, you are using splice to "modify" the subfeatures[] array, (adding a new element) but at the same time you are looping over that array, that causes infinite loop, I think your logic is good, instead of using splice, it may be easier to just construct a new array
the commented line are the only modification you have to do.(you also have to consider if the last element not ending at the upper limit)
//var newArr=[];
for (i = 0; i < subfeatures.length - 1; i++) {
//newArr.push(subfeatures[i]);
if ( subfeatures[i].end != subfeatures[i+1].start) {
var feat = {start: subfeatures[i].end, end: subfeatures[i+1].start, type: null};
console.log("A feature should be placed after the current index: "+i+". This feature would have the starting point: "+subfeatures[i].end+" and the ending point: "+subfeatures[i+1].start);
//newArr.push(feat);
}
}
//return newArr;

Splice() is not optimal because you have to move all the later elements in the array every time you find a gap. Here's the solution with a new array that Kossel is suggesting:
var newArray = [];
for (i = 0; i < subfeatures.length - 1; i++) {
newArray.push(subfeatures[i]);
if ( subfeatures[i].end != subfeatures[i+1].start) {
var feat = {start: subfeatures[i].end, end: subfeatures[i+1].start, type: null};
newArray.push(feat);
}
}

Related

JS Function that checks a dynamic number of index positions and returns array element if it satisfies the condition [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I've been looking for a way to return elements in an array based on a dynamic number. This dynamic number will be the number of required index positions for each array element, if each element can satisfy the required number of index positions (its own position counts towards the requirement) then that element should be returned.
const arr = [1,2,3,4,5,6]
const requiredIndexes = 3
So with the variables listed above I should return [1,2,3,4] because 5 and 6 will not be able to return three index positions.
The Array.prototype.slice might give you some help. Please refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
const arr = [1,2,3,4,5,6]
const requiredIndexes = 3
console.log(arr.slice(0, arr.length - requiredIndexes + 1))
I am not an expert but I think you would want to iterate up to the position. Are you having the dynamic number be a random number? You may want to also clone your array and use the clone as the worker array. Not sure exactly what you are wanting to do with the array, but you can then slice from the array and the parent array stays unefected.
function pickposition() {
var randIndex = Math.floor(Math.random() * clone.length);
rand = clone[randIndex];
clone.splice(randIndex,1);
}

How can i find the index of the element of an Array? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Here is my code, it gives me undefined i have also tried indexof() method
let Numbers = [2,3,1,5,6,7,8 ];`
console.log("Unsorted array " + Numbers);
for(var i=0 ;i<Numbers.length;i++){`
alert(Numbers.findIndex[i]);
}
The below code would work after some changes in your code -
let Numbers = [2, 3, 1, 5, 6, 7, 8];
console.log("Unsorted array " + Numbers);
for (var i = 0; i < Numbers.length; i++) {
console.log(Numbers.indexOf(Numbers[i]));
}
In your case, you were using findIndex() which takes a function and executes it for each element of the array. You were passing it a number which is not correct. Also, the invocation of function you were doing was not correct - use () brackets and not [] brackets for function call.
Also, the i itself is the index. I don't know why you would need to use indexOf to get the index of element which you already know is present at a particular index. This method wouldn't be practical unless your array has duplicates and you need to find the first occurring index number for each element of array.
As a side tip, avoid using alert for such purposes. Stick with console log.

How to calculate all possible results in a 4x3 array? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
assume that the array looks like this.
var res = [2,4,1,6,
1,1,2,8,
5,6,7,1];
all possible four quadrants combinations of this array are 81.
in this example we have only one combination on index : 4,5,2,11 which is four 1.
my question is how to calculate them.
thanks.
I'm not completely clear on what you're trying to achieve. Do you want to find every subset of length exactly 4 which contains all the same value? If so, you can do this in N^2 time with the following naive algorithm:
let quadrants = [];
res.forEach(checkElement => {
let possibility = [];
res.forEach((element, index) => {
if (element === checkElement) {
possibility.push(index);
}
});
if (possibility.length === 4) {
quadrants.push(possibility);
}
});
If you want to account for the possibility of the original array having more than 4 of the same number and include all subset quadrants, you'll need to change the length check to >=4 and add one more step at the end of this: calculate the power set of all listed quadrants with length greater than 4, filter out the ones that aren't length 4, and then concatenate those to the quadrants array. (You'll want to remove each quadrant with length >4 from the quadrants array before calculating its power set, so it won't be in the final result.)
If you do that, you may be able to optimize the last step by only calculating the subsets of length 4 of the longer quadrants; try using this as a guide for that if you need it: https://www.geeksforgeeks.org/print-subsets-given-size-set/

Getting all positions of bit 1 in javascript? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have provided binary for example, 01001, and would like to get positions of bit 1, so I expect it will return me [0, 3].
Is there any function provided by javascript to get all positions of bit 1?
If it's a number, convert it to a string before hand, if it is a string you can do:
positionArray = [];
binary.split('');
for (i = 0; i < binary.length; i++){
if (binary[i] == "1"){
positionArray.push(i);
}
}
return positionArray;
What i'm essentially doing is converting the string to an array (or number to a string to an array) of characters and then going through each entry to find the positions of each '1'.
Not sure you can do it this way with numbers, which is why I suggested converting it to a string before hand. It's just a rough solution and I bet there are much better ways of doing it but hope it helps.
MDN has a useful piece of code that works numerically and will take a number like 9 or in binary 0b1001 and return you an array with true/false values depending on whether or not the corresponding bit is set in the input value. For 1001 it returns [true, false, false, true]
You can then use this array to create your desired output by checking which indexes are true, and getting [0,3]
The MDN snippet is here:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Reverse_algorithm_an_array_of_booleans_from_a_mask
And a quick example of using it is here:
https://repl.it/DuEh/5
#DibsyJr has a nice solution if you are dealing with strings. However if you start from a number, then converting it to a string is an unnecessary overhead. You can do it efficiently with this function:
function get_idxs(x) {
var arr = [];
var idx = 0;
while (x) {
if (x & 1) {
arr.push(idx);
}
idx++;
x >>= 1;
}
return arr;
}
> get_idxs(0b1001);
[0, 3]
WARNING: It does not work for negative numbers. Unfortunately for negative numbers the answer to the question depends on the underlying cpu architecture.

JavaScript average calculator [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am wondering how i would make a function that will record the 10 most recent Date.now commands and then turn them into an average. I then want to put it into a side bar and make it sort of like a scoreboard. http://jsfiddle.net/eh5dxyp4/ . Thanks in advance
clickedTime=Date.now();
reactionTime=(clickedTime-createdTime)/1000;
document.getElementById("time").innerHTML=reactionTime;
this.style.display="none";
makeBox();
}
makeBox();`
You've shown quite a bit of code that doesn't seem relevant to the actual maths part of your question. I'm going to provide one way to do this part:
record the 10 most recent Date.now commands and then turn them into an average
Create an array:
var recent = [];
And a function that adds a value to that array but also ensures there will only be at most ten items in it:
var recentLimit = 10;
function addRecentItem(item) {
recent.push(item); // add to end of array
if (recent.length > recentLimit)
recent.shift(); // remove from start of array
}
Then you just need a function to calculate the average:
function getRecentAverage() {
var i,
sum = 0;
for (i = 0; i < recent.length; i++)
sum += recent[i];
return sum / recent.length;
}
So then wherever in your code you produce one of the Date.now objects you can simply add it to the recent list:
addRecentItem(yourValueHere);
And then get the current average:
console.log( getRecentAverage() );
As far as your scoreboard concept goes, you just need a function that loops through whatever is in the recent array and creates appropriate html elements (li elements, for example).
Add var reactionTimes=[]; somewhere outside the function that calulates it then use
var reactionTime = (clickedTime-createdTime)/1000;
reactionTimes.push(reactionTime);
document.getElementById("time").innerHTML=reactionTime;
if (reactionTimes.length==10) {
var average = reactionTimes.reduce(function(sum, a) { return sum + a },0)/(reactionTimes.length!=0?reactionTimes.length:1);
reactionTimes.pop(); // make ready for a new 10th value
document.getElementById("average").innerHTML=average;
}

Categories