## Posts Tagged 'binary'

### Binary

I program for living, but i’ve never received proper formal education in serious algorithms.

Here’s a very simple problem: Take an array of length `n` and fill it with zeros. Every array member represents a binary digit. Now, using this array and not using the usual math for binary conversion, print all binary digits from zero to the maximum binary number with `n` digits. For example, with `n == 3` this should be printed:

```0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
```

Here’s what i wrote. Is it OK or is it an embarrassment?

```use strict;
use warnings;

# That's right, upgrade to Perl 5.10.
# If you can't, comment out this line.
use 5.010;

my \$digits = \$ARGV // 3;

# /If you don't have Perl 5.10, use this:
# my \$digits = defined \$ARGV ? \$ARGV : 3;

my @matrix = ();
my @number = map { 0 } (1 .. \$digits);
my \$last = 0;

NUMBER:
while (not \$last) {
push @matrix, [ @number ];

my \$digit_index = \$digits;
DIGIT:
while (\$digit_index) {
\$digit_index--;
\$last = 1;

if (\$number[\$digit_index]) {
\$number[\$digit_index] = 0;
}
else {
\$last = 0;
\$number[\$digit_index] = 1;
next NUMBER;
}
}
}

foreach my \$number (@matrix) {
print "@{\$number}\n";
}
```

Oh (edit): The real embarrassment – in WordPress the sourcecode presentation cannot display Perl properly. But if i put ‘ruby’ instead of ‘perl’ in the language attribute, it works mostly fine …