Created
October 8, 2015 18:10
-
-
Save anonymous/948a39efd73275266fa1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl6 | |
constant DEFAULT_BASE = 10; | |
# ndr = Number of Digits Required | |
multi sub ndr(Int $value , Int :$radix = DEFAULT_BASE) { | |
1 + floor log (1 max abs $value), $radix | |
} | |
multi sub ndr(Int @values, Int :$radix = DEFAULT_BASE) { | |
1 + floor log (1 max [max] @values>>.abs), $radix; | |
} | |
multi sub MAIN(Int $value is copy, Int :@radix!) { | |
flat reverse gather for @radix { | |
take $value % $_; | |
$value div= $_; | |
} | |
} | |
multi sub MAIN(Int $value , Int :$radix = DEFAULT_BASE, Bool :$c = False) { | |
return ndr $value, :$radix if $c; | |
MAIN $value, :radix(my Int @ = $radix xx ndr $value, :$radix); | |
} | |
multi sub MAIN(Int @values, Int :$radix = DEFAULT_BASE, Bool :$c = False) { | |
#TODO: don't recalc ndr every iter | |
map &MAIN.assuming(* , :$radix, :$c), @values; | |
} | |
multi sub MAIN(Int @values, Int :@radix!) { | |
map &MAIN.assuming(*, :@radix), @values; | |
} | |
sub USAGE() { | |
my $m10_12_34 = :60[10,12,34]; | |
say MAIN :60[10,12,34]; # 10,12,34 | |
say MAIN (my Int @ = :60[10,12,34],:60[1,2,3]), :radix(60); #(10,12,34), (1,2,3) | |
my Int @coins = 25,10,5,1; | |
my Int @change = 5,20,0,28; | |
my Int $net_worth = [+] @coins >>*<< @change; | |
say qq:to"end"; | |
NAME | |
$*PROGRAM-NAME -- explode numbers into digits | |
SYNOPSIS | |
$*PROGRAM-NAME [-c] [--radix=base] value(s) | |
DESCRIPTION | |
$*PROGRAM-NAME explodes integer <value(s)> into their component digits, defined generically. | |
If no <radix> is provided, base 10 is assumed. | |
-c Instead of digits, maximum # of digits required to represent the value, or in the | |
case of a vector, the biggest magnitude integer in that vector. | |
--radix Base used for explosion. May be standard (scalar) or mixed (vector). | |
$*PROGRAM-NAME 1234 # (1,2,3,4) | |
$*PROGRAM-NAME 1234,5678 # (1,2,3,4),(5,6,7,8) | |
$*PROGRAM-NAME -c 1234 # 4 decimal digits required | |
$*PROGRAM-NAME -c --radix=16 0xAAAA # 4 hex digits | |
$*PROGRAM-NAME -c --radix=2 0b1010111 # 7 bits | |
$*PROGRAM-NAME -c 1, 100, 1000, -10000 # widest number (-10000) requires 5 decimal digits | |
$*PROGRAM-NAME --radix=60 $m10_12_34 # Break integer into time of day | |
$*PROGRAM-NAME --radix=24,60,60 $m10_12_34 # Same | |
$*PROGRAM-NAME --radix={join(',', @coins)} $net_worth # make change (quarters, dimes, nickels cents) | |
end | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment