【发布时间】:2014-09-09 06:02:42
【问题描述】:
我有一个函数,可以从前一个二进制组合计算下一个二进制组合,并希望将其转换为一个函数,直接通过循环计算二进制组合。二进制数组将非常大,如数百万个元素甚至更多。该怎么做?
组合功能:
void NextBinComb(byte[] b)
{
byte c=1;
for (int x = 0; x < b.Length; x++)
{
byte t = b[x] & c;
b[x] ^= c;
c = t;
}
//print binary combination
Print(b);
}
这会产生:
000000
100000
010000
110000
001000
101000
011000
111000
000100
100100
010100
110100
001100
101100
011100
111100
000010
100010
010010
110010
进入:
//function that calculate binary combination directly by not using previous one
void NextBinComb(k)
{
byte[] b = new byte[k];
int[] tab = new int[k];//indexes
//these loops needs to create b array like function presented here on top
//How to change them to achieve that goal?
for (tab[0] = 0; tab[0] < n; tab[0]++)
for (tab[1] = tab[0] + 1; tab[1] < n; tab[1]++)
for (tab[2] = tab[1] + 1; tab[2] < n; tab[2]++)
for (tab[3] = tab[2] + 1; tab[3] < n; tab[3]++)
for (tab[4] = tab[3] + 1; tab[4] < n; tab[4]++)
...
for (tab[k] = tab[k-1] + 1; tab[k] < n; tab[k]++)
{
//print combination
GetBinComb(tab,b);//Get binary combination
Print(b);
}
}
void GetBinComb(int [] tab, byte [] b)
{
List<byte> list = new List<byte>();
for (int x = 0; x < b.Length; x++)
{
if (tab.Contains(x))
{
list.Add(1);
}
else
{
list.Add(0);
}
}
b=list.ToArray();
}
目标:
byte[] GetCombinationBinaryIndexArray(byte[] binaryComb)
{
//sth
return calculatedBinaryIndex;
}
用法:
GetCombinationBinaryIndexArray 假设产生以下索引:
对于 5 个,n=8:
comb: 11111000 index: 000000
comb: 11110100 index: 100000
comb: 11110010 index: 010000
comb: 11110001 index: 110000
comb: 11101100 index: 001000
comb: 11101010 index: 101000
comb: 11101001 index: 011000
comb: 11100110 index: 111000
对于 6 个,n=8:
comb: 11111100 index: 00000
comb: 11111010 index: 10000
comb: 11111001 index: 01000
comb: 11110110 index: 11000
comb: 11110101 index: 00100
comb: 11110011 index: 10100
comb: 11101110 index: 01100
comb: 11101101 index: 11100
对于 7 个,n=8:
comb: 11111110 index: 000
comb: 11111101 index: 100
comb: 11111011 index: 010
comb: 11110111 index: 110
comb: 11101111 index: 001
comb: 11011111 index: 101
comb: 10111111 index: 011
comb: 01111111 index: 111
对于 7 个,n=12:
comb: 111111100000 index: 000000000
comb: 111111010000 index: 100000000
comb: 111111001000 index: 010000000
comb: 111111000100 index: 110000000
comb: 111111000010 index: 001000000
comb: 111111000001 index: 101000000
comb: 111110110000 index: 011000000
comb: 111110101000 index: 111000000
【问题讨论】:
-
您在顶部描述的
NextBinComb函数不是递归的。 -
递归在哪里?这看起来是个可怕的主意。您要解决什么问题,它与(共)递归有什么关系?
-
递归函数可以从前一个二进制组合中计算出下一个二进制组合。我正在寻找一种将其转换为直接计算二进制组合的循环的方法。目标是将二进制组合映射到大型数组的二进制索引。