如何计算位图? [英] how to compute a bitmap?
问题描述
我要寻找一种方式来获得一个列表项目的所有组合。
我想是有两个渔政船阵,类似地以位图
例如位[] [] MYBITMAP;
I am looking for a way to get all combination of a list item. what i thinking is to have a two dimention array, similary to a bit map e.g bit[][] mybitmap;
例如,如果我有我的名单4项A,B,C,D
我希望我的位图是填充像这样
for example if i have 4 item in my list "A, B, C, D" i want my bitmap to be populate like this
A B C D
0, 0, 0, 1 --> D
0, 0, 1, 0 --> C
0, 0, 1, 1 --> C, D
0, 1, 0, 0 --> B
0, 1, 0, 1
0, 1, 1, 0
0, 1, 1, 1
1, 0, 0, 0
1, 0, 0, 1
1, 0, 1, 0
1, 0, 1, 1 --> A, C, D
1, 1, 0, 0
1, 1, 0, 1
1, 1, 1, 0
1, 1, 1, 1 --> A, B, C, D
但我怎么能写一些C#code来填充我的位图?
(PS:我的名单可能有大约80项到90,而不是100到200,刚刚确认)
but how can i write some C# code to populate my bit map? (PS: my list might have items around 80 to 90, not 100 to 200, just confirmed)
感谢
推荐答案
我相信你并不需要所有的组合存储在内存中。
从全零位(第一组合)阵列刚开始。为了得到下一个组合只需添加1〜previous组合的最后一位(这是很容易实现的操作)。等等。
低内存占用,支持高达2亿元的数字。 :)
I believe you don't need to store all combinations in memory. Just start from array with all zero bits (first combination). To get next combination just add 1 to last bit of previous combination (it is easily implementing operation). And so on. Low memory usage, support of up to 2 billions of digits. :)
private void button1_Click(object sender, EventArgs e)
{
string[] items = {"A", "B", "C", "D"};
bool[] bits = new bool[items.Length];
for (int i = 0; i < bits.Length; i++)
{
bits[i] = false;
}
while (!bits.All(x => x))
{
listBox1.Items.Add(string.Join(", ", GetCombination(items, bits)));
AddBit(bits, bits.Length - 1);
}
}
public string[] GetCombination(string[] items, bool[] bits)
{
List<string> combination = new List<string>();
for (int i = 0; i < bits.Length; i++)
{
if (bits[i])
{
combination.Add(items[i]);
}
}
return combination.ToArray();
}
private void AddBit(bool[] bits, int pos)
{
if (pos < 0)
{
// overflow :)
return;
}
if (bits[pos])
{
bits[pos] = false;
AddBit(bits, pos - 1);
}
else
{
bits[pos] = true;
}
}
这篇关于如何计算位图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!