I have such function
applyDiff(List orders, List ordersToAdd, int[] ordersToRemove) {
}
This function should add orders from orderToAdd to orders and remove some orders from orders, indexes of orders to be removed are passed in ordersToRemove array.
The problem is: every time order from ordersToAdd is inserted into orders somewhere at position pos, all indexes from orderToRemove that a greather than pos must be increased at 1.
So should I dinamically modify ordersToRemove array?
What is general “algorithm” or modifing a collection when I should at the same time add-remove elements and I have indexes of elements to be removed?
Note I can not break this task at two (orders adding, orders removing) because the order is very important and function inside it decides in what order orders should be added and removed.
You have not specified explicitly how do you determine at which positions exactly you insert, neither what is the semantics of
int[] ordersToRemove(though for the latter I assume it is indices of objects to remove considering your notes). However I can still suggest an “algorithm” and you will apply it accordingly:Introduce one more variable in you method
indexIncrease. Initialize it to0. Every time you add toordersToAddincrease this variable. Every time you consider a value fromint[] ordersToRemovedo not just consider this value, but rather considerordersToRemove[i] + indexIncrease. Thus you will get your updated value fromordersToRemovewithout the need of iterating of over the whole array and increasing the values after each addition.Note that applying this “alogrithm” you ensure that the list
ordersis always in its current state, but theordersToRemovewill not be updated at all. hopefully this will work for you.EDIT As per the comments and the completely changed problem description:
ordersToRemoveif you use binary index tree. With it every modification becomesO(log n)in complexity, where n is the total number of orders that will exist.As seen overall: I advise you to stick with the current solution.