【问题标题】:Generate only those binary strings of length n with maximum k consecutive zeros仅生成长度为 n 且具有最大 k 个连续零的那些二进制字符串
【发布时间】:2015-06-08 07:40:12
【问题描述】:

什么是只生成长度为 n 的二进制字符串的最有效方法,这些字符串最多有 k 个连续的零。

例如:- 如果 n = 3,k = 2:

0 0 1

0 1 0

0 1 1

1 0 0

1 0 1

1 1 0

1 1 1

而不是 000

注意:我的研究 (NLP) 需要这种方法,我使用位字符串生成具有所有可能的 n-gram 的句子。 我已经尝试枚举所有二进制字符串,但是,由于二进制字符串的数量在句子 2^(n-1) 的长度上是指数的,如果 n > 30,代码就会崩溃。因此,我仅限于生成具有上述条件的位串,计算可行性。

【问题讨论】:

标签: algorithm binary nlp bits bitmask


【解决方案1】:

简单的递归版本(Delphi)

  procedure Generate(ZeroCount, MaxZeroCount, Len, MaxLen: Integer; s: string);
  begin
    if Len = MaxLen then
      Output(s)
    else begin
      if ZeroCount < MaxZeroCount then
        Generate(ZeroCount + 1, MaxZeroCount, Len + 1, MaxLen, s + '0');
      Generate(0, MaxZeroCount, Len + 1, MaxLen, s + '1');
    end;
  end;

整数值而不是字符串的变体

  if ZeroCount < MaxZeroCount then
    Generate(ZeroCount + 1, MaxZeroCount, Len + 1, MaxLen, Value shl 1);
  Generate(0, MaxZeroCount, Len + 1, MaxLen, (Value shl 1) or 1);

生成的输出(0, 2, 0, 5, '');

00100
00101
00110
00111
01001
01010
01011
01100
01101
01110
01111
10010
10011
10100
10101
10110
10111
11001
11010
11011
11100
11101
11110
11111

【讨论】:

  • 谢谢@MBo!你(几乎)完全正确!但是,上述代码尚未生成某些字符串,例如 - 00100、00101 等。因此,在 Generate(0, MaxZeroCount, Len + 1, MaxLen, s + '1') 中将 ZeroCount 重置为 0 有助于生成综合列表。再次感谢。
  • 谢谢,这是我的错。固定。
猜你喜欢
  • 2010-12-23
  • 2011-12-04
  • 2013-11-08
  • 1970-01-01
  • 1970-01-01
  • 2019-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多