Index finite lists of positive integers: Difference between revisions

Content added Content deleted
(Added Arturo implementation)
m (syntax highlighting fixup automation)
Line 28: Line 28:
{{trans|Python}}
{{trans|Python}}


<lang 11l>F rank(x)
<syntaxhighlight lang="11l">F rank(x)
R BigInt(([1] [+] x).map(String).join(‘A’), radix' 11)
R BigInt(([1] [+] x).map(String).join(‘A’), radix' 11)


Line 40: Line 40:
print(n)
print(n)
l = unrank(n)
l = unrank(n)
print(l)</lang>
print(l)</syntaxhighlight>


{{out}}
{{out}}
Line 51: Line 51:
=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>rank: function [arr][
<syntaxhighlight lang="rebol">rank: function [arr][
if empty? arr -> return 0
if empty? arr -> return 0
from.binary "1" ++ join.with:"0" map arr 'a -> repeat "1" a
from.binary "1" ++ join.with:"0" map arr 'a -> repeat "1" a
Line 70: Line 70:


u: unrank r
u: unrank r
print ["Unranked:" u]</lang>
print ["Unranked:" u]</syntaxhighlight>


{{out}}
{{out}}
Line 81: Line 81:
This solution isn't efficient.
This solution isn't efficient.
{{trans|Python}}
{{trans|Python}}
<lang d>import std.stdio, std.algorithm, std.array, std.conv, std.bigint;
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.array, std.conv, std.bigint;


BigInt rank(T)(in T[] x) pure /*nothrow*/ @safe {
BigInt rank(T)(in T[] x) pure /*nothrow*/ @safe {
Line 101: Line 101:
s.rank.writeln;
s.rank.writeln;
s.rank.unrank.writeln;
s.rank.unrank.writeln;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>[1, 2, 3, 10, 100, 987654321]
<pre>[1, 2, 3, 10, 100, 987654321]
Line 110: Line 110:
=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
Restricted to shortish lists with smallish integers, because the rank integers get really big really fast, and bloating the code with arbitrary precision arithmetic isn't illustrative.
Restricted to shortish lists with smallish integers, because the rank integers get really big really fast, and bloating the code with arbitrary precision arithmetic isn't illustrative.
<lang FreeBASIC>type duple
<syntaxhighlight lang="freebasic">type duple
A as ulongint
A as ulongint
B as ulongint
B as ulongint
Line 202: Line 202:
print R,
print R,
unrank R, X()
unrank R, X()
show_list(X())</lang>
show_list(X())</syntaxhighlight>
{{out}}
{{out}}
<pre>0 []
<pre>0 []
Line 213: Line 213:


A list element n is encoded as a 1 followed by n 0's. Element encodings are concatenated to form a single integer rank. An advantage of this encoding is that no special case is required to handle the empty list.
A list element n is encoded as a 1 followed by n 0's. Element encodings are concatenated to form a single integer rank. An advantage of this encoding is that no special case is required to handle the empty list.
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 251: Line 251:
r := rank(u)
r := rank(u)
fmt.Printf("\n%v\n%d\n%d\n", &b, u, &r)
fmt.Printf("\n%v\n%d\n%d\n", &b, u, &r)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 273: Line 273:


A bit of a hack to make a base 11 number then interpret it as base 16, just because that's easiest. Not bijective. Practical though for small lists of large numbers.
A bit of a hack to make a base 11 number then interpret it as base 16, just because that's easiest. Not bijective. Practical though for small lists of large numbers.
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 365: Line 365:
}
}
return l
return l
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 385: Line 385:
=={{header|Haskell}}==
=={{header|Haskell}}==


<lang haskell>import Data.List
<syntaxhighlight lang="haskell">import Data.List


toBase :: Int -> Integer -> [Int]
toBase :: Int -> Integer -> [Int]
Line 410: Line 410:
go 0 [] = []
go 0 [] = []
go i (0:xs) = go (i+1) xs
go i (0:xs) = go (i+1) xs
go i (x:xs) = (i*b + x - 1) : go 0 xs</lang>
go i (x:xs) = (i*b + x - 1) : go 0 xs</syntaxhighlight>


Using different bases we may enumerate lists.
Using different bases we may enumerate lists.
Line 440: Line 440:
Implementation:
Implementation:


<lang j>scrunch=:3 :0
<syntaxhighlight lang="j">scrunch=:3 :0
n=.1x+>./y
n=.1x+>./y
#.(1#~##:n),0,n,&#:n#.y
#.(1#~##:n),0,n,&#:n#.y
Line 450: Line 450:
n=.#.m{.(m+1)}.b
n=.#.m{.(m+1)}.b
n #.inv#.(1+2*m)}.b
n #.inv#.(1+2*m)}.b
)</lang>
)</syntaxhighlight>


Example use:
Example use:


<lang J> scrunch 4 5 7 9 0 8 8 7 4 8 8 4 1
<syntaxhighlight lang="j"> scrunch 4 5 7 9 0 8 8 7 4 8 8 4 1
4314664669630761
4314664669630761
hcnurcs 4314664669630761
hcnurcs 4314664669630761
4 5 7 9 0 8 8 7 4 8 8 4 1</lang>
4 5 7 9 0 8 8 7 4 8 8 4 1</syntaxhighlight>


Explanation. We treat the sequence as an n digit number in base m where n is the length of the list and m is 1+the largest value in the list. (This is equivalent to treating it as a polynomial in m with coefficients which are the values of the list, with powers of m increasing from right to left.) In other words 4 5 7 9 0 8 8 7 4 8 8 4 1 becomes 4579088748841. Now we just need to encode the base (10, in this case). To do that we treat this number as a sequence of bits and prepend it with 1 1 1 1 0 1 0 1 0. This is a sequence of '1's whose length matches the number of bits needed to represent the base of our polynomial, followed by a 0 followed by the base of our polynomial.
Explanation. We treat the sequence as an n digit number in base m where n is the length of the list and m is 1+the largest value in the list. (This is equivalent to treating it as a polynomial in m with coefficients which are the values of the list, with powers of m increasing from right to left.) In other words 4 5 7 9 0 8 8 7 4 8 8 4 1 becomes 4579088748841. Now we just need to encode the base (10, in this case). To do that we treat this number as a sequence of bits and prepend it with 1 1 1 1 0 1 0 1 0. This is a sequence of '1's whose length matches the number of bits needed to represent the base of our polynomial, followed by a 0 followed by the base of our polynomial.
Line 469: Line 469:
Base 11 encoding:
Base 11 encoding:


<lang j> rank =. 11&#.@:}.@:>@:(,&:>/)@:(<@:(10&,)@:(10&#.^:_1)"0)@:x:
<syntaxhighlight lang="j"> rank =. 11&#.@:}.@:>@:(,&:>/)@:(<@:(10&,)@:(10&#.^:_1)"0)@:x:
unrank=. 10&#.;._1@:(10&,)@:(11&#.^:_1)</lang>
unrank=. 10&#.;._1@:(10&,)@:(11&#.^:_1)</syntaxhighlight>


Example use:
Example use:


<lang J> rank 1 2 3 10 100 987654321 135792468107264516704251 7x
<syntaxhighlight lang="j"> rank 1 2 3 10 100 987654321 135792468107264516704251 7x
187573177082615698496949025806128189691804770100426
187573177082615698496949025806128189691804770100426
unrank 187573177082615698496949025806128189691804770100426x
unrank 187573177082615698496949025806128189691804770100426x
1 2 3 10 100 987654321 135792468107264516704251 7</lang>
1 2 3 10 100 987654321 135792468107264516704251 7</syntaxhighlight>


Prime factorization (Gödelian) encoding:
Prime factorization (Gödelian) encoding:


<lang j> rank=. */@:(^~ p:@:i.@:#)@:>:@:x:
<syntaxhighlight lang="j"> rank=. */@:(^~ p:@:i.@:#)@:>:@:x:
unrank=. <:@:(#;.1@:~:@:q:)</lang>
unrank=. <:@:(#;.1@:~:@:q:)</syntaxhighlight>


Example use:
Example use:


<lang J> rank 1 11 16 1 3 9 0 2 15 7 19 10
<syntaxhighlight lang="j"> rank 1 11 16 1 3 9 0 2 15 7 19 10
6857998574998940803374702726455974765530187550029640884386375715876970128518999225074067307280381624132537960815429687500
6857998574998940803374702726455974765530187550029640884386375715876970128518999225074067307280381624132537960815429687500
unrank 6857998574998940803374702726455974765530187550029640884386375715876970128518999225074067307280381624132537960815429687500x
unrank 6857998574998940803374702726455974765530187550029640884386375715876970128518999225074067307280381624132537960815429687500x
1 11 16 1 3 9 0 2 15 7 19 10</lang>
1 11 16 1 3 9 0 2 15 7 19 10</syntaxhighlight>


=== Bijective ===
=== Bijective ===
Line 497: Line 497:
Using the method of the Python version (shifted):
Using the method of the Python version (shifted):


<lang j> rank=. 1 -~ #.@:(1 , >@:(([ , 0 , ])&.>/)@:(<@:($&1)"0))@:x:
<syntaxhighlight lang="j"> rank=. 1 -~ #.@:(1 , >@:(([ , 0 , ])&.>/)@:(<@:($&1)"0))@:x:
unrank=. #;._2@:((0 ,~ }.)@:(#.^:_1)@:(1&+))</lang>
unrank=. #;._2@:((0 ,~ }.)@:(#.^:_1)@:(1&+))</syntaxhighlight>


Example use:
Example use:


<lang J> >@:((] ; unrank ; rank@:unrank)&.>)@:i. 11
<syntaxhighlight lang="j"> >@:((] ; unrank ; rank@:unrank)&.>)@:i. 11
┌──┬───────┬──┐
┌──┬───────┬──┐
│0 │0 │0 │
│0 │0 │0 │
Line 530: Line 530:
┌─────────┬────────┬─────────┐
┌─────────┬────────┬─────────┐
│1 2 3 5 8│14401278│1 2 3 5 8│
│1 2 3 5 8│14401278│1 2 3 5 8│
└─────────┴────────┴─────────┘</lang>
└─────────┴────────┴─────────┘</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
Translation of [[Index_finite_lists_of_positive_integers#Python|Python]] via [[Index_finite_lists_of_positive_integers#D|D]]
Translation of [[Index_finite_lists_of_positive_integers#Python|Python]] via [[Index_finite_lists_of_positive_integers#D|D]]
{{works with|Java|8}}
{{works with|Java|8}}
<lang java>import java.math.BigInteger;
<syntaxhighlight lang="java">import java.math.BigInteger;
import static java.util.Arrays.stream;
import static java.util.Arrays.stream;
import java.util.*;
import java.util.*;
Line 562: Line 562:
System.out.println(unrank(rank(s)));
System.out.println(unrank(rank(s)));
}
}
}</lang>
}</syntaxhighlight>
<pre>[1, 2, 3, 10, 100, 987654321]
<pre>[1, 2, 3, 10, 100, 987654321]
37699814998383067155219233
37699814998383067155219233
Line 570: Line 570:
{{trans|Python}}
{{trans|Python}}


<lang julia>using LinearAlgebra
<syntaxhighlight lang="julia">using LinearAlgebra
LinearAlgebra.rank(x::Vector{<:Integer}) = parse(BigInt, "1a" * join(x, 'a'), base=11)
LinearAlgebra.rank(x::Vector{<:Integer}) = parse(BigInt, "1a" * join(x, 'a'), base=11)
function unrank(n::Integer)
function unrank(n::Integer)
Line 585: Line 585:
n = rank(v)
n = rank(v)
v = unrank(n)
v = unrank(n)
println("# v = $v\n -> n = $n\n -> v = $v")</lang>
println("# v = $v\n -> n = $n\n -> v = $v")</syntaxhighlight>


{{out}}
{{out}}
Line 593: Line 593:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2


import java.math.BigInteger
import java.math.BigInteger
Line 646: Line 646:
println("${"%2d".format(i)} -> ${li.toString().padEnd(9)} -> ${rank2(li)}")
println("${"%2d".format(i)} -> ${li.toString().padEnd(9)} -> ${rank2(li)}")
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 674: Line 674:


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>ClearAll[Rank,Unrank]
<syntaxhighlight lang="mathematica">ClearAll[Rank,Unrank]
Rank[x_List]:=FromDigits[Catenate[Riffle[IntegerDigits/@x,{{15}},{1,-1,2}]],16]
Rank[x_List]:=FromDigits[Catenate[Riffle[IntegerDigits/@x,{{15}},{1,-1,2}]],16]
Unrank[n_Integer]:=FromDigits/@SequenceSplit[IntegerDigits[n,16],{15}]
Unrank[n_Integer]:=FromDigits/@SequenceSplit[IntegerDigits[n,16],{15}]
Rank[{0,1,2,3,10,100,987654321,0}]
Rank[{0,1,2,3,10,100,987654321,0}]
Unrank[%]
Unrank[%]
First@*Unrank@*Rank@*List /@ Range[0, 20]</lang>
First@*Unrank@*Rank@*List /@ Range[0, 20]</syntaxhighlight>
{{out}}
{{out}}
<pre>4886947482322057719812858634706703
<pre>4886947482322057719812858634706703
Line 688: Line 688:
{{trans|Go}}
{{trans|Go}}
{{libheader|bignum}}
{{libheader|bignum}}
<lang Nim>import strformat, strutils
<syntaxhighlight lang="nim">import strformat, strutils
import bignum
import bignum


Line 718: Line 718:
let u = b.unrank()
let u = b.unrank()
let r = u.rank()
let r = u.rank()
echo &"\n{b}\n{u}\n{r}"</lang>
echo &"\n{b}\n{u}\n{r}"</syntaxhighlight>


{{out}}
{{out}}
Line 741: Line 741:
{{trans|Raku}}
{{trans|Raku}}
{{libheader|ntheory}}
{{libheader|ntheory}}
<lang perl>use bigint;
<syntaxhighlight lang="perl">use bigint;
use ntheory qw(fromdigits todigitstring);
use ntheory qw(fromdigits todigitstring);
use feature 'say';
use feature 'say';
Line 750: Line 750:
say join ' ', @n = qw<12 11 0 7 9 15 15 5 7 13 5 5>;
say join ' ', @n = qw<12 11 0 7 9 15 15 5 7 13 5 5>;
say $n = rank(@n);
say $n = rank(@n);
say join ' ', unrank $n;</lang>
say join ' ', unrank $n;</syntaxhighlight>
{{out}}
{{out}}
<pre>12 11 0 7 9 15 15 5 7 13 5 5
<pre>12 11 0 7 9 15 15 5 7 13 5 5
Line 761: Line 761:
{{libheader|Phix/mpfr}}
{{libheader|Phix/mpfr}}
Note this is ''not'' supported under pwa/p2js because mpz_set_str() currently only handles bases 2, 8, 10, and 16.
Note this is ''not'' supported under pwa/p2js because mpz_set_str() currently only handles bases 2, 8, 10, and 16.
<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">without</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">without</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
Line 786: Line 786:
<span style="color: #004080;">sequence</span> <span style="color: #000000;">u</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">unrank</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">u</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">unrank</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%V\n"</span><span style="color: #0000FF;">,{{</span><span style="color: #000000;">l</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">mpz_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">),</span><span style="color: #000000;">u</span><span style="color: #0000FF;">}})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%V\n"</span><span style="color: #0000FF;">,{{</span><span style="color: #000000;">l</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">mpz_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">),</span><span style="color: #000000;">u</span><span style="color: #0000FF;">}})</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 794: Line 794:
===bijective===
===bijective===
{{trans|Python}}
{{trans|Python}}
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">unrank</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">unrank</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
Line 821: Line 821:
<span style="color: #004080;">sequence</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8</span><span style="color: #0000FF;">}</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8</span><span style="color: #0000FF;">}</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%v =&gt; %d =&gt; %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">rank</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">),</span><span style="color: #000000;">unrank</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rank</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">))})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%v =&gt; %d =&gt; %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">rank</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">),</span><span style="color: #000000;">unrank</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rank</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">))})</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 839: Line 839:


=={{header|Python}}==
=={{header|Python}}==
<lang python>def rank(x): return int('a'.join(map(str, [1] + x)), 11)
<syntaxhighlight lang="python">def rank(x): return int('a'.join(map(str, [1] + x)), 11)


def unrank(n):
def unrank(n):
Line 851: Line 851:
print n
print n
l = unrank(n)
l = unrank(n)
print l</lang>
print l</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 861: Line 861:
=== Bijection ===
=== Bijection ===
Each number in the list is stored as a length of 1s, separated by 0s, and the resulting string is prefixed by '1', then taken as a binary number. Empty list is mapped to 0 as a special case. Don't use it on large numbers.
Each number in the list is stored as a length of 1s, separated by 0s, and the resulting string is prefixed by '1', then taken as a binary number. Empty list is mapped to 0 as a special case. Don't use it on large numbers.
<lang python>def unrank(n):
<syntaxhighlight lang="python">def unrank(n):
return map(len, bin(n)[3:].split("0")) if n else []
return map(len, bin(n)[3:].split("0")) if n else []


Line 873: Line 873:
x = [1, 2, 3, 5, 8];
x = [1, 2, 3, 5, 8];
print x, rank(x), unrank(rank(x))
print x, rank(x), unrank(rank(x))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 893: Line 893:
=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery> [ $ "" swap
<syntaxhighlight lang="quackery"> [ $ "" swap
witheach
witheach
[ number$
[ number$
Line 912: Line 912:
else join ]
else join ]
drop ] is unrank ( n --> [ )
drop ] is unrank ( n --> [ )
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 938: Line 938:
{{trans|Tcl}} (which gives credit to [[#D]])
{{trans|Tcl}} (which gives credit to [[#D]])


<lang racket>#lang racket/base
<syntaxhighlight lang="racket">#lang racket/base
(require (only-in racket/string string-join string-split))
(require (only-in racket/string string-join string-split))


Line 959: Line 959:
(displayln loi)
(displayln loi)
(displayln rnk)
(displayln rnk)
(displayln urk))</lang>
(displayln urk))</syntaxhighlight>


{{out}}
{{out}}
Line 970: Line 970:
(formerly Perl 6)
(formerly Perl 6)
Here is a cheap solution using a base-11 encoding and string operations:
Here is a cheap solution using a base-11 encoding and string operations:
<lang perl6>sub rank(*@n) { :11(@n.join('A')) }
<syntaxhighlight lang="raku" line>sub rank(*@n) { :11(@n.join('A')) }
sub unrank(Int $n) { $n.base(11).split('A') }
sub unrank(Int $n) { $n.base(11).split('A') }


say my @n = (1..20).roll(12);
say my @n = (1..20).roll(12);
say my $n = rank(@n);
say my $n = rank(@n);
say unrank $n;</lang>
say unrank $n;</syntaxhighlight>
{{out}}
{{out}}
<pre>1 11 16 1 3 9 0 2 15 7 19 10
<pre>1 11 16 1 3 9 0 2 15 7 19 10
Line 983: Line 983:
Here is a bijective solution that does not use string operations.
Here is a bijective solution that does not use string operations.


<lang perl6>multi infix:<rad> () { 0 }
<syntaxhighlight lang="raku" line>multi infix:<rad> () { 0 }
multi infix:<rad> ($a) { $a }
multi infix:<rad> ($a) { $a }
multi infix:<rad> ($a, $b) { $a * $*RADIX + $b }
multi infix:<rad> ($a, $b) { $a * $*RADIX + $b }
Line 1,023: Line 1,023:
my @unrank = unrank $_;
my @unrank = unrank $_;
say "$_ -> [$@unrank] -> {rank @unrank}";
say "$_ -> [$@unrank] -> {rank @unrank}";
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,042: Line 1,042:


No checks are made that the numbers are non-negative integers or malformed integers.
No checks are made that the numbers are non-negative integers or malformed integers.
<lang rexx>/*REXX program assigns an integer for a finite list of arbitrary non-negative integers. */
<syntaxhighlight lang="rexx">/*REXX program assigns an integer for a finite list of arbitrary non-negative integers. */
parse arg $ /*obtain optional argument (int list).*/
parse arg $ /*obtain optional argument (int list).*/
if $='' | $="," then $=3 14 159 265358979323846 /*Not specified? Then use the default.*/
if $='' | $="," then $=3 14 159 265358979323846 /*Not specified? Then use the default.*/
Line 1,055: Line 1,055:
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
rank: return x2d( translate( space( arg(1) ), 'c', ",") )
rank: return x2d( translate( space( arg(1) ), 'c', ",") )
unrank: return space( translate( d2x( arg(1) ), ',', "C") )</lang>
unrank: return space( translate( d2x( arg(1) ), ',', "C") )</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
{{out|output|text=&nbsp; when using the default input:}}
<pre>
<pre>
Line 1,065: Line 1,065:
=={{header|Ruby}}==
=={{header|Ruby}}==
{{trans|Python}}
{{trans|Python}}
<lang ruby>def rank(arr)
<syntaxhighlight lang="ruby">def rank(arr)
arr.join('a').to_i(11)
arr.join('a').to_i(11)
end
end
Line 1,078: Line 1,078:
p n
p n
l = unrank(n)
l = unrank(n)
p l</lang>
p l</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,087: Line 1,087:
=== Bijection ===
=== Bijection ===
{{trans|Python}}
{{trans|Python}}
<lang ruby>def unrank(n)
<syntaxhighlight lang="ruby">def unrank(n)
return [0] if n==1
return [0] if n==1
n.to_s(2)[1..-1].split('0',-1).map(&:size)
n.to_s(2)[1..-1].split('0',-1).map(&:size)
Line 1,103: Line 1,103:
puts
puts
x = [1, 2, 3, 5, 8]
x = [1, 2, 3, 5, 8]
puts "#{x} => #{rank(x)} => #{unrank(rank(x))}"</lang>
puts "#{x} => #{rank(x)} => #{unrank(rank(x))}"</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,123: Line 1,123:
=={{header|Scala}}==
=={{header|Scala}}==
{{Out}}Best seen in running your browser either by [https://scalafiddle.io/sf/7NvnU4t/0 ScalaFiddle (ES aka JavaScript, non JVM)] or [https://scastie.scala-lang.org/l0uAGyyCTDSAV9Q45vRGaA Scastie (remote JVM)].
{{Out}}Best seen in running your browser either by [https://scalafiddle.io/sf/7NvnU4t/0 ScalaFiddle (ES aka JavaScript, non JVM)] or [https://scastie.scala-lang.org/l0uAGyyCTDSAV9Q45vRGaA Scastie (remote JVM)].
<lang Scala>object IndexFiniteList extends App {
<syntaxhighlight lang="scala">object IndexFiniteList extends App {
val (defBase, s) = (10, Seq(1, 2, 3, 10, 100, 987654321))
val (defBase, s) = (10, Seq(1, 2, 3, 10, 100, 987654321))


Line 1,138: Line 1,138:
println(unrank(ranked).mkString("[", ", ", "]"))
println(unrank(ranked).mkString("[", ", ", "]"))


}</lang>
}</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Ruby}}
{{trans|Ruby}}
<lang ruby>func rank(Array arr) {
<syntaxhighlight lang="ruby">func rank(Array arr) {
Number(arr.join('a'), 11)
Number(arr.join('a'), 11)
}
}
Line 1,155: Line 1,155:
say n
say n
var l = unrank(n)
var l = unrank(n)
say l</lang>
say l</syntaxhighlight>
{{out}}
{{out}}
<pre>[1, 2, 3, 10, 100, 987654321]
<pre>[1, 2, 3, 10, 100, 987654321]
Line 1,162: Line 1,162:


'''Bijection:'''
'''Bijection:'''
<lang ruby>func unrank(Number n) {
<syntaxhighlight lang="ruby">func unrank(Number n) {
n == 1 ? [0]
n == 1 ? [0]
: n.base(2).substr(1).split('0', -1).map{.len}
: n.base(2).substr(1).split('0', -1).map{.len}
Line 1,178: Line 1,178:
say ''
say ''
var x = [1, 2, 3, 5, 8]
var x = [1, 2, 3, 5, 8]
say "#{x} => #{rank(x)} => #{unrank(rank(x))}"</lang>
say "#{x} => #{rank(x)} => #{unrank(rank(x))}"</syntaxhighlight>
{{out}}
{{out}}
<pre> 0 : [] : 0
<pre> 0 : [] : 0
Line 1,197: Line 1,197:
{{works with|Tcl|8.6}}
{{works with|Tcl|8.6}}
Inspired by the [[#D|D solution]].
Inspired by the [[#D|D solution]].
<lang tcl>package require Tcl 8.6
<syntaxhighlight lang="tcl">package require Tcl 8.6


proc rank {integers} {
proc rank {integers} {
Line 1,205: Line 1,205:
proc unrank {codedValue} {
proc unrank {codedValue} {
lmap i [split $codedValue 8] {scan $i %llo}
lmap i [split $codedValue 8] {scan $i %llo}
}</lang>
}</syntaxhighlight>
Demonstrating:
Demonstrating:
<lang tcl>set s {1 2 3 10 100 987654321 135792468107264516704251 7}
<syntaxhighlight lang="tcl">set s {1 2 3 10 100 987654321 135792468107264516704251 7}
puts "prior: $s"
puts "prior: $s"
set c [rank $s]
set c [rank $s]
puts "encoded: $c"
puts "encoded: $c"
set t [unrank $c]
set t [unrank $c]
puts "after: $t"</lang>
puts "after: $t"</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,223: Line 1,223:
{{trans|Kotlin}}
{{trans|Kotlin}}
{{libheader|Wren-big}}
{{libheader|Wren-big}}
<lang ecmascript>import "/big" for BigInt
<syntaxhighlight lang="ecmascript">import "/big" for BigInt


// Separates each integer in the list with an 'a' then encodes in base 11.
// Separates each integer in the list with an 'a' then encodes in base 11.
Line 1,263: Line 1,263:
System.print("Rank = %(r)")
System.print("Rank = %(r)")
li = unrank2.call(r)
li = unrank2.call(r)
System.print("After unranking : %(li)")</lang>
System.print("After unranking : %(li)")</syntaxhighlight>


{{out}}
{{out}}
Line 1,280: Line 1,280:
=={{header|zkl}}==
=={{header|zkl}}==
Using GMP, base 11 and sometimes strings to represent big ints.
Using GMP, base 11 and sometimes strings to represent big ints.
<lang zkl>var BN=Import("zklBigNum");
<syntaxhighlight lang="zkl">var BN=Import("zklBigNum");
fcn rank(ns) { BN(ns.concat("A"),11) }
fcn rank(ns) { BN(ns.concat("A"),11) }
fcn unrank(bn) { bn.toString(11).split("a").apply("toInt") }
fcn unrank(bn) { bn.toString(11).split("a").apply("toInt") }
fcn unrankS(bn){ bn.toString(11).split("a") }</lang>
fcn unrankS(bn){ bn.toString(11).split("a") }</syntaxhighlight>
<lang zkl>fcn rankz(ns,S=False){
<syntaxhighlight lang="zkl">fcn rankz(ns,S=False){
ns.println();
ns.println();
rank(ns).println();
rank(ns).println();
Line 1,291: Line 1,291:
}
}
rankz(T(1,2,3,10,100,987654321));
rankz(T(1,2,3,10,100,987654321));
rankz(T(1,2,3,10,100,987654321,"135792468107264516704251",7),True);</lang>
rankz(T(1,2,3,10,100,987654321,"135792468107264516704251",7),True);</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>