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[0] // 3;

# /If you don't have Perl 5.10, use this:
# my $digits = defined $ARGV[0] ? $ARGV[0] : 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 …

0 Responses to “Binary”



  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




Archives


%d bloggers like this: