Anonymous user
Index finite lists of positive integers: Difference between revisions
Index finite lists of positive integers (view source)
Revision as of 04:15, 13 May 2014
, 10 years ago→{{header|Perl 6}}: style upgrade
m (→Bijection: allowing empty list is probably more correct) |
(→{{header|Perl 6}}: style upgrade) |
||
Line 226:
Here is a bijective solution that does not use string operations.
<lang perl6>
multi infix:<rad> ($a) { $a }
multi infix:<rad> ($a, $b) { $a * $*RADIX + $b }
multi expand(Int $n is copy, 1) { $n }
multi expand(Int $n is copy, Int $*RADIX) {
my \RAD = $*RADIX;
my @reversed-digits = gather while $n > 0 {
take $n %
$n div=
}
eager for ^RAD {
[rad] reverse @reversed-digits[$_, * +
}▼
sub compress(*@n is copy where @n > 0) {▼
my $dimension = @n.elems;▼
reverse gather while @n.any > 0 {▼
(state $i = 0) %= $dimension;▼
take @n[$i] % $dimension;▼
@n[$i] div= $dimension;▼
$i++;▼
}
}
sub unrank(Int $n) { my ($a, $b) = expand($n, 2); expand $a, $b + 1 }▼
▲ [rad] reverse gather while @n.any > 0 {
}
▲}
sub rank(@n) { compress (compress(@n), @n - 1)}
say my @list = (^10).roll((2..20).pick);
say my $rank = rank @list;
say unrank $rank;
for ^10 {
my @unrank = unrank $_;
say $_, " <-> [", @unrank, "] <-> ", rank @unrank;</lang>
{{out}}
<pre>7 1 2 2
22307919125181853053469970435648803626620419
7 1 2 2
0 <-> [0] <-> 0
1 <-> [1] <-> 1
|