我需要把集合中的数字组合起来以缩小集合的大小。我需要所有可能的组合。
这里有两个例子可以说明我的情况。
1)SET1有4个条目,SET2有2个。所以我们需要在每种情况下合并两个数字。
Set1 = {70, 100, 50, 200}; Set2 = {"part1", "part2"}
All combinations I want to retrive should look like following:
"part1" |"part2"
70 + 100 | 50 + 200
70 + 50 | 100 + 200
70 + 200 | 50 + 100
100 + 50 | 70 + 200
100 + 200 | 50 + 70
50 + 200 | 100 + 70
50 | 70 + 100 + 200
70 | 50 + 100 + 200
100 | 50 + 70 + 200
200 | 50 + 70 + 100
70 + 100 + 200 | 50
50 + 100 + 200 | 70
50 + 70 + 200 | 100
50 + 70 + 100 | 200
2)Set1有4个条目,Set2有3个条目所以我们需要两个数字合并一次。
Set1 = {70, 100, 50, 200}; Set2 = {"part1", "part2", "part3"}
All combinations I want to retrive should look like following:
"part1" |"part2" |"part3"
70 | 100 | 50 + 200
70 | 50 | 100 + 200
70 | 200 | 50 + 100
50 | 70 | 100 + 200
50 | 100 | 70 + 200
50 | 200 | 70 + 100
100 | 70 | 50 + 200
100 | 200 | 50 + 70
100 | 50 | 200 + 70
200 | 70 | 50 + 100
200 | 100 | 50 + 70
200 | 50 | 70 + 100
70 | 50 + 200 | 100
70 | 100 + 200 | 50
70 | 50 + 100 | 200
50 | 100 + 200 | 70
50 | 200 + 70 | 100
50 | 70 + 100 | 200
100 | 50 + 200 | 70
100 | 50 + 70 | 200
100 | 200 + 70 | 50
200 | 50 + 100 | 70
200 | 50 + 70 | 100
200 | 70 + 100 | 50
50 + 200 | 100 | 70
100 + 200 | 50 | 70
50 + 100 | 200 | 70
100 + 200 | 70 | 50
70 + 200 | 100 | 50
70 + 100 | 200 | 50
50 + 200 | 70 | 100
50 + 70 | 200 | 100
200 + 70 | 50 | 100
50 + 100 | 70 | 200
50 + 70 | 100 | 200
70 + 100 | 50 | 200
我很感激你的帮助。我想不出任何话来更好地解释我的担心。但我很乐意回答任何问题有你的帮助,我也许能证实我的问题。
虽然应用程序是用C编写的,但我不一定需要源代码我的问题是概念而不是实现。
提前谢谢!
最佳答案
好吧,这里的总体思路是
从{0, 0, 0, 0}
开始-对于Set1
的每个元素都是零。0
表示Set2
中的第一项。因此,第一个数组是“所有Set1
中的内容都属于Set2
中的第一项”。
返回与此对应的分区。
将{0, 0, 0, 0}
增加到{0, 0, 0, 1}
。1
表示Set2
中的第二项。因此,这个数组是“除最后一个属于Set1
中的第二个项目外,Set2
中的所有内容都属于Set2
中的第一个项目”。
返回与此对应的分区。
将{0, 0, 0, 1}
增加到{0, 0, 1, 0}
(如果{0, 0, 0, 2}
中有两个以上的项,则为Set2
)。
重复,直到您点击{1, 1, 1, 1}
(或{2, 2, 2, 2}
等),无法继续。
然后,您可以添加逻辑来说明“如果一个分区有任何空的部分,就不用费心了”。
我的实现如下:
static IEnumerable<ILookup<T, U>> Pool<T, U>(T[] t, U[] u)
{
// Start off with all zeroes.
int[] indices = new int[u.Length];
while (true)
{
// Build a Lookup from the array.
var lookup = (Lookup<T,U>)indices
.Select((ti, ui) => new { U = u[ui], T = t[ti] })
.ToLookup(p => p.T, p => p.U);
// Only return it if every part is non-empty.
if (lookup.Count == t.Length)
yield return lookup;
// Increment to the next value.
int toIncrement = u.Length - 1;
while (++indices[toIncrement] == t.Length)
{
indices[toIncrement] = 0;
// Stop when we can't increment further.
if (toIncrement-- == 0)
yield break;
}
}
}
你可以称之为
foreach (var q in Pool(
new[] { "part1", "part2" },
new[] { 70, 100, 50, 200 }))
{
foreach (int i in q["part1"])
Console.Write(i + " ");
Console.Write("| ");
foreach (var ii in q["part2"])
Console.Write(ii + " ");
Console.WriteLine();
}
注意,我之所以创建参数数组是因为我很懒,但您可以将它们列为列表,或者使它们可枚举并对它们调用
ToArray
。关于c# - 一组数字中的池号以匹配另一组的大小,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14438404/