Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
148
rated 0 times [  151] [ 3]  / answers: 1 / hits: 14277  / 10 Years ago, thu, april 3, 2014, 12:00:00

I am using two arrays to accomplish a task of checking if values in array1 exist in array2. If so remove the content in array1 and keep checking till array1 is empty. If they dont exist just return from the function. I am using Javascript



I implemented it using classic two for loops which gives a run time of o(n*2). I would like to know if there is any other efficient way to perform this operation using any other data structure that javascript supports. Below is my current implementation



for(var j = 0; j < tempArray.length; j++){
for(var k = 0; k < this.probsSolved.length; k++){
if(tempArray[j] == this.probsSolved[k]){
tempArray.splice(j,1);
if(tempArray.length <= 0){
this.updateAchievements(achID);
this.storage.set(achKey,1);
return;
}
}
}


The thing is I have to call the function under which this operation is performed every 5 seconds and this for me looks highly inefficient.



Could someone suggest a better algorithm or a data structure that performs better than the one above that I can use and how would I use if so.


More From » algorithm

 Answers
12

Putting the elements of array2 in a dictionary data-structure (to ensure that lookup is quick) might help.



See How to do associative array/hashing in JavaScript



In pseudo-code, I would approach like the following:



dict = {}

foreach elem in array2:
insert elem in dict

foreeach elem in array1:
if elem in dict:
remove elem from array1

[#46293] Thursday, April 3, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
samaraanandah

Total Points: 94
Total Questions: 86
Total Answers: 99

Location: Montenegro
Member since Thu, Jun 16, 2022
2 Years ago
;