Skip to content

Instantly share code, notes, and snippets.

@jnicklas
Created January 4, 2013 19:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnicklas/4455256 to your computer and use it in GitHub Desktop.
Save jnicklas/4455256 to your computer and use it in GitHub Desktop.
def diff(a, b)
a = a.clone # we will mutate a, so clone it
operations = []
# find and remove stuff which is in a, but not in b
a.reverse.each do |item|
unless b.include?(item)
index = a.index(item)
a.delete(item)
operations.push(["delete", index])
end
end
# find and insert stuff which is in b, but not in a
b.each do |item|
unless a.include?(item)
index = b.index(item)
a.insert(index, item)
operations.push(["insert", index, item])
end
end
# sort it
a.each_with_index do |item, aindex|
unless item == b[aindex]
bindex = b.index(item)
a[aindex], a[bindex] = a[bindex], a[aindex]
operations.push(["swap", aindex, bindex])
end
end
operations
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment