如何获取数组的所有子集? [英] How to get all subsets of an array?
本文介绍了如何获取数组的所有子集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个数组:[dog, cat, mouse]
最优雅的创作方式是什么:
what is the most elegant way to create:
[,,]
[,,mouse]
[,cat,]
[,cat,mouse]
[dog,,]
[dog,,mouse]
[dog,cat,]
[dog,cat,mouse]
我需要它来处理任何大小的数组.
I need this to work for any sized array.
这本质上是一个二进制计数器,其中数组索引代表位.这大概可以让我使用一些按位运算来计数,但我看不到将其转换为数组索引的好方法.
This is essentially a binary counter, where array indices represent bits. This presumably lets me use some bitwise operation to count, but I can't see a nice way of translating this to array indices though.
推荐答案
string[] source = new string[] { "dog", "cat", "mouse" };
for (int i = 0; i < Math.Pow(2, source.Length); i++)
{
string[] combination = new string[source.Length];
for (int j = 0; j < source.Length; j++)
{
if ((i & (1 << (source.Length - j - 1))) != 0)
{
combination[j] = source[j];
}
}
Console.WriteLine("[{0}, {1}, {2}]", combination[0], combination[1], combination[2]);
}
这篇关于如何获取数组的所有子集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文