我有一个包含二进制数的字符串数组: {" xx0x"," 110x"," 100x"," 010x"," x01x"," 1010"," 0011"," 0111"," 1111"," xxxx"," 0001", " 1010"," 0110" };
' x'可以是0或1。 我需要创建一个包含所有可能性的新数组。
我考虑过创建一个包含所有选项的数组而不是比较它,但我不确定如何进行比较。
答案 0 :(得分:0)
这是一个将枚举所有可能值的代码。
string[] patterns = { "xx0x", "110x", "100x", "010x", "x01x", "1010", "0011", "0111", "1111", "xxxx", "0001", "1010", "0110" };
// - Loop for each input pattern
foreach (string pattern in patterns)
{
// - Count the varying characters and memorize their position
int wildcardsCount = pattern.Count(x => x == 'x');
int[] positions = new int[wildcardsCount];
int index = 0;
int position = 0;
foreach (char c in pattern)
{
if (c == 'x')
positions[index++] = position;
position++;
}
// - Loop in all possible values taken by missing bits
int count = (int)Math.Pow(2, wildcardsCount);
for (int currentValue = 0; currentValue < count; currentValue++)
{
// - Prepare the binary string
string currentValueStr = Convert.ToString(currentValue, 2).PadLeft(wildcardsCount, '0');
// - Replace each character with known wildcard positions
char[] tmpOutput = pattern.ToCharArray();
int charIndex = 0;
for (charIndex = 0; charIndex < wildcardsCount; charIndex++)
tmpOutput[positions[charIndex]] = currentValueStr[charIndex];
string output = new string(tmpOutput);
// - Here we are
Debug.WriteLine(pattern + " (" + (currentValue + 1).ToString() + "/" + count.ToString() + ") => " + output);
}
}
输出:
xx0x (1/8) => 0000
xx0x (2/8) => 0001
xx0x (3/8) => 0100
xx0x (4/8) => 0101
xx0x (5/8) => 1000
xx0x (6/8) => 1001
xx0x (7/8) => 1100
xx0x (8/8) => 1101
110x (1/2) => 1100
110x (2/2) => 1101
100x (1/2) => 1000
100x (2/2) => 1001
010x (1/2) => 0100
010x (2/2) => 0101
x01x (1/4) => 0010
x01x (2/4) => 0011
x01x (3/4) => 1010
x01x (4/4) => 1011
1010 (1/1) => 1010
0011 (1/1) => 0011
0111 (1/1) => 0111
1111 (1/1) => 1111
xxxx (1/16) => 0000
xxxx (2/16) => 0001
xxxx (3/16) => 0010
xxxx (4/16) => 0011
xxxx (5/16) => 0100
xxxx (6/16) => 0101
xxxx (7/16) => 0110
xxxx (8/16) => 0111
xxxx (9/16) => 1000
xxxx (10/16) => 1001
xxxx (11/16) => 1010
xxxx (12/16) => 1011
xxxx (13/16) => 1100
xxxx (14/16) => 1101
xxxx (15/16) => 1110
xxxx (16/16) => 1111
0001 (1/1) => 0001
1010 (1/1) => 1010
0110 (1/1) => 0110
最好的问候。