diff options
| author | Mohammad S Anwar <mohammad.anwar@yahoo.com> | 2020-07-23 17:42:14 +0100 |
|---|---|---|
| committer | Mohammad S Anwar <mohammad.anwar@yahoo.com> | 2020-07-23 17:42:14 +0100 |
| commit | e2ba1b26b2471a5298a011ef58d785bb2944802d (patch) | |
| tree | 13e54ca7718f58230dc5f200c64141577a7cd093 /challenge-070 | |
| parent | f6d0e30913aa2c06ff102261f4e8301e6a44e053 (diff) | |
| download | perlweeklychallenge-club-e2ba1b26b2471a5298a011ef58d785bb2944802d.tar.gz perlweeklychallenge-club-e2ba1b26b2471a5298a011ef58d785bb2944802d.tar.bz2 perlweeklychallenge-club-e2ba1b26b2471a5298a011ef58d785bb2944802d.zip | |
- Added solution by Ulrich Rieke.
Diffstat (limited to 'challenge-070')
| -rw-r--r-- | challenge-070/ulrich-rieke/perl/ch-2.pl | 38 |
1 files changed, 38 insertions, 0 deletions
diff --git a/challenge-070/ulrich-rieke/perl/ch-2.pl b/challenge-070/ulrich-rieke/perl/ch-2.pl new file mode 100644 index 0000000000..07a8a46393 --- /dev/null +++ b/challenge-070/ulrich-rieke/perl/ch-2.pl @@ -0,0 +1,38 @@ +#!/usr/bin/perl ; +use strict ; +use warnings ; +use feature 'say' ; + +#function to convert a binary string to a decimal number! +#Of course, we have pack and unpack, but this seems less unwieldy... +sub binToDecimal { + my $binary = shift ; + my $decimal = 0 ; + my $expo = 1 ; + my @reversed = reverse split (// , $binary) ; + for my $num ( @reversed ) { + $decimal += ( $expo * $num ) ; + $expo *= 2 ; + } + return $decimal ; +} + +my $limit = $ARGV[ 0 ] ; +my @current = ("0" , "1" ) ; +my $n = 1 ; +while ( $n < $limit ) { + for my $element ( reverse @current ) { + push( @current , $element ) ; + } + my $len = scalar @current ; + for my $i (0..$len / 2 - 1 ) { + $current[ $i ] = "0" . $current[ $i ] ; + } + for my $i ( $len / 2 .. $len - 1 ) { + $current[ $i ] = "1" . $current[ $i ] ; + } + $n++ ; +} +my @numbers = map { binToDecimal( $_ ) } @current ; +say join (', ' , @numbers ) ; + |
