没有重复的置换C#

本文关键字: | 更新日期: 2023-09-27 18:25:32

我是C#的初学者,我正在寻找一个代码来返回集合的所有可能的排列,例如{1,1,2},而不重复:{112121211}。我找到了以下链接,但我不知道如何使用它。

http://www.codeproject.com/Articles/26050/Permutations-Combinations-and-Variations-using-C-G

我尝试过的代码如下。例如,当我试图获得"111"的排列时,它会返回所有可能的重复排列,即六个111。但我正在寻找一种能提供不重复排列的东西。更详细地说,111只是一个排列,而不是六个。

class Program
{
    private static void Swap(ref char a, ref char b)
    {
        if (a == b) return;
        a ^= b;
        b ^= a;
        a ^= b;
    }
    public static void GetPer(char[] list)
    {
        int x = list.Length - 1;
        GetPer(list, 0, x);
    }
    private static void GetPer(char[] list, int k, int m)
    {
        if (k == m)
        {
            Console.Write(list);
        }
        else
            for (int i = k; i <= m; i++)
            {
                   Swap(ref list[k], ref list[i]);
                   GetPer(list, k + 1, m);
                   Swap(ref list[k], ref list[i]);
            }
    }
    static void Main()
    {
        string str = "sagiv";
        char[] arr = str.ToCharArray();
        GetPer(arr);
    }
}

没有重复的置换C#

由于您还没有发布任何代码,所以只能猜测。但是,如果你把问题语句分解开来,那么听起来你只有一个问题,那就是消除输入的重复。那是一个需要解决的琐碎问题。这里有一种方法:

string dedupe = new string(input.ToCharArray().Distinct().ToArray()); 

字符串重复数据消除现在只包含原始字符串输入中的唯一字符。

我终于找到了我要找的代码。

公共静态void置换(int[]ps,int start,int n){

//doSomething(ps);
int tmp = 0;
if (start < n) {
  for (int i = n - 2; i >= start; i--) {
    for (int j = i + 1; j < n; j++) {
      if (ps[i] != ps[j]) {
        // swap ps[i] <--> ps[j]
        tmp = ps[i];
        ps[i] = ps[j];
        ps[j] = tmp;
        permute(ps, i + 1, n);
      }
    }
    // Undo all modifications done by
    // recursive calls and swapping
    tmp = ps[i];
    for (int k = i; k < n - 1;)
      ps[k] = ps[++k];
    ps[n - 1] = tmp;
  }
}

}

相关文章:
  • 没有找到相关文章