给定n个不同项目的列表,我如何一次逐步浏览每次交换一对值的项目的每个排列? (我认为这是可能的,当然感觉应该是。)

我正在寻找的是一个迭代器,该迭代器会产生下一对交换项目的索引,因此,如果迭代n!-1次,它将跨过n!列表以某种顺序排列。如果再次迭代它将将列表还原到其起始顺序,这将是一个奖励,但这不是必需的。如果所有对涉及第一个(分别为最后一个)元素作为对的一个,则该函数只需要返回一个值,这也是一个奖励。

示例: - 对于3个元素,您可以与第一个和第二个元素交替交换最后一个和第二个元素,以通过排列循环,即:( abc)交换0-2 =>(cba)1-2(cab)0-2(cab)0-2( BAC)1-2(BCA)0-2(ACB)。

我将在C中实施,但可能会以大多数语言来解决解决方案。

有帮助吗?

解决方案 2

啊,一旦我计算了n = 4的序列(用“始终将第一项交换另一个”约束),我就能找到序列 A123400 在OEIS中,告诉我我需要“ Ehrlich的交换方法”。

Google找到了我 C ++实现, ,我想 这个 在GPL下。我也找到了诺斯的 束2b 它描述了我的问题的各种解决方案。

一旦我进行了测试的C实现,我将使用代码更新此信息。

这是一些基于Knuth的描述实现Ehrlich的方法的Perl代码。对于最多10个项目,我在每种情况下都测试了它正确生成完整的排列列表,然后停止。

#
# Given a count of items in a list, returns an iterator that yields the index
# of the item with which the zeroth item should be swapped to generate a new
# permutation. Returns undef when all permutations have been generated.
#
# Assumes all items are distinct; requires a positive integer for the count.
#
sub perm_iterator {
    my $n = shift;
    my @b = (0 .. $n - 1);
    my @c = (undef, (0) x $n);
    my $k;
    return sub {
        $k = 1;
        $c[$k++] = 0 while $c[$k] == $k;
        return undef if $k == $n;
        ++$c[$k];
        @b[1 .. $k - 1] = reverse @b[1 .. $k - 1];
        return $b[$k];
    };
}

示例使用:

#!/usr/bin/perl -w
use strict;
my @items = @ARGV;
my $iterator = perm_iterator(scalar @items);
print "Starting permutation: @items\n";
while (my $swap = $iterator->()) {
    @items[0, $swap] = @items[$swap, 0];
    print "Next permutation: @items\n";
}
print "All permutations traversed.\n";
exit 0;

根据要求,Python代码。 (抱歉,这可能不是过分惯用的。受到改进的建议。)

class ehrlich_iter:
  def __init__(self, n):
    self.n = n
    self.b = range(0, n)
    self.c = [0] * (n + 1)

  def __iter__(self):
    return self

  def next(self):
    k = 1
    while self.c[k] == k:
      self.c[k] = 0
      k += 1
    if k == self.n:
      raise StopIteration
    self.c[k] += 1
    self.b[1:k - 1].reverse
    return self.b[k]

mylist = [ 1, 2, 3, 4 ]   # test it
print "Starting permutation: ", mylist
for v in ehrlich_iter(len(mylist)):
  mylist[0], mylist[v] = mylist[v], mylist[0]
  print "Next permutation: ", mylist
print "All permutations traversed."

其他提示

我敢肯定,这对您来说太晚了,但是我在这个问题上找到了一个不错的补充: Steinhaus – Johnson -Trotter算法 它的变体可以按照您的要求完成。此外,它具有额外的属性,它总是交换相邻索引。我试图在Java中实现其中一种变体(偶数)作为迭代器,并且效果很好:

import java.util.*;

// Based on https://en.wikipedia.org/wiki/Steinhaus%E2%80%93Johnson%E2%80%93Trotter_algorithm#Even.27s_speedup
public class PermIterator
    implements Iterator<int[]>
{
    private int[] next = null;

    private final int n;
    private int[] perm;
    private int[] dirs;

    public PermIterator(int size) {
        n = size;
        if (n <= 0) {
            perm = (dirs = null);
        } else {
            perm = new int[n];
            dirs = new int[n];
            for(int i = 0; i < n; i++) {
                perm[i] = i;
                dirs[i] = -1;
            }
            dirs[0] = 0;
        }

        next = perm;
    }

    @Override
    public int[] next() {
        int[] r = makeNext();
        next = null;
        return r;
    }

    @Override
    public boolean hasNext() {
        return (makeNext() != null);
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }

    private int[] makeNext() {
        if (next != null)
            return next;
        if (perm == null)
            return null;

        // find the largest element with != 0 direction
        int i = -1, e = -1;
        for(int j = 0; j < n; j++)
            if ((dirs[j] != 0) && (perm[j] > e)) {
                e = perm[j];
                i = j;
            }

        if (i == -1) // no such element -> no more premutations
            return (next = (perm = (dirs = null))); // no more permutations

        // swap with the element in its direction
        int k = i + dirs[i];
        swap(i, k, dirs);
        swap(i, k, perm);
        // if it's at the start/end or the next element in the direction
        // is greater, reset its direction.
        if ((k == 0) || (k == n-1) || (perm[k + dirs[k]] > e))
            dirs[k] = 0;

        // set directions to all greater elements
        for(int j = 0; j < n; j++)
            if (perm[j] > e)
                dirs[j] = (j < k) ? +1 : -1;

        return (next = perm);
    }

    protected static void swap(int i, int j, int[] arr) {
        int v = arr[i];
        arr[i] = arr[j];
        arr[j] = v;
    }


    // -----------------------------------------------------------------
    // Testing code:

    public static void main(String argv[]) {
        String s = argv[0];
        for(Iterator<int[]> it = new PermIterator(s.length()); it.hasNext(); ) {
            print(s, it.next());
        }
    }

    protected static void print(String s, int[] perm) {
        for(int j = 0; j < perm.length; j++)
            System.out.print(s.charAt(perm[j]));
        System.out.println();
    }
}

将其修改为无限迭代器,该迭代器在末尾重新启动周期,或者将返回交换索引而不是下一个排列的迭代器。

这里 收集各种实现的另一个链接。

查看C ++标准库功能Next_permuation(...)。那应该是一个很好的起点。

你可以看看 https://sourceforge.net/projects/swappermoutt/ 这是您要求的Java实现:生成掉期的迭代器。一段时间以前创建了一个最近更新的。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top