# 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.