Given a 64 bit integer, where the last 52 bits to be evaluated and the leading 12 bits are to be ignored, what is the fastest way to loop every single combination of 7 bits on and all other bits off?
Example:
First permutation:
0[x57]1111111
Last permutation
00000000000011111110[x45]
Where 0[xn]
means n
off (zero) bits.
Speed is absolutely crucial, we are looking to save every clock cycle we can as it is part of a greater solution that needs to evaluate billions of states in a reasonable amount of time.
A working solution is not required, but some pseudo code would do just fine :)
If you want to test both conditions, use the && operator. What is happening in your code is related to how the comma operator , works. Both i < p and j < q are evaluated, but only the result of the 2nd expression j < q is checked by the for loop. Save this answer.
The for loop is the fastest but poorly readable. The foreach is fast, and iteration is controllable. The for…of takes time, but it's sweeter. The for…in takes time, hence less convenient.
List comprehensions are faster than for loops to create lists.
You can do the same type of for loop if you want to loop over every character in a string. To loop through a set of code a certain number of times, you can use the range() function, which returns a list of numbers starting from 0 to the specified end number.
I think you'll be interested in this article: http://realtimecollisiondetection.net/blog/?p=78
It solves your problem in very efficient way.
What you need is a good algorithm that will take you from one permutation to the next in minimal time.
Now, the first algorithm that comes to mind is to go through all combinations with seven loops.
This will give you the fastest iteration. Here is some pseudo C++ code:
__int64 deck;
int bit1, bit2, bit3, ...;
for (bit1=0;bit1<52-6;bit1++) {
for (bit2=bit1+1;bit2<52-5;bit2++) {
...
for (bit7=bit6+1;bit7<52;bit7++) {
deck = (1<<bit1)+(1<<bit2)+(1<<bit3)+...; // this could be optimized.
// do whatever with deck
}
...
}
}
// note: the 52-6, 52-5, will be pre-calculated by the compiler and are there for convenience. You don't have to worry about optimizing this.
There is your solution right there. If you want to check that it works, I always downscale it. For example, following that algorithm on a 4bit number where you need to set 2 bits would go like this:
1100
1010
1001
0110
0101
0011
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With