Skip to content

Instantly share code, notes, and snippets.

@adamcrussell
Last active July 14, 2019 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamcrussell/3fbecefa5f157669e3619ca50e62277b to your computer and use it in GitHub Desktop.
Save adamcrussell/3fbecefa5f157669e3619ca50e62277b to your computer and use it in GitHub Desktop.
Perl Weekly Challenge 016
use strict;
use warnings;
##
# At a party a pie is to be shared by 100 guests.
# The first guest gets 1% of the pie, the second
# guest gets 2% of the remaining pie, the third
# gets 3% of the remaining pie, the fourth gets 4% and so on.
# Write a script that figures out which guest gets the largest piece of pie.
##
use constant PIE_SIZE => 100;
my $pie_remaining = PIE_SIZE;
my @pie_eaters;
my $eater = 1;
my $eaten;
do{
$eaten = $pie_remaining * ($eater * .01);
$pie_eaters[$eater] = $eaten;
$pie_remaining = $pie_remaining - $eaten;
print "$eater $eaten $pie_remaining\n";
$eater++;
} while($pie_remaining > 0 && $eaten > 0);
use strict;
use warnings;
##
# Write a script to validate a given bitcoin address.
##
use boolean;
use Digest::SHA q/sha256/;
my @BASE58 = (1 .. 9, 'A' .. 'H', 'J' .. 'N', 'P' .. 'Z', 'a' .. 'k', 'm' .. 'z');
my %BASE58_ENCODING = map { $BASE58[$_] => $_ } 0 .. 57;
sub base58_decode{
my($address) = @_;
my @bytes;
my @characters = map { $BASE58_ENCODING{$_} } split(//, $address);
foreach my $c (@characters) {
for (my $i = 25; $i--; ) {
$c += (58 * ($bytes[$i] || 0));
$bytes[$i] = $c % 256;
$c /= 256;
}
}
return @bytes;
}
sub validate_address {
my($address) = @_;
my @address_bytes = base58_decode($address);
if((pack "C*", @address_bytes[21..24]) eq substr(sha256(sha256(pack("C*", @address_bytes[0..20]))), 0, 4)){
return true;
}
return false;
}
##
# Main
##
my $address = $ARGV[0];
if(validate_address($address)){
print "$address is VALID\n";
}
else{
print "$address is INVALID\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment