简体   繁体   English

基于两个列表的差异创建指令列表

[英]Create instructions list based on a diff of two lists

I have two lists (A,B) with values and I want to create an instructions list of operations which will change list A into B. 我有两个带有值的列表(A,B),我想创建一个操作指令列表,它将列表A更改为B。
There are no duplicates in the lists but the order is important. 列表中没有重复项,但是顺序很重要。
Example: 例:

 A              B
 ================
 1              5
 2              4
 3              6
 4              3
                1
                7

I'm looking for an efficient algorithm which will generate the minimal list of instructions such as: 我正在寻找一种高效的算法,该算法将生成最少的指令列表,例如:
Delete at, Insert at, Move from to (at, from and to are locations in the array) 删除位置,插入位置,移至至(移至数组中的位置)

For the above example: (indexes starts from 1) 对于上面的示例:(索引从1开始)

                       1 2 3 4
Move from 1 to 4    -> 2 3 4 1
Del 1               -> 3 4 1
Insert 5 location 1 -> 5 3 4 1
Move from 3 to 2    -> 5 4 3 1
Insert 6 location 3 -> 5 4 6 3 1
Insert 7 location 6 -> 5 4 6 3 1 7

If there is Java ready algorithm it will be great, but other solutions are welcomed as well. 如果有支持Java的算法,那就更好了,但也欢迎其他解决方案。 In real life scenario the lists contain java objects which are comparable. 在现实生活中,列表包含可比较的Java对象。

Here's an O(n log n)-time algorithm that computes a shortest edit sequence, where n is the total length of the two lists. 这是O(n log n)-时间算法,用于计算最短的编辑序列,其中n是两个列表的总长度。 First, delete entries from A that are not in B, recording them as deletions. 首先,从A中删除不在B中的条目,将其记录为删除。 Second, delete entries from B that are not in A, recording them in reverse order as insertions. 其次,从B中删除不在A中的条目,以相反的顺序记录它们作为插入。 Clearly all of these operations are necessary. 显然,所有这些操作都是必需的。

Now we have a list A' that needs to be transformed into one of its permutations B'. 现在我们有了一个列表A',需要将其转换为其排列B'之一。 The shortest edit sequence consists solely of moves, since an insert/delete operation must have a counterpart, and such a pair can be replaced by one move. 最短的编辑序列仅由移动组成,因为插入/删除操作必须具有对应的对象,并且可以用一个移动来替换这样的一对。 Let's assume for the sake of exposition that A' is in sorted order; 为了说明起见,假设A'处于排序顺序; for the implementation, we could implement a custom comparator. 对于实现,我们可以实现一个自定义比较器。

Consider a shortest move sequence. 考虑最短的移动顺序。 The elements not moved must appear in order in B', ie, they constitute an increasing subsequence of B'. 未移动的元素必须按顺序出现在B'中,即,它们构成B'的递增子序列。 To compute a shortest edit sequence, use dynamic programming to find a longest increasing subsequence of B' in time O(n log n). 要计算最短的编辑序列,请使用动态编程在时间O(n log n)中找到B'的最长递增子序列 Move all of the other elements appropriately. 适当移动所有其他元素。 Most of the implementation complexity here is bookkeeping, though life is a lot easier if you can tolerate a quadratic-time implementation. 尽管您可以忍受二次时间的实现,但实现起来的大多数复杂性是簿记,尽管生活会容易得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM