入力値が可変であり、実際の出力を確認したかったことを考慮して、再帰アルゴリズムを使用して、特定の長さに対する 0 と 1 のすべての組み合わせを決定しました。
private static void BinaryNumberWithOnes(int n, int dump, int ones, string s = "")
{
if (n == 0)
{
if (BinaryWithoutDumpCountContainsnumberOfOnes(s, dump,ones))
Console.WriteLine(s);
return;
}
BinaryNumberWithOnes(n - 1, dump, ones, s + "0");
BinaryNumberWithOnes(n - 1, dump, ones, s + "1");
}
およびBinaryWithoutDumpCountContainsnumberOfOnesを使用して、2 進数が基準を満たすかどうかを判断します。
private static bool BinaryWithoutDumpCountContainsnumberOfOnes(string binaryNumber, int dump, int ones)
{
int current = 0;
int count = binaryNumber.Length;
while(current +dump < count)
{
var fail = binaryNumber.Remove(current, dump).Replace("0", "").Length < ones;
if (fail)
{
return false;
}
current++;
}
return true;
}
BinaryNumberWithOnes(6, 3, 2) を呼び出すと、一致するすべての 2 進数が出力されます。
010011
011011
011111
100011
100101
100111
101011
101101
101111
110011
110101
110110
110111
111011
111101
111110
111111