返回所有排列的函数

时间:2015-12-22 05:42:48

标签: function rust permutation

我想创建一个函数来返回序列的所有排列。我从Rosetta Code中拿了一个例子并尝试在Rust中编写它,但它不起作用。当我尝试修复它时,我会导致溢出或再次破坏它。此代码有一个算术溢出错误:

int

如果有更好的方法,我想知道,否则我需要有关如何解决此问题的想法。

2 个答案:

答案 0 :(得分:3)

看一下你所需要的permutohedron箱子。请查看其benchmarkstests,了解如何使用它。

基本上,您将&mut数据提供给构建Heap,然后您可以在其上调用next_permutation()以获得Option的可变引用置换数据。它是Option,因此None可以表示没有剩余的排列。请注意,Heap也会实现Iterator,因此您也可以使用for permutation in heap { ... }

答案 1 :(得分:3)

  

此代码有算术溢出错误

如果我做了很少的更改(见下文)甚至让你的代码编译,我会收到这个错误:

thread '<main>' panicked at 'arithmetic operation overflowed', <anon>:26

读取错误 - 告诉您导致问题的行。看第26行,我看到了:

items.push(item[item.len() - 1]);

您的item.len()为零,并且您试图从中减去1。这会导致崩溃。别这么做。

fn permutations_(sequence: Vec<i32>) -> Vec<Vec<i32>> {
    if sequence.len() == 0 {
        let x: Vec<Vec<i32>> = vec![vec![]];
        return x
    }

    let mut result: Vec<Vec<i32>> = Vec::new();

    for (i, item) in permutations_(sequence[0..sequence.len() - 1].into()).iter().enumerate() {
        let mut n = (0..item.len() + 1).collect::<Vec<usize>>();
        if i % 2 == 0 {
            n.reverse();
        }

        for k in n {
            let mut items = Vec::new();

            for x in &item[0..k] {
                items.push(*x);
            }

            items.push(item[item.len() - 1]);

            for x in &item[k..item.len()] {
                items.push(*x);
            }

            result.push(items);
        }
    }

    result
}

fn main() {
    println!("{:?}", permutations_(vec![1]))
}
相关问题