Check if value range is in array [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 9 years ago.
Improve this question
What: I have an array that has angles from 0 to 360, a predefined range is entered, and a periodically updating input ranging from 0 to 360. I want to check if the input is within the the predefined range of the array.
Example
array:
array[0]=100, array[1]=40, array[2]=320, array[3]=60, etc....
What I need to do is to see if the input lets say
input:
input=50;
is within a range of any of the values in the array
range:
range=25;
What I need code to do:
lower range = input-range & upper range = input+range
if values between the lower range and upper range exist in the array output the array number.
Completing the example: input-range=25 & input+range=75
so if a value between 25 & 75 exist in the array
array[1]=40 & array[3]=60 are within that range.
output the array key:
output[0]=1, output[1]=3
Approach:
Create a new nested array with the range added to and subtracted from the value in each array component. Then a for loop to check if the input is within any of the values.
Example Solution:
var nodeArray=new Array();
for(var i = 0; i<array.length;i++){
nodeArray[i].push(array[i]-range);
nodeArray[i].push(array[i]+range);
}
then the function to check:
for(var j=0;i<array.length;i++){
if ((input>nodeArray[j][0])&&(input<nodeArray[j][1])){
alert("within range");
}
}
Problem: I need a fast executing solution as time of execution is important to me and Im just curious if someone has a much improved idea on how to solve this problem.
Note: I also have not solved the fold over problem(350deg + 20 deg = 10 deg)

I found three optimisations
First : Don't use the function length in your loop, because the function is called each time. Declares a new variable and save the array length inside :
for(var j=0, arrayLength = array.length; j < arrayLength ;j++){}
Second : If you just need to know if one value is within the range, use break in your requirement if to exit the loop 'for':
if ((input>nodeArray[j][0])&&(input<nodeArray[j][1])){
alert("within range");
break;
}
Third: You can change the way to write the for loop.
for(var i = -array.length; i++ ;){}
Like that you remove one variable declaration and one operation of comparison.

Related

Algorithm to queue objects in a step wise manner in a matrix? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
I have an empty object array called groups.
Which is initialised as:
const groups = [[],[],[]]
Now array objects will populate inside each of the arrays inside the root object in the following manner:
The first object will go into the first array, the second object will be paired with the first object in the first array,
the third object will go into the second and the fourth will be paired with the third object in the second array.
Once all the arrays have 2 objects, the next incoming object will go into the first array and then the second, and so on.
Once all the arrays have 3 objects, next incoming object will go into the first array and then the second, and so on.
I have tried if else, but I think this has a particular algorithm solution that I cannot figure out.
It would be great if you can point me to the right direction.
Further clarification
I tested the logic given below, while it is close to what I am looking for, but in my case there has to be a predefined set of [[],[],[],[],[]] 5 arrays inside a root array and each array cannot hold more than 5 objects maximum. And considering your example of using a numerical value as an object it would be something like this if the total number of objects are less than 10: [[1,2],[3,4],[5,6],[7,8],[9,10]] if more than 10 and less than 15: [[1,2,11],[3,4,12],[5,6,13],[7,8,14],[9,10,15]], if more than 15 less than 20: [[1,2,11,16],[3,4,12,17],[5,6,13,18]...] and so on.
The logic seems to first fill the sub arrays with 2 objects each, and then each next object is added in a round-robin order.
We could leave the initialisation of groups to be either an array of 3 sub arrays, or 5 sub arrays, or still some other number of sub arrays, and build it up from there.
This leads to the following logic:
let groups = [[], [], [], [], []];
let max = groups.length * groups.length;
let firstPhase = groups.length * 2;
for (let val = 0; val < max; val++) {
let index = val < firstPhase ? val >> 1 : val % groups.length;
groups[index].push(val+1); // +1 because you start numbering from 1.
console.log(JSON.stringify(groups));
}

better way to find duplicate item in a sequence than checking its first and last index [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 5 years ago.
Improve this question
I'm solving a challenge which has a sequence of integers from 1 to N, and the task is to find the missing integer in the sequence, and the one integer that is duplicated.
The constraints -
You are not allowed to sort the array.
Your solution should not time out for large values of N.
Ideally, your solution should not use extra space except the one provided by the input array (which can be modified).
My current code times out, I'm assuming that's because the complexity for finding the duplicate element might be O(N^2).
For the missing element, my algorithm is -
Create a variable, set it to 1, and loop until condition is true
In loop, check if variable is present in array, if so, increment variable and continue loop
If variable was not found in array, this was the missing element. Break out of loop.
This should run in O(N) time, so this part should be fine.
For the duplicate element, my approach was to check the first index and last index of every element in array. For unique elements, the index values would be the same, but it would be different for the duplicates.
This is where the problem lies, I think.
My code -
function solution(array) {
var missing = 0,
duplicate = 0;
let notFound = true;
let curr = 1;
while (notFound) {
if (array.indexOf(curr) === -1) {
notFound = false;
break;
}
curr++;
}
missing = curr;
duplicate = array.find((e, i, arr) => arr.indexOf(e) !== arr.lastIndexOf(e));
return [missing, duplicate];
}
console.log(solution([2, 3, 1, 4, 4, 6]));
I checked some related questions, like this and this, but couldn't get anything out of them.
How do I fix this?
I think you can hash your input array.
What I mean by that is, suppose your array is [4,1,5,6,3,1]
Here is a simple pseudo-code.
You can get duplicate element like this:
for i:array.length
array[array[i]] = array[i]*-1 // you found and marked first element of your array
if(array[i] > 0) //it would be positive if you found and marked an element twice.
array[array[i]] is the duplicate element
This runs in O(n)
Now to get the missing element, you can traverse the array again
for i:array.length
if (array[i] > 0 && array[i]!=duplicate element) //there would be two positive numbers, missing number and the duplicate
i = missing element
This O(n) again, so its O(n) overall.
If anything is unclear, you can ask. Sorry about preferring to write a pseudo-code instead of an explanation.

Type error, cannot read property 'match' of undefined [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
i got stuck in the Javascript code below, I don't know what's the problem.
the code is always showing"Type error, cannot read property 'match' of undefined",
Here IS THE CODE:
function keepletteronly(str) {
str=str.toLowerCase();//Make the string to lower case
arr=str.split(""); //This way I make an array out of the string
arr1=[]; //make an new array
for (i=1; i<=arr.length;i++){
if (arr[i].match(/[a-z]/)!=null) { //This is where the problem is
arr1.push(arr[i]); //retain only the letters and append to the arr1
}
}
newstring=arr1.join;
return newstring;
}
keepletteronly("1eye");
The index of a JS array starts from zero.
You should change your for sentence to
for ( i = 0; i < arr.length; i += 1) {
Moreover, another sentence is also incorrect:
newstring=arr1.join;
it should be
newstring=arr1.join('');
or simply produce the resultant string without arr1, like:
newstring='';
...
newstring+=arr[i];
Arrays in Javascript are base 0, meaning the first item is at index 0. Imagine you have three items in an array, the length property will say 3 and the three items will occupy indices 0, 1 and 2.
In your for loop, you start at index 1 (i=1;), meaning the loop will skip the first item (at index 0) and then you iterate while i is lower or equal to the length of the array. The length of the array is 3, but because of base 0, the last item in the array is at index 2. So in the last iteration of your for loop, you try to access index 3 of the array, which is undefined.
So, what you need to do is to change your for loop expressions to look like this:
(i = 0; i < arr.length; i++)
This way you will properly iterate over 0, 1 and 2 instead of 1, 2 and 3

storing values derived in a loop in javascript [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 6 years ago.
Improve this question
Please I need you guys help. I want do some calculations on the values that will be obtained from a loop but the calculation will depend on the last value the loop will compute. How do I store these values until the last value is computed by the loop and use the outcome to do further calculation on the previous values. Please I need a demonstrating example
I'm not exactly sure what you mean, but you could store every single value from the loop like this:
//First, make an empty array.
var values = [];
//Then, make your loop. This loop runs 50 times, but
//you can make it run however many times you want.
for (var i = 0; i < 50; i++) {
//This is where your loop does something with "i".
//You can do whatever you want with it, but I've chosen to square it.
values[i] = i * i;
}
//Now, "values" is an array with every calculation from the loop.
//Make another for loop, where "i" counts up to the length of "values".
for (var i = 0; i < values.length; i++) {
//The last result of the first loop is values[values.length - 1].
//here, do what you want with the values. I have chosen to divide each
//value by the last calculation of the function.
values[i] = values[i] / values[values.length - 1];
}
Hope this helped.

Insert n characters in the nth row using JavaScript [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 7 years ago.
Improve this question
Given a number n and a character c, the task is to replace the innerHTML of an element with n rows of text. The first row should have one copy of c, the second row should have two copies of c, etc. <br> tags are to be inserted to separate each row.
I've been thinking that a nested for loop might be appropriate here, where the outer for creates the rows, and the inner for repeats the characters in each row, but just can't put it together in my mind, and not sure if that's even a good approach.
I am thinking something perhaps like:
for(i = 1; i <= n; i++) {
for(j = 1, j <= n; j++) {
document.getElementById("output").innerHTML = c;
}
document.getElementById("output").innerHTML += <br>;
}
Nested for loops typically have bad performance implications, but assuming you're doing this on a small scale, this should give you an idea of what to go for http://jsfiddle.net/mrodkc1u/1/
However, since the number of rows will be the same number of characters in the largest row, you shouldn't need to use a nested loop. Here's an updated fiddle with just one loop http://jsfiddle.net/mrodkc1u/2/

Categories

Resources