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