Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array difference as a series of actions

In short: I have two arrays which may be different, and I'll like to get the difference/transformation as a series of "actions" (adds and removes). That is, in a basic example:

Current: [a, b, d]
Desired: [a, b, c, d]
Actions: Add c in position 2

Basically, the instructions are how to transform the current array so that it's got the same members and order as the desired array. For my application, each change triggers events which update UI and so on, so it would be highly preferable if the actions were not "redundant": that is, the above could have been remove d, add c @ 2, add d @ 3, but this would cause a lot of unwanted processing elsewhere in the system.

Perhaps as another example which might help illustrate:

Current: [a, b, d]
Desired: [b, c, d, a]
Actions: remove a, add c @ 1, add a @ 3

I figure this is something which has been solved before, but it's kinda difficult to search for it since "array difference" doesn't give you the right results.

If it matters, I'm implementing this in Javascript, but I guess the algorithm is language agnostic.

like image 256
nickf Avatar asked Dec 19 '13 18:12

nickf


People also ask

What is the difference between array and Series?

Series as generalized NumPy array The essential difference is the presence of the index: while the Numpy Array has an implicitly defined integer index used to access the values, the Pandas Series has an explicitly defined index associated with the values.

Is an array a series of variables?

In computer science, array is a data type that represents a collection of elements (values or variables), each selected by one or more indices (identifying keys) that can be computed at run time during program execution. Such a collection is usually called an array variable or array value.

What is an array An array is a series?

An array is a series of memory locations – or 'boxes' – each of which holds a single item of data, but with each box sharing the same name. All data in an array must be of the same data type . For example, imagine that a score table in a game needs to record ten scores.


1 Answers

This does indeed exists, it's called the edit distance. The basic algorithm doesn't remember the kind of edits, but it's easily modified.

One type of edit distance is the Levenshtein distance. This wikipedia page contains some code snippets you may find useful.

Hirschberg's algorithm may also be useful.

like image 184
Noctua Avatar answered Sep 21 '22 09:09

Noctua