【问题标题】:How to find a list of steps needed to reorder a list to get another list?如何找到重新排序列表以获取另一个列表所需的步骤列表?
【发布时间】:2015-07-08 23:37:57
【问题描述】:

假设我们必须列出(表示为数组或任何语言的任何内容)。这些列表同样长并且包含相同的独特元素 - 但顺序不同。

例如:

First list: A, B, C, D
Second list: A, D, B, C

现在我要查找的是重新排序第一个列表以匹配第二个列表所需的步骤列表。在这个例子中,只有一步:

3 -> 1

也就是说,因为索引 3 处的元素被移动到索引 1。请注意,B 和 C 确实更改了索引,但这只是因为它们在 D 插入索引 1 时为 D“腾出空间”,所以这step 不应包含在移动列表中!

另一个例子:

First list: A, B, C, D, E, F
Second list: D, B, A, C, E, F
Changes:  3 -> 0, 1 -> 1

因为 D 被移动到索引 0 而 B 被移动到 1。请注意,对于 B,我们使用原始索引 1 而不是执行第一次移动后的索引。

这些步骤都是“一次执行”——这意味着没有顺序,但我们只是通过将移动的元素放在它们应该在的位置然后用剩余的元素填充剩余的插槽来创建一个新列表。

现在我的问题是:有人知道任何算法可以做到这一点吗?

提前致谢! :)

【问题讨论】:

  • 您需要找到最短的步骤列表还是可以接受任何合适的列表?
  • @Alexei Shestakov:任何合适的列表都是可以接受的! :-)
  • 你不能把所有的元素都移动到它们各自的位置吗?因此,对于您的第二个示例,移动将是: 5 -> 5, 4-> 4, 3 -> 0, 2 -> 3, 1 -> 1, 0 -> 2?
  • 我没有那样想...好吧,我想我确实需要最短的列表。 ://

标签: arrays algorithm list reorderlist


【解决方案1】:

如果您需要最短的步骤列表,请在列表上执行 Longest Increasing Subsequence 并仅更改该子序列之外元素的位置。

【讨论】:

    【解决方案2】:

    如果您不需要最短的步骤列表并且由于某种原因无法接受简单的解决方案,那么这是我在 python 中的解决方案。我认为这很简单,可以理解:

    first = ['A', 'B', 'C', 'D']
    second = ['A', 'D', 'B', 'C']
    steps = []
    tmp = second[:]  # copy second list to temp list
    for pos in range(len(first)):
        # find position where first and temp lists are different
        if first[pos] != tmp[pos]:
            # get element that should be placed in position 'pos'
            element = first[pos]
            # get position of that element in second list
            sec_pos = second.index(element)
            # add step: move element from sec_pos to pos
            step = '%d -> %d' % (sec_pos, pos)
            steps.append(step)
            # do permutation in temp list
            tmp.remove(element)  # remove element
            tmp.insert(pos, element)  # put it in proper position
            # print step and intermediate result
            print step, tmp
    print steps
    

    输出:

    2 -> 1 ['A', 'B', 'D', 'C']

    3 -> 2 ['A', 'B', 'C', 'D']

    ['2 -> 1', '3 -> 2']

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-09
      • 1970-01-01
      • 2015-02-27
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-29
      相关资源
      最近更新 更多