Array 1 | Array 2 ================= 1 | 2 2 | 3 3 | 4 5 | 5 | 6
What is a good algorithm to ‘sync’ or combine Array 2 into Array 1? The following needs to happen:
- Integers in Array 2 but not in Array 1 should be added to Array 1.
- Integers in both Arrays can be left alone.
- Integers in Array 1 but not in Array 2 should be removed from Array 1.
I’ll eventually be coding this in Obj-C, but I’m really just looking for a pseudo-code representation of an efficient algorithm to solve this problem so feel free to suggest an answer in whatever form you’d like.
EDIT:
The end result I need is bit hard to explain without giving the backstory. I have a Cocoa application that has a Core Data entity whose data needs to be updated with data from a web service. I cannot simply overwrite the contents of Array 1 (the core data entity) with the content of Array 2 (the data parsed from the web into an array) because the Array 1 has relationships with other core data entities in my application. So basically it is important that integers contained in both Arrays are not overwritten in array one.
I’m kind of guessing since your example leaves some things up in the air, but typically in situations like this I would use a set. Here’s some example code in Obj-C.