Index finite lists of positive integers: Difference between revisions
Content added Content deleted
m (→{{header|Perl 6}}: comma missing) |
(→{{header|Perl 6}}: adding extra credit) |
||
Line 186: | Line 186: | ||
406578125236287223374090483 |
406578125236287223374090483 |
||
4 5 7 9 0 8 8 7 4 8 8 4 1</pre> |
4 5 7 9 0 8 8 7 4 8 8 4 1</pre> |
||
'''Extra credit''' |
|||
To get a bijection we need to shift the encoding of the length by two: |
|||
<lang perl6>sub rank(@n) { compress compress(@n), +@n - 2} |
|||
sub unrank(Int $n) { my ($a, $b) = expand($n, 2); expand $a, $b + 2 } |
|||
for ^20 { |
|||
my @unrank = unrank $_; |
|||
say @unrank, " <-> ", rank @unrank; |
|||
}</lang> |
|||
{{out}} |
|||
<pre>0 0 <-> 0 |
|||
1 0 <-> 1 |
|||
0 0 0 <-> 2 |
|||
1 0 0 <-> 3 |
|||
0 1 <-> 4 |
|||
1 1 <-> 5 |
|||
2 0 0 <-> 6 |
|||
0 1 0 <-> 7 |
|||
0 0 0 0 <-> 8 |
|||
1 0 0 0 <-> 9 |
|||
0 0 0 0 0 <-> 10</pre> |
|||
This does not deal with the degenerate case of lists of length one, though. |
|||
=={{header|Python}}== |
=={{header|Python}}== |