【问题标题】:scanning binary sequences of length n with k 1's and n-k 0's用 k 1 和 n-k 0 扫描长度为 n 的二进制序列
【发布时间】:2013-09-24 06:11:19
【问题描述】:

我想编写一个循环,用 k 1 和 n-k 0 扫描所有长度为 n 的二进制序列。

实际上,在每次迭代中,都会对序列执行一个操作,如果满足某个条件,则循环将中断,否则进入下一个序列。 (我不是在寻找 nchoosek 或 perms,因为对于较大的 n 值,需要很长时间才能给出输出)。

您建议使用什么 MATLAB 代码?

【问题讨论】:

  • 这不是同一个问题asked yesterday吗?现在好像被移除了,我相信那里至少有一些有用的 cmets。
  • 那么所有的 0 都跟在所有的 1 后面吗(反之亦然)?
  • @Parag 不!此类序列的所有组合无一例外。
  • @BasSwinckels:+1 确实有很好的建议:在 C++ 中使用 std::next_permutation 和 Gosper's Bit Twiddling Hack
  • @MahdiKhosravi 您上次得到 C++ 答案是因为您将其标记为 C++。

标签: algorithm matlab combinations permutation bits


【解决方案1】:

你可以实现类似iterator/generator 模式:

classdef Iterator < handle
    properties (SetAccess = private)
        n              % sequence length
        counter        % keeps track of current iteration
    end

    methods
        function obj = Iterator(n)
            % constructor
            obj.n = n;
            obj.counter = 0;
        end

        function seq = next(obj)
            % get next bit sequence
            if (obj.counter > 2^(obj.n) - 1)
                error('Iterator:StopIteration', 'Stop iteration')
            end
            seq = dec2bin(obj.counter, obj.n) - '0';
            obj.counter = obj.counter + 1;
        end

        function tf = hasNext(obj)
            % check if sequence still not ended
            tf = (obj.counter <= 2^(obj.n) - 1);
        end

        function reset(obj)
            % reset the iterator
            obj.counter = 0;
        end
    end
end

现在您可以将其用作:

k = 2;
iter = Iterator(4);
while iter.hasNext()
    seq = iter.next();
    if sum(seq)~=k, continue, end
    disp(seq)
end

在上面的示例中,这将遍历所有长度为 4 的 0/1 序列,其中恰好 k=2 个:

 0     0     1     1
 0     1     0     1
 0     1     1     0
 1     0     0     1
 1     0     1     0
 1     1     0     0

【讨论】:

  • 非常感谢。看起来不错。对于我面临的情况,我必须跳过 1 的数量不是所需 k 的情况?还是有更好的解决方案?
  • 你可以在循环中添加一个测试:if sum(seq)~=k, continue, end
  • 有什么办法让它更快吗?不幸的是,nchoosek 工作得更快
  • 你看过我链接的问题中的答案吗,有一些非常聪明的想法。如果您绝对想要速度,只需将 C/C++ 中的先前建议实现为 MEX 函数并在您的代码中调用它...
猜你喜欢
  • 2012-12-10
  • 2010-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-08
  • 1970-01-01
  • 2019-07-13
  • 1970-01-01
相关资源
最近更新 更多