You are already on a good path with binomial odds. There are several factors to consider:
Think of your number as a binary string of length n . Now we can create another array counting the number of times the bit will be flipped:
[0, 1, 0, 0, 1] number [a, b, c, d, e] number of flips.
But even the number of coups leads to the same result, as well as all the odd numbers of coups. Thus, basically the corresponding part of the distribution can be represented by% 2
The next logical question is how many different combinations of even and odd values are available. We will take care of the order later, and now just assume that a sorting array is ordered for simplicity. We start with k as a singular flip in an array. Now we want to add a flip. Since the entire flipping array is used by% 2, we must remove two from the k value to achieve this and insert them into the array separately. For instance:.
[5, 0, 0, 0] mod 2 [1, 0, 0, 0] [3, 1, 1, 0] [1, 1, 1, 0] [4, 1, 0, 0] [0, 1, 0, 0]
As the last example shows (remember that we are working modulo 2 in the final result), moving a single 1 does not change the number of flips in the final result. Thus, we should always flip the even bits of a number in an inverted array. If k even, so will the number of flipped bits, and vice versa, regardless of what the value of n .
So now the question is, how many different ways to fill an array are available? For simplicity, we will start with mod 2 right away.
Obviously, we start with 1 inverted bit if k is odd, otherwise with 1. And we always add 2 inverted bits. We can continue this until we flip all bits of n (or at least as many as we can flip)
v = (k % 2 == n % 2) ? n : n - 1
or we cannot propagate k further along the array.
v = k
Combining this:
noOfAvailableFlips: if k < n: return k else: return (k % 2 == n % 2) ? n : n - 1
So far so good, there are always v / 2 flipping arrays (mod 2) that differ in the number of upside down bits. Now we move on to the next part, rearranging these arrays. This is just a simple permutation function (exact repetition permutation):
flipArrayNo(flippedbits): return factorial(n) / (factorial(flippedbits) * factorial(n - flippedbits)
Putting it all together:
solutionsByFlipping(n, k): res = 0 for i in [k % 2, noOfAvailableFlips(), step=2]: res += flipArrayNo(i) return res
It also shows that for sufficiently large numbers we cannot get 2 ^ n sequences for the simple reason that we cannot organize operations as we please. The number of flips that really affect the result will always be even or odd depending on k . There is no way around this. The best result might be a 2^(n-1) sequence.