Skip to content

Instantly share code, notes, and snippets.

@smw
Created October 8, 2015 21:39
Show Gist options
  • Save smw/f150a4c5f9df1dfc69e4 to your computer and use it in GitHub Desktop.
Save smw/f150a4c5f9df1dfc69e4 to your computer and use it in GitHub Desktop.
def next_perm(v):
"""
Generates next permutation with a given amount of set bits,
given the previous lexicographical value.
Taken from http://graphics.stanford.edu/~seander/bithacks.html
"""
t = (v | ( v - 1)) + 1
w = t | ((((t & -t) / (v & -v)) >> 1) - 1)
return w
def perm_gen(size, set_bits):
start = 2**set_bits - 1
cur = start
while True:
yield cur
if cur >= start << (size - set_bits):
break
cur = next_perm(cur)
print ['{0:010b}'.format(x) for x in perm_gen(10, 3)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment