aboutsummaryrefslogtreecommitdiff
path: root/challenge-016
diff options
context:
space:
mode:
authorFrancis Whittle <code@powered.ninja>2019-07-14 20:44:31 +1000
committerFrancis Whittle <code@powered.ninja>2019-07-14 20:45:13 +1000
commitb55eb16e4d8d9e0eb467f5500e4f2d154f0be3a0 (patch)
tree7c6838ab6eb946424416ad1157c22bcd7b5cb525 /challenge-016
parentf9a095fa25cbdadf0548b73a4a8df0f89ee5e79b (diff)
downloadperlweeklychallenge-club-b55eb16e4d8d9e0eb467f5500e4f2d154f0be3a0.tar.gz
perlweeklychallenge-club-b55eb16e4d8d9e0eb467f5500e4f2d154f0be3a0.tar.bz2
perlweeklychallenge-club-b55eb16e4d8d9e0eb467f5500e4f2d154f0be3a0.zip
fjwhittle challenge 016 solutions.
Diffstat (limited to 'challenge-016')
-rw-r--r--challenge-016/fjwhittle/perl6/ch-1.p619
-rw-r--r--challenge-016/fjwhittle/perl6/ch-2.p639
2 files changed, 58 insertions, 0 deletions
diff --git a/challenge-016/fjwhittle/perl6/ch-1.p6 b/challenge-016/fjwhittle/perl6/ch-1.p6
new file mode 100644
index 0000000000..bdaa4d0347
--- /dev/null
+++ b/challenge-016/fjwhittle/perl6/ch-1.p6
@@ -0,0 +1,19 @@
+#!/usr/bin/env perl6
+
+#| Calculate which guest gets the largest slice of pie and what percentage that is.
+unit sub MAIN(
+ UInt $guests where * > 0 = 100 #= Number of guests, defaults to 100.
+);
+
+# Start with a whole pie
+my FatRat $pie = 1.FatRat;
+
+# Calculate slices. 0th guest to line up the indices, gets 0 anyway.
+my @slices = (0..$guests).map: -> $n is copy {
+ $n *= $pie / $guests;
+ $pie -= $n;
+ $n * 100; # As a percentage.
+};
+
+# .key is the guest number, .value is the percentage ofthe pie they get.
+@slices.pairs.max(*.value).fmt('With %2$.2f%%, guest %1$d gets the most pie.').put;
diff --git a/challenge-016/fjwhittle/perl6/ch-2.p6 b/challenge-016/fjwhittle/perl6/ch-2.p6
new file mode 100644
index 0000000000..97238f6276
--- /dev/null
+++ b/challenge-016/fjwhittle/perl6/ch-2.p6
@@ -0,0 +1,39 @@
+#!/usr/bin/env perl6
+
+use Digest::SHA;
+
+#| Validate Bitcoin address
+sub MAIN (
+ Str $bitcoin-addr, #= A bitcoin address
+ Bool :$q = False #= Suppress output
+) {
+
+ # First verify against regex for bitcoin addresses.
+ $bitcoin-addr ~~ / ^ <?before [ 1 || 3 ]>
+ <[a..z 1..9 A..Z]-[IOl]> ** 21..31
+ <[a..z A..Z 0..9]> ** 4 $ / or die q{Doesn't match address pattern};
+
+ # Alphabet mapping for Base 58 conversion.
+ my %alpha = ((1..9, 'A'..'Z', 'a'..'z') ∖ <I O l>).keys.sort.antipairs;
+
+ # Do base 58 conversion.
+ my @addrmod = ([+] %alpha{$bitcoin-addr.comb}.reverse.map({ $_ * 58 ** $++ }))\
+ .polymod(256 xx 24).reverse;
+
+ # Double SHA256 digest the address
+ my $addrsha = sha256(sha256(Blob.new: @addrmod[^21]));
+
+ # Compare digest against the checksum.
+ $addrsha.subbuf(0, 4) eqv Blob.new(@addrmod[* - 4 .. *]) or die 'Checksum does not match';
+
+ # Valid if we got this far.
+ $q or say 'Valid bitcoin address.';
+
+ # CATCH to hide errors for quiet mode.
+ CATCH {
+ default {
+ $q and exit 1;
+ die $_;
+ }
+ }
+}