diff options
| author | Jared Martin <jaredor+github@gmail.com> | 2020-05-09 17:01:24 -0500 |
|---|---|---|
| committer | Jared Martin <jaredor+github@gmail.com> | 2020-05-09 17:01:24 -0500 |
| commit | 43761bc6e29b86d43551883c7f11f97c3b74afdd (patch) | |
| tree | 41f51ba4880e405042d90893f4ec19218df55cd4 /challenge-059 | |
| parent | 545b1ac0f487c742b81ee0772cae1f3de36978d1 (diff) | |
| download | perlweeklychallenge-club-43761bc6e29b86d43551883c7f11f97c3b74afdd.tar.gz perlweeklychallenge-club-43761bc6e29b86d43551883c7f11f97c3b74afdd.tar.bz2 perlweeklychallenge-club-43761bc6e29b86d43551883c7f11f97c3b74afdd.zip | |
Simpler version for arbitrarilly large numbers.
Diffstat (limited to 'challenge-059')
| -rwxr-xr-x | challenge-059/jaredor/perl/ch-2.pl | 41 |
1 files changed, 15 insertions, 26 deletions
diff --git a/challenge-059/jaredor/perl/ch-2.pl b/challenge-059/jaredor/perl/ch-2.pl index 4cd8a0563b..873484518a 100755 --- a/challenge-059/jaredor/perl/ch-2.pl +++ b/challenge-059/jaredor/perl/ch-2.pl @@ -4,46 +4,35 @@ use v5.012; use warnings; use bigint; use Config; -use List::Util qw(all sum max); +use List::Util qw(all sum); # PWC 059, TASK #2 : Bit Sum # Answer based on perl doc for unpack and www.perlmonks.org/?node_id=407933 -my ( $LL, $NN ) = - defined $Config{longlongsize} - ? ( 8 * $Config{longlongsize}, 'Q' ) - : ( 8 * $Config{longsize}, 'L' ); - -my $CHOP_SIZE = 2**${LL}; -my $CHOP_ZERO = pack "${NN}", 0; - die "This script requires one or more positive integer arguments." unless @ARGV; die "Not all arguments to the script are positive integers." unless all { /\A [1-9] \d* \Z/xms } @ARGV; -#my @nums = map { pack "${NN}*", $_ } @ARGV; +my ( $LL, $NN ) = + defined $Config{longlongsize} + ? ( 8 * $Config{longlongsize}, 'Q' ) + : ( 8 * $Config{longsize}, 'L' ); + +my $WORD = 2**$LL; -sub chop_up { - my ( $num, @chopped ) = ( 0 + $_[0], ); - while ($num) { - push @chopped, $num % $CHOP_SIZE; - $num = int( $num / $CHOP_SIZE ); - } - return [ map { pack "${NN}", $_ } @chopped ]; +sub num2bitstr { + my ( $numstr, $bitstr ) = ( $_[0], ); + $bitstr .= pack "${NN}", $numstr % $WORD and $numstr /= $WORD while $numstr; + return $bitstr; } -my @nums = map { chop_up $_ } @ARGV; -my $chops = max map { $#$_ } @nums; -( $chops - $#$_ ) and push @$_, ($CHOP_ZERO) x ( $chops - $#$_ ) for @nums; +my @nums = map { num2bitstr $_ } @ARGV; -my ( @diffbits, $numa ); -while ( $numa = shift @nums ) { - for my $numb (@nums) { - push @diffbits, unpack( "%${LL}b*", $numa->[$_] ^ $numb->[$_] ) - for 0 .. $chops; - } +my ( @diffbits, $num ); +while ( $num = pop @nums ) { + push @diffbits, unpack( "%${LL}b*", $num ^ $_ ) for @nums; } say @diffbits ? sum @diffbits : 0; |
