Skip to content

Instantly share code, notes, and snippets.

@isoiphone
Created September 29, 2015 22:48
Show Gist options
  • Select an option

  • Save isoiphone/9fb82c009f2e9674f11d to your computer and use it in GitHub Desktop.

Select an option

Save isoiphone/9fb82c009f2e9674f11d to your computer and use it in GitHub Desktop.
Comparing two arrays for changes
enum Change {
case Insert(at: Int)
case Delete(at: Int)
case Move(from: Int, to: Int)
}
extension Change: Printable {
var description: String {
switch self {
case .Insert(let at):
return "(Insert \(at))"
case .Delete(let at):
return "(Delete \(at))"
case .Move(let from, let to):
return "(Move \(from)->\(to))"
}
}
}
func ExtractChanges<T: Hashable>(source: [T], dest: [T]) -> [Change] {
var changes = [Change]()
var sourceIndex = [T: Int]()
for (i,v) in enumerate(source) {
sourceIndex[v] = i
}
for (i,v) in enumerate(dest) {
if let prevIndex = sourceIndex[v] {
if prevIndex != i {
changes.append( .Move(from: prevIndex, to: i) )
} else {
// no change
}
sourceIndex.removeValueForKey(v)
} else {
changes.append( .Insert(at: i) )
}
}
for i in sourceIndex.values {
changes.append( .Delete(at: i) )
}
return changes
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment