You have 2 arrays.
arrA is empty.
arrB is full of stuff (what it's full of doesnt matter, but assume it's huge).
When a user does a thing, an item is removed from arrB and that item is placed in arrA.
When a user does a different thing, it pulls items from arrA and puts it in arrB.
Is it possible to do this without having a loop within a loop?
Or to put it in computer science terminology:
Is it possible to do this with linear ( ϴ(n) ) time/space complexity?
Right now I have something that is at least ϴ(n*k)
(where n is the length of arrB, and k is the number of items passed to applyItems):
var arrA = [], arrB = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
function addToArray(arrayToAddTo, item){
if(arrayToAddTo.indexOf(item) === -1){
arrayToAddTo.push(item);
}
}
function removeFromArray(arrayToRemoveFrom, item){
var i = arrayToRemoveFrom.length;
var temp = [];
while(i--){
if(arrayToRemoveFrom[i] !== item){
temp.push(arrayToRemoveFrom[i]);
}
}
return temp;
}
function applyItems(arrayOfItems){
var i = arrayOfItems.length;
while(i--){
var current = arrayOfItems[i]
addToArray(arrA, current);
arrB = removeFromArray(arrB, current);
}
}
applyItems([0, 5, 3]);
console.log(arrA);
console.log(arrB);
applyItems works, but is not efficient.
Is it possible to decrease the time/space complexity here?
Based on my comment:
You can use native tools that will be way faster than manually looping. removeFromArray can use indexOf to get the position of the one to remove and then uses splice to remove it. Also you can work with reference instead of recreating the array every time.
with some other optimizations...
var arrA = [], arrB = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
function addToArray(item){
if(arrA.indexOf(item) === -1){
arrA.push(item);
}
}
function removeFromArray(item){
var index = arrB.indexOf(item);
if (index > -1) {
arrB.splice(index, 1);
}
}
function applyItems(arrayOfItems){
arrayOfItems.map(function(item) {
addToArray(item);
removeFromArray(item);
});
}
applyItems([0, 5, 3]);
console.log(arrA);
console.log(arrB);