c# - 两个字符的组合

标签 c# combinations

我将输入作为 int 并根据该输入我想要两个字符的组合, 例如 我将输入作为 2 并且我有两个字符 x 和 y 所以我想要这样的组合

    xx,yy,xy,yx

如果输入是3,我要

    xxx,xyy,xxy,xyx,yxx,yyy,yxy.yyx

等等,我已经尝试了下面的代码,

     int input1 = 4;
        Double totalpossibilities = Math.Pow(2, input1);
        string[] PArray = new string[Convert.ToInt16(totalpossibilities)];
        char[] chars = new char[] { 'x', 'y'};

        for (int i = 0; i < totalpossibilities; i++)
        {
            string possibility = "" ;
            for (int j = 0; j < input1; j++)
            {
                Random random = new Random();
                int r = random.Next(chars.Length);
                char randomChar = chars[r];
                possibility = possibility + randomChar;

            }
            if (PArray.Contains(possibility))
            {
                i--;
            }
            else
                PArray[i] = possibility;
        }

但是正如你所看到的,我使用的是随机函数,所以我需要很长时间才能完成,是否有任何不同的逻辑?

最佳答案

使用从 here 中逐字复制的笛卡尔积扩展方法的副本:

static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) 
{ 
  IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; 
  return sequences.Aggregate( 
    emptyProduct, 
    (accumulator, sequence) => 
      from accseq in accumulator 
      from item in sequence 
      select accseq.Concat(new[] {item})); 
}

然后在你的代码中你可以:

IEnumerable<char> possibleCharacters = "xy";//change to whatever
int numberOfDigits = 3;

var result = Enumerable.Repeat(possibleCharacters, numberOfDigits)
     .CartesianProduct()
     .Select(chars => new string(chars.ToArray()));

//display (or do whatever with) the results
foreach (var item in result)
{
    Console.WriteLine(item);
}

关于c# - 两个字符的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10606277/

相关文章:

c# - 在 C# 中重写 Paint 控件

C# - 关键字用法 virtual+override 与 new

python - 来自迭代器的随机项目?

Python itertools 组合长度

javascript - 检查是否存在具有值的组合选择 web 服务 prestashop

c# - 在 C# 中使用泛型属性

c# - 您如何使用 Fluent Validation 对列表中的每个字符串进行验证?

c# - .net 中的 Soap 登录

algorithm - 来自非统一表的所有可能组合,每列只有一个值

Python根据值列表创建所有字典的组合