Assume we have a integer of bitsize n=4;
The problem I am describing is how you would go about indexing a number to an array position based on the Hamming weight and its value knowing the bitsize
. E.g.
An array with 16 elements for bitsize 4 would/could look like this:
|0|1|2|4|8|3|5|6|9|10|12|7|11|13|14|15|
Where elements are grouped by their Hamming weight(necessary) and sorted based on size(not necessary). Sorting is not necessary as long as you can take e.g. 3(0011) do some operations and get back index 5, 5(0101) -> 6 etc.
All combinations of n
bits will be present and there will be no duplication. E.g.
bitsize of 3
would have the array:
|0|1|2|4|3|5|6|7|
I would preferably have a solution without loops. Or any papers that discuss simillar solutions. Or finally just throw out any ides on how you could go about doing that.
Note that you can enumerate numbers (in counting order) with the same hamming weight using the following functions:
As an example, repititive application of prev() on x = 5678:
Hence theoretically you can compute the index of a number by repititive application of this. However this can take very long. The better approach would be to "jump" over some combinations.
There are 2 rules:
The following algorithm computes the index of a number among the numbers with the same Hamming weight (i did not bother about fast implementation of binomial):
For example, given the number x=5678 the algorithm will compute its index in just 4 iterations:
Note that 1137 is the position of 5678 within the group of numbers with the same Hamming weight. Hence you would have to shift this index accordingly to account for all the numbers with smaller Hamming weights
Here is a concept work, just to get the discussion started.
The step one is hardest - solved using approximation to calculate factorials.
Anymore bright ideas?
Ideone link