Index finite lists of positive integers: Difference between revisions
Content added Content deleted
(→{{header|Python}}: correct when list begins with 0s) |
(→{{header|Ruby}}: added Bijection) |
||
Line 367: | Line 367: | ||
14307647611639042485573 |
14307647611639042485573 |
||
[1, 2, 3, 10, 100, 987654321] |
[1, 2, 3, 10, 100, 987654321] |
||
</pre> |
|||
=== Bijection === |
|||
{{trans|Python}} |
|||
<lang ruby>def unrank(n) |
|||
return [0] if n==1 |
|||
n.to_s(2)[1..-1].split('0',-1).map(&:size) |
|||
end |
|||
def rank(x) |
|||
return 0 if x.empty? |
|||
('1' + x.map{ |a| '1'*a }.join('0')).to_i(2) |
|||
end |
|||
for x in 0..10 |
|||
puts "%3d : %-18s: %d" % [x, a=unrank(x), rank(a)] |
|||
end |
|||
puts |
|||
x = [1, 2, 3, 5, 8] |
|||
puts "#{x} => #{rank(x)} => #{unrank(rank(x))}"</lang> |
|||
{{out}} |
|||
<pre> |
|||
0 : [] : 0 |
|||
1 : [0] : 1 |
|||
2 : [0, 0] : 2 |
|||
3 : [1] : 3 |
|||
4 : [0, 0, 0] : 4 |
|||
5 : [0, 1] : 5 |
|||
6 : [1, 0] : 6 |
|||
7 : [2] : 7 |
|||
8 : [0, 0, 0, 0] : 8 |
|||
9 : [0, 0, 1] : 9 |
|||
10 : [0, 1, 0] : 10 |
|||
[1, 2, 3, 5, 8] => 14401279 => [1, 2, 3, 5, 8] |
|||
</pre> |
</pre> |
||