I am looking for a function that inputs (n,r) and outputs the all the ways in which we can pick r objects from a string of n objects. Moreover, I would like this list as an increasing, binary sequence.
For example:
(5,2)
would output: [00011,00101,00110,01001,01010,01100,10001,10010,10100,11000]
I have tried to do this by considering the rightmost 1 and checking whether it can 'move left without bumping into another 1'. If it cannot, then I move to the next 1 and check the same thing. If any of the 1's can be 'moved to the left', every 1 to the right of it gets 'reset'.
Although my code has not been working trying this method.
Your desired order is simply the lexicographic order emitted by itertools.combinations
when choosing n - r positions for 0s from n positions:
from itertools import combinations
def binary_combinations(n, r):
for c in map(set, combinations(range(n), n - r)):
yield ''.join('0' if i in c else '1' for i in range(n))
print(*binary_combinations(5, 2), sep='\n')
This outputs:
00011
00101
00110
01001
01010
01100
10001
10010
10100
11000
Demo here