Jump to content

Index finite lists of positive integers: Difference between revisions

m
syntax highlighting fixup automation
(Added Arturo implementation)
m (syntax highlighting fixup automation)
Line 28:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F rank(x)
R BigInt(([1] [+] x).map(String).join(‘A’), radix' 11)
 
Line 40:
print(n)
l = unrank(n)
print(l)</langsyntaxhighlight>
 
{{out}}
Line 51:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">rank: function [arr][
if empty? arr -> return 0
from.binary "1" ++ join.with:"0" map arr 'a -> repeat "1" a
Line 70:
 
u: unrank r
print ["Unranked:" u]</langsyntaxhighlight>
 
{{out}}
Line 81:
This solution isn't efficient.
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.array, std.conv, std.bigint;
 
BigInt rank(T)(in T[] x) pure /*nothrow*/ @safe {
Line 101:
s.rank.writeln;
s.rank.unrank.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[1, 2, 3, 10, 100, 987654321]
Line 110:
=={{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.
<langsyntaxhighlight FreeBASIClang="freebasic">type duple
A as ulongint
B as ulongint
Line 202:
print R,
unrank R, X()
show_list(X())</langsyntaxhighlight>
{{out}}
<pre>0 []
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.
<langsyntaxhighlight lang="go">package main
 
import (
Line 251:
r := rank(u)
fmt.Printf("\n%v\n%d\n%d\n", &b, u, &r)
}</langsyntaxhighlight>
{{out}}
<pre>
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.
<langsyntaxhighlight lang="go">package main
 
import (
Line 365:
}
return l
}</langsyntaxhighlight>
{{out}}
<pre>
Line 385:
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">import Data.List
 
toBase :: Int -> Integer -> [Int]
Line 410:
go 0 [] = []
go i (0:xs) = go (i+1) xs
go i (x:xs) = (i*b + x - 1) : go 0 xs</langsyntaxhighlight>
 
Using different bases we may enumerate lists.
Line 440:
Implementation:
 
<langsyntaxhighlight lang="j">scrunch=:3 :0
n=.1x+>./y
#.(1#~##:n),0,n,&#:n#.y
Line 450:
n=.#.m{.(m+1)}.b
n #.inv#.(1+2*m)}.b
)</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight Jlang="j"> scrunch 4 5 7 9 0 8 8 7 4 8 8 4 1
4314664669630761
hcnurcs 4314664669630761
4 5 7 9 0 8 8 7 4 8 8 4 1</langsyntaxhighlight>
 
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:
Base 11 encoding:
 
<langsyntaxhighlight lang="j"> rank =. 11&#.@:}.@:>@:(,&:>/)@:(<@:(10&,)@:(10&#.^:_1)"0)@:x:
unrank=. 10&#.;._1@:(10&,)@:(11&#.^:_1)</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight Jlang="j"> rank 1 2 3 10 100 987654321 135792468107264516704251 7x
187573177082615698496949025806128189691804770100426
unrank 187573177082615698496949025806128189691804770100426x
1 2 3 10 100 987654321 135792468107264516704251 7</langsyntaxhighlight>
 
Prime factorization (Gödelian) encoding:
 
<langsyntaxhighlight lang="j"> rank=. */@:(^~ p:@:i.@:#)@:>:@:x:
unrank=. <:@:(#;.1@:~:@:q:)</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight Jlang="j"> rank 1 11 16 1 3 9 0 2 15 7 19 10
6857998574998940803374702726455974765530187550029640884386375715876970128518999225074067307280381624132537960815429687500
unrank 6857998574998940803374702726455974765530187550029640884386375715876970128518999225074067307280381624132537960815429687500x
1 11 16 1 3 9 0 2 15 7 19 10</langsyntaxhighlight>
 
=== Bijective ===
Line 497:
Using the method of the Python version (shifted):
 
<langsyntaxhighlight lang="j"> rank=. 1 -~ #.@:(1 , >@:(([ , 0 , ])&.>/)@:(<@:($&1)"0))@:x:
unrank=. #;._2@:((0 ,~ }.)@:(#.^:_1)@:(1&+))</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight Jlang="j"> >@:((] ; unrank ; rank@:unrank)&.>)@:i. 11
┌──┬───────┬──┐
│0 │0 │0 │
Line 530:
┌─────────┬────────┬─────────┐
│1 2 3 5 8│14401278│1 2 3 5 8│
└─────────┴────────┴─────────┘</langsyntaxhighlight>
 
=={{header|Java}}==
Translation of [[Index_finite_lists_of_positive_integers#Python|Python]] via [[Index_finite_lists_of_positive_integers#D|D]]
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import java.math.BigInteger;
import static java.util.Arrays.stream;
import java.util.*;
Line 562:
System.out.println(unrank(rank(s)));
}
}</langsyntaxhighlight>
<pre>[1, 2, 3, 10, 100, 987654321]
37699814998383067155219233
Line 570:
{{trans|Python}}
 
<langsyntaxhighlight lang="julia">using LinearAlgebra
LinearAlgebra.rank(x::Vector{<:Integer}) = parse(BigInt, "1a" * join(x, 'a'), base=11)
function unrank(n::Integer)
Line 585:
n = rank(v)
v = unrank(n)
println("# v = $v\n -> n = $n\n -> v = $v")</langsyntaxhighlight>
 
{{out}}
Line 593:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
import java.math.BigInteger
Line 646:
println("${"%2d".format(i)} -> ${li.toString().padEnd(9)} -> ${rank2(li)}")
}
}</langsyntaxhighlight>
 
{{out}}
Line 674:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">ClearAll[Rank,Unrank]
Rank[x_List]:=FromDigits[Catenate[Riffle[IntegerDigits/@x,{{15}},{1,-1,2}]],16]
Unrank[n_Integer]:=FromDigits/@SequenceSplit[IntegerDigits[n,16],{15}]
Rank[{0,1,2,3,10,100,987654321,0}]
Unrank[%]
First@*Unrank@*Rank@*List /@ Range[0, 20]</langsyntaxhighlight>
{{out}}
<pre>4886947482322057719812858634706703
Line 688:
{{trans|Go}}
{{libheader|bignum}}
<langsyntaxhighlight Nimlang="nim">import strformat, strutils
import bignum
 
Line 718:
let u = b.unrank()
let r = u.rank()
echo &"\n{b}\n{u}\n{r}"</langsyntaxhighlight>
 
{{out}}
Line 741:
{{trans|Raku}}
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use bigint;
use ntheory qw(fromdigits todigitstring);
use feature 'say';
Line 750:
say join ' ', @n = qw<12 11 0 7 9 15 15 5 7 13 5 5>;
say $n = rank(@n);
say join ' ', unrank $n;</langsyntaxhighlight>
{{out}}
<pre>12 11 0 7 9 15 15 5 7 13 5 5
Line 761:
{{libheader|Phix/mpfr}}
Note this is ''not'' supported under pwa/p2js because mpz_set_str() currently only handles bases 2, 8, 10, and 16.
<!--<langsyntaxhighlight Phixlang="phix">-->
<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>
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: #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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 794:
===bijective===
{{trans|Python}}
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
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: #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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 839:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">def rank(x): return int('a'.join(map(str, [1] + x)), 11)
 
def unrank(n):
Line 851:
print n
l = unrank(n)
print l</langsyntaxhighlight>
{{out}}
<pre>
Line 861:
=== 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.
<langsyntaxhighlight lang="python">def unrank(n):
return map(len, bin(n)[3:].split("0")) if n else []
 
Line 873:
x = [1, 2, 3, 5, 8];
print x, rank(x), unrank(rank(x))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 893:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ $ "" swap
witheach
[ number$
Line 912:
else join ]
drop ] is unrank ( n --> [ )
</syntaxhighlight>
</lang>
 
{{out}}
Line 938:
{{trans|Tcl}} (which gives credit to [[#D]])
 
<langsyntaxhighlight lang="racket">#lang racket/base
(require (only-in racket/string string-join string-split))
 
Line 959:
(displayln loi)
(displayln rnk)
(displayln urk))</langsyntaxhighlight>
 
{{out}}
Line 970:
(formerly Perl 6)
Here is a cheap solution using a base-11 encoding and string operations:
<syntaxhighlight lang="raku" perl6line>sub rank(*@n) { :11(@n.join('A')) }
sub unrank(Int $n) { $n.base(11).split('A') }
 
say my @n = (1..20).roll(12);
say my $n = rank(@n);
say unrank $n;</langsyntaxhighlight>
{{out}}
<pre>1 11 16 1 3 9 0 2 15 7 19 10
Line 983:
Here is a bijective solution that does not use string operations.
 
<syntaxhighlight lang="raku" perl6line>multi infix:<rad> () { 0 }
multi infix:<rad> ($a) { $a }
multi infix:<rad> ($a, $b) { $a * $*RADIX + $b }
Line 1,023:
my @unrank = unrank $_;
say "$_ -> [$@unrank] -> {rank @unrank}";
}</langsyntaxhighlight>
 
{{out}}
Line 1,042:
 
No checks are made that the numbers are non-negative integers or malformed integers.
<langsyntaxhighlight lang="rexx">/*REXX program assigns an integer for a finite list of arbitrary non-negative integers. */
parse arg $ /*obtain optional argument (int list).*/
if $='' | $="," then $=3 14 159 265358979323846 /*Not specified? Then use the default.*/
Line 1,055:
/*──────────────────────────────────────────────────────────────────────────────────────*/
rank: return x2d( translate( space( arg(1) ), 'c', ",") )
unrank: return space( translate( d2x( arg(1) ), ',', "C") )</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 1,065:
=={{header|Ruby}}==
{{trans|Python}}
<langsyntaxhighlight lang="ruby">def rank(arr)
arr.join('a').to_i(11)
end
Line 1,078:
p n
l = unrank(n)
p l</langsyntaxhighlight>
{{out}}
<pre>
Line 1,087:
=== Bijection ===
{{trans|Python}}
<langsyntaxhighlight lang="ruby">def unrank(n)
return [0] if n==1
n.to_s(2)[1..-1].split('0',-1).map(&:size)
Line 1,103:
puts
x = [1, 2, 3, 5, 8]
puts "#{x} => #{rank(x)} => #{unrank(rank(x))}"</langsyntaxhighlight>
{{out}}
<pre>
Line 1,123:
=={{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)].
<langsyntaxhighlight Scalalang="scala">object IndexFiniteList extends App {
val (defBase, s) = (10, Seq(1, 2, 3, 10, 100, 987654321))
 
Line 1,138:
println(unrank(ranked).mkString("[", ", ", "]"))
 
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">func rank(Array arr) {
Number(arr.join('a'), 11)
}
Line 1,155:
say n
var l = unrank(n)
say l</langsyntaxhighlight>
{{out}}
<pre>[1, 2, 3, 10, 100, 987654321]
Line 1,162:
 
'''Bijection:'''
<langsyntaxhighlight lang="ruby">func unrank(Number n) {
n == 1 ? [0]
: n.base(2).substr(1).split('0', -1).map{.len}
Line 1,178:
say ''
var x = [1, 2, 3, 5, 8]
say "#{x} => #{rank(x)} => #{unrank(rank(x))}"</langsyntaxhighlight>
{{out}}
<pre> 0 : [] : 0
Line 1,197:
{{works with|Tcl|8.6}}
Inspired by the [[#D|D solution]].
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
 
proc rank {integers} {
Line 1,205:
proc unrank {codedValue} {
lmap i [split $codedValue 8] {scan $i %llo}
}</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight lang="tcl">set s {1 2 3 10 100 987654321 135792468107264516704251 7}
puts "prior: $s"
set c [rank $s]
puts "encoded: $c"
set t [unrank $c]
puts "after: $t"</langsyntaxhighlight>
{{out}}
<pre>
Line 1,223:
{{trans|Kotlin}}
{{libheader|Wren-big}}
<langsyntaxhighlight lang="ecmascript">import "/big" for BigInt
 
// Separates each integer in the list with an 'a' then encodes in base 11.
Line 1,263:
System.print("Rank = %(r)")
li = unrank2.call(r)
System.print("After unranking : %(li)")</langsyntaxhighlight>
 
{{out}}
Line 1,280:
=={{header|zkl}}==
Using GMP, base 11 and sometimes strings to represent big ints.
<langsyntaxhighlight lang="zkl">var BN=Import("zklBigNum");
fcn rank(ns) { BN(ns.concat("A"),11) }
fcn unrank(bn) { bn.toString(11).split("a").apply("toInt") }
fcn unrankS(bn){ bn.toString(11).split("a") }</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">fcn rankz(ns,S=False){
ns.println();
rank(ns).println();
Line 1,291:
}
rankz(T(1,2,3,10,100,987654321));
rankz(T(1,2,3,10,100,987654321,"135792468107264516704251",7),True);</langsyntaxhighlight>
{{out}}
<pre>
10,333

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.