How to produce all binary vectors of length n with k zero elements sequentially?

How to produce all binary vectors of length n with k zero elements sequentially?

I know how to produce all combination of such sequences once. But I am looking for an algorithm to build them one by one.

This codes generate all of binary vectors of length a+b with a zero elements and stores them in V:

function V = build_2(a,b)
C = nchoosek(1:a+b,b);
V = zeros(size(C,1),a+b);
for i=1:size(V,1)
    V(i,C(i,:)) = 1;
end

Answers


How about this?

for n = 0:2^(a+b)-1
    aux = dec2bin(n,a+b)-'0'; %// or use: aux = de2bi(n,a+b);
    if sum(aux)~=b
        continue
    end
    v = aux; %// desired result
    disp(v) %// do stuff with this v
end

This generates all binary vectors of length a+b and skips those that don't have exactly b ones. bin2dec is used for generating each binary vector. Since bin2dec gives a string, subtracting '0' converts to a numeric vector.


Need Your Help

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >=

sql sql-server

I know this question is quite redundant already but in my case I can't figure out what went wrong with my code or probably with the data inside my table.

FPS Mouse movement in OpenGL (even outside window)

java opengl jogl

I'm creating a simple FPS game where the camera movement is controlled with the mouse. It's fairly simple to move the camera with the mouse when it's inside the window. But how can I make this work...