I have a particular array, by which I wanted to check if two values within the array equal the value passed into the function, and if the two integers do, then pass it into a new array.
I have solved this by using two backwards while loops and caching the length as a variable, which seemed to be efficient. However, someone mentioned to me there might be a way to remove the need for one of the loops and making it much more efficient and thus optimizing the BIG O notation.
Any ideas how this could be done? This is what I have...
var intArray = [1, 3, 7, 8, 10, 4, 6, 13, 0],
newArray = [],
i = intArray.length;
function arrayCheck(k) {
while(i--) {
var z = i;
while (z--) {
if (intArray[i] + intArray[z] === k) {
newArray.push(intArray[i]);
newArray.push(intArray[z]);
}
}
}
alert(newArray);
}
arrayCheck(8);
There is an algorithm that solves this problem in linear [O(n)] time. I recommend you check out this SO answer.
Also, as others have stated, marking answers as accepted will make people more likely to answer your questions. You may wish to revisit questions you've previously asked and accept any answers that deserve it.
if you check for number N, and intArray[i] = M, then you need to find a value N-M in the array.
Build an efficient tree search to find values N-M and you can solve this in O(n+logn).
Related
I have a question about map.As you know by using map we can iterate arrays and able to change the element of arrays.To do that there are two ways and I listed them below.Which way has less complexity and more performance?(In the examples arrays are not big but think about the real world like 500 elements in an array)
var numbers = [4, 9, 16, 25];
numbers=numbers.map(e=>{
return e=e*2;
})
In this approach assigning each returned value to current array.
numbers.map((e,a)=>{
numbers[a]=e*2;
})
In this one on each iteration we need to go to array by index to find element and I think this is worse than above but Im not sure.
Don't use map if you're not going to use the array it creates. If you just want to loop through an array, use a loop or forEach or similar.
Whether you want a new array or not, the most efficient way to loop through an array is usually a for loop:
const numbers = [4, 9, 16, 25];
for (let i = 0, len = numbers.length; i < len; ++i) {
numbers[i] = numbers[i] * 2;
}
(Or any of several variations on that.)
But "most efficient" is extremely unlikely to actually matter in real-world code, so using things like map (if you want a new array) or forEach (if you don't) is just fine. map is idiomatic for that operation (creating a new array containing the entries from a previous array modified in some way).
Conclusion:
If you want a new array, feel free to use map, or create a blank array and use any of your options for looping arrays to loop the original and add entries to the new one.
If you don't want a new array, don't use map, use any of your options for iterating over the original except for ones that don't give you the index, and assign the updated value back to the entry.
Semantically you need for or forEach when you do not need a new array.
For sufficiently small arrays there is no difference in performance
var numbers = [4, 9, 16, 25];
numbers.forEach((e,i)=> numbers[i] = e*2);
console.log(numbers)
nums.forEach((v, i) => nums[i] = v);
is the fastest method possible that you listed (equivalent to your second method. Why? nums = nums.map(...) creates an entire copy of the array in memory and replaces the array with that copy. When you simply iterate over the array with an index and replace elements, you avoid making that copy, and it ends up being around 15% faster (see this benchmark.
The fastest way to change a value of an array is to iterate the index and update the item.
This approach is faset than forEach or map, because it does not have the overhead of this and it does not need the feature of the supplied structure of the callback.
var numbers = [4, 9, 16, 25];
for (let i = 0; i < numbers.length; i++) numbers[i] *= 2;
console.log(numbers);
I know that this question has been asked over and over. There are extensive discussions here and here, and a ton of other places online, but I just can't seem to work it out.
I want to store the contents of a gridview in a 2D array in Javascript. I have 4 columns and a varying number (100 to 300) of rows.
I've tried a number of different approaches to create and fill this array. They all take the basic form:
myVar = [ [] ];
myVar = [ [], [], [], [] ];
myVar = new Array([]);
myVar = new Array(new Array());
These are just a few of the approaches I've found and tried, but they either don't work or they only work on rows 0 and 1 (several of the proposed solutions have associated comments that mention this, so I know I'm not imagining it).
Many suggested solutions use loops, and some even use functions, but I can't imagine that this simple task, to create a 2D array, needs to be that complicated.
Can anyone please post simple syntax that creates a 2D array in Javascript, and the syntax to fill it and to access it? Many thanks.
Full disclosure: I'm still relatively new to Javascript myself, so I'm not sure if this an idiomatic or even all that wise of a solution, but you could try something like:
var defaultValue = 0;
var arr2D = new Array(300).fill( new Array(4).fill(defaultValue) );
You can create a 2D array in javascript like so
twoDArray = [ [1, 2, 3, 4], [5, 6, 7, 8] ];
alert(twoDArray[0][1]); // results in 2
You can access it by first providing the array location "0" and then the element location "1".
You can iterate over it like so
for(var x = 0; x < twoDArray.length; x++)
{
for(var y = 0; y < twoDArray[x].length; y++)
{
alert(twoDArray[x][y]);
}
}
jsFiddle: https://jsfiddle.net/81j5uug7/
I'm learning about the map() method right now and I understand very basic examples.
var numbers = [2, 4, 6];
var double = numbers.map(function(value) {
return value * 2;
});
My question is, in what cases do developers use the map() method to help solve problems? Are there some good resources with real world examples?
Thanks for the help!
As #Tushar referred:
The map() method creates a new array with the results of calling a
provided function on every element in this array.
So it is basically used when you need to apply certain functionality to every single element of an array and get the result back as an array with the new results.
For example doubling the numbers:
var numbers = [1, 4, 9];
var doubles = numbers.map(function(num) {
return num * 2;
});
// doubles is now [2, 8, 18]. numbers is still [1, 4, 9]
It basically helps to shorten your code eliminating the need of using for loop. But do remember it is used when every element of the array is manipulated because map() generates similar length of array provided.
For eg.- in the example you provided doubles will have [2, 8, 18].
where 2 correspond to 1.
4 correspond to 8.
9 correspond to 18.
I recommend you to watch the whole video but your answer is at the 14th minute:
Asynchronous JavaScript at Netflix by Matthew Podwysowski at JSConf Budapest 2015
I am little bit confused about every() and forloop. Which is the best loop for array elements with some condition. For example:
function isBigEnough(element, index, array) {
return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough); // false
[12, 54, 18, 130, 44].every(isBigEnough); // true
or
var arr = [12, 5, 8, 130, 44];
for(i =0 ; i<arr.length; i++) {
if(arr[i] >= 10)
console.log(arr[i])
}
Which is one best performance for check/sort out the element from array. I hope you to clear my doubts.
first thing instead of every use some function, it is more apt in your case.
secondly using asynchronous native array functions is always better in terms of code readability as well as performance when you app scales.
Plus they have additional benefit when it comes to object oriented implementation.
The best is to ignore issues like that unless you have a good reason to suspect that performance is going to be a factor.
Use the cleanest, most readable approach by default. Only consider performance when you think it's likely this is going to be a bottle-neck (and a bother). Iterating over ten elements isn't - and even then, the answer is that you need to profile the time for yourself; just try both the possibilities, measure the difference, and if it's big enough, pick the faster one. Saving 5% of run time isn't usually worth the costs.
I would go for the simplest approach and that is with the for loop.
The Every loop is something new that not all browsers are compatible with and this mean you will add more code to check this.
Therefore the for loop is the best idea to use .
Thanks
What's the best way to generate 5 random non duplicating integers from 0 - 20?
I'm thinking, use Math.random with floor, loop it 5 times, check for duplicates, if duplicate, random again.
What's your way?
You could generate an array of numbers from 0 to 20, shuffle it and take the first 5 elements of the resulting array.
late answer i know, but:
var a=[];
while(a.length <3) {
var n = Math.round(Math.random() * 20);
if (a.indexOf(n)==-1) a.push(n);
}
=> [14, 17, 19]
Edit: A better solution that this or the others posted here can be found in this answer to this question when it was asked back in 2008. Summarizing: Generate an array (as Darin suggests in his answer below) and shuffle it using the Knuth-Yates-Fisher shuffle. Don't use a naive shuffle, use one that's known to have good results.
That's pretty much how I'd do it, yes. I'd probably use an object to keep track of the integers I already had, since that's convenient. E.g.:
var ints = {};
Then once you've created a new random number, check it and possibly keep it:
if (!ints[number]) {
// It's a keeper
ints[number] = true;
results.push(number);
}