Sosumi
Sosumi

Reputation: 779

Generate all binary combinations possible

I would like to specify a number of bits, and then get an array containing every possible combination of these bits, in PHP.

Example:

number: 3
000
001
010
011
etc...

I have tried recursive algorithms which were originally designed for strings, so the algorithm is too slow.

What is the most efficient way to do this?

Upvotes: 2

Views: 2670

Answers (1)

Tom van der Woerdt
Tom van der Woerdt

Reputation: 29975

The nice part about bits is that you can do really simple stuff with them. If you want 3 bits, you'll have 7 numbers, which happens to be 8-1. If you want 4 bits, you'll have 15 numbers, which happens to be 16-1. Use this nice fact to make your code simple.

$bits = 4;
$max = (1 << $bits);

for ($i = 0; i < $max; $i++) {
    // Use $i
    // echo str_pad(decbin($i), $bits, '0', STR_PAD_LEFT);
}

Upvotes: 6

Related Questions