【问题标题】:c# output possible routesc# 输出可能的路线
【发布时间】:2012-03-09 18:16:50
【问题描述】:

我有一个动态数组,例如包含 (int) {1, 2, 3}

我想生成以下内容:

123 132 213 231 312 321

(注意排序)

我正在考虑为上述构建 3 个循环,但是当数组长度为 16 时,该解决方案效果不佳,我需要一个动态解决方案。

你能帮忙吗?谢谢你。这是一个个人项目。

【问题讨论】:

  • 如果输入是 {1,1,2,3},预期的输出是什么
  • 你尝试了什么?有没有具体问题?本网站不会为您编写代码。
  • 就像我说的,我想到了多个循环,但这似乎不适合使用,因为数组的长度不是恒定的。

标签: c# algorithm combinations combinatorics


【解决方案1】:

您可以使用优秀的EvenMoreLINQ project 中的Permutations Extension Method

例子:

foreach (var p in new int[] { 1, 2, 3 }.Permutations())
{
    Console.WriteLine(string.Join(", ", p));
}

输出:

1, 2, 3
1, 3, 2
2, 1, 3
2, 3, 1
3, 1, 2
3, 2, 1

【讨论】:

    【解决方案2】:

    您正在谈论按字典顺序列出数组的所有排列。让我们首先假设我们有一个排列,我们想要生成一个按字典顺序排列的排列。以下是我们必须采取的步骤(这里a 用于数组变量,):

    1. 找到最大的i,其中a[i] < a[i+1]
    2. 找到最大的j,其中a[i] < a[j]
    3. a[i]a[j] 交换。
    4. a[i+1]a[n-1](包括两者)之间反转元素。

    现在从第一个排列(基本上是一个排序数组)开始,我们可以一次一个地产生所有排列,每次都使用这些步骤,直到我们在第一步中找不到i。发生这种情况时,这意味着我们刚刚生成了按字典顺序排列的最后一个排列。

    更新:这是代码示例 - 函数接受一个表示排列的数组并按字典顺序生成(并打印)下一个。

    /// <summary>
    /// Generates and prints next permutation lexicographically.
    /// </summary>
    /// <param name="a">An array representing a permutation.</param>
    /// <returns><c>true</c> if next permutation was generated succesfully, <c>false</c> otherwise.</returns>
    public bool PrintNextPermutation(int[] a)
    {
        int i = a.Length - 2;
        while (i >= 0 && a[i] >= a[i + 1]) i--;
    
        if (i <0)
        {
            // it was the last permutation
            return false;
        }
    
        int j = a.Length - 1;
        while (a[i] >= a[j]) j--;
    
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    
        Array.Reverse(a, i + 1, a.Length - (i + 1));
    
        foreach (int item in a)
        {
            Console.Write(item + " ");
        }
        Console.WriteLine();
    
        return true;
    }
    

    【讨论】:

    • 我开始编写代码,但似乎我对结构和我应该采取的一些行动感到困惑。你能举个小例子吗?谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-22
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    • 2014-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多