【问题标题】:Permutations on Dictionary in C#C#中字典的排列
【发布时间】:2015-03-12 03:41:39
【问题描述】:

我有一本包含键和值的字典。我正在尝试获取所有可能的键组合而不重复。所以 AB 和 BC 和 CDE 但不是 BA。这些值此时并不重要,稍后我将使用它们。我该怎么做?

Dictionary<string, int> datadict = new Dictionary<string, int>();

datadict.Add("A", 310);
datadict.Add("B", 200);
datadict.Add("C", 510);
datadict.Add("D", 340);
datadict.Add("E", 230);
datadict.Add("F", 940);
datadict.Add("G", 470);
datadict.Add("H", 430);
datadict.Add("I", 440);
datadict.Add("J", 360);

【问题讨论】:

  • 你能定义你的确切要求吗?到目前为止你做了什么?也只是A,B等键吗?
  • 这是一个常见的编程“问题”。这是一个很好的资源,codeproject.com/Articles/37215/…
  • @KcDoD 我正在尝试一点一点地翻译一个python程序,我大部分都理解它,但对C#的了解有限。是的,在我制作更多唯一标识符之前,它现在只是一个字母 A-Z。
  • @RaySuelzer 谢谢,我会检查一下

标签: c# dictionary combinations permutation


【解决方案1】:

可能有一些LINQfor-loops

使用LINQ将密钥集提取为array

var KeyList = datadict.Select(r => r.Key).ToArray();

示例程序:2个字符的组合

// Keys are extracted from Dictionary : A String Array
var KeyList = datadict.Select(r => r.Key).ToArray();
// Values are extracted from Dictionary : An int Array
var ValueList = datadict.Select(r => r.Value).ToArray();

// Here I have provided a simple algorithm to get Combinations of Two characters
// Ex : AB , AC ... 
// Does not get AA. BB .. OR BA, CA..

int res=0;
// Outer Loop walk through all elements
for (int i = 0; i < KeyList.Length; i++)
{
     // Inner loop walk from outer loop index +1 
     for (int j = i+1; j < KeyList.Length; j++)
     {
          // Find the SUM 
          res=ValueList[i]+ValueList[j];

          // Permutations and the SUM
          Console.WriteLine(KeyList[i]+KeyList[j]+"  "+res);
     }
}

输出:

AB
AC
AD
.
.
IJ

【讨论】:

  • 哦,你知道吗,我刚刚意识到,如果我想获得 A-Z 的所有可能组合,那将是巨大的。这就是每个值旁边的值进来的地方。我想过滤结果,以便只输出总和小于最大值(例如 900)的组合。我想我可能应该用那个重新发布,因为你们可能想知道所有这些组合的 id 到底是做什么的!
  • 我们无法为您的要求提供准确的代码。但是是的,我试图为您提供一种方式 :) ..
  • 这很好,但是 3 个字符,或 4 个字符,或者理想情况下尽可能多的字符呢?我认为这将意味着更多的嵌套循环,所以我无法让我的大脑告诉我需要什么来代替它。但感谢您的帮助。
  • @Kian 这需要一个算法 :) 简单地说是循环,但比我最简单的方式更合适:) 希望你能从中得到一些东西。此外,您可能不需要重新发明轮子,将会有大量可用的算法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-19
相关资源
最近更新 更多