Index finite lists of positive integers: Difference between revisions
Index finite lists of positive integers (view source)
Revision as of 08:39, 1 February 2024
, 4 months ago→{{header|jq}}: simplify
Drkameleon (talk | contribs) (Added Arturo implementation) |
(→{{header|jq}}: simplify) |
||
(18 intermediate revisions by 3 users not shown) | |||
Line 28:
{{trans|Python}}
<
R BigInt(([1] [+] x).map(String).join(‘A’), radix' 11)
Line 40:
print(n)
l = unrank(n)
print(l)</
{{out}}
Line 51:
=={{header|Arturo}}==
<
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]</
{{out}}
Line 81:
This solution isn't efficient.
{{trans|Python}}
<
BigInt rank(T)(in T[] x) pure /*nothrow*/ @safe {
Line 101:
s.rank.writeln;
s.rank.unrank.writeln;
}</
{{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.
<
A as ulongint
B as ulongint
Line 202:
print R,
unrank R, X()
show_list(X())</
{{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.
<
import (
Line 251:
r := rank(u)
fmt.Printf("\n%v\n%d\n%d\n", &b, u, &r)
}</
{{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.
<
import (
Line 365:
}
return l
}</
{{out}}
<pre>
Line 385:
=={{header|Haskell}}==
<
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</
Using different bases we may enumerate lists.
Line 440:
Implementation:
<
n=.1x+>./y
#.(1#~##:n),0,n,&#:n#.y
Line 450:
n=.#.m{.(m+1)}.b
n #.inv#.(1+2*m)}.b
)</
Example use:
<
4314664669630761
hcnurcs 4314664669630761
4 5 7 9 0 8 8 7 4 8 8 4 1</
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:
<
unrank=. 10&#.;._1@:(10&,)@:(11&#.^:_1)</
Example use:
<
187573177082615698496949025806128189691804770100426
unrank 187573177082615698496949025806128189691804770100426x
1 2 3 10 100 987654321 135792468107264516704251 7</
Prime factorization (Gödelian) encoding:
<
unrank=. <:@:(#;.1@:~:@:q:)</
Example use:
<
6857998574998940803374702726455974765530187550029640884386375715876970128518999225074067307280381624132537960815429687500
unrank 6857998574998940803374702726455974765530187550029640884386375715876970128518999225074067307280381624132537960815429687500x
1 11 16 1 3 9 0 2 15 7 19 10</
=== Bijective ===
Line 497:
Using the method of the Python version (shifted):
<
unrank=. #;._2@:((0 ,~ }.)@:(#.^:_1)@:(1&+))</
Example use:
<
┌──┬───────┬──┐
│0 │0 │0 │
Line 530:
┌─────────┬────────┬─────────┐
│1 2 3 5 8│14401278│1 2 3 5 8│
└─────────┴────────┴─────────┘</
=={{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}}
<
import static java.util.Arrays.stream;
import java.util.*;
Line 562:
System.out.println(unrank(rank(s)));
}
}</
<pre>[1, 2, 3, 10, 100, 987654321]
37699814998383067155219233
[1, 2, 3, 10, 100, 987654321]</pre>
=={{header|jq}}==
'''Works with gojq'''
'''Works with jq''' within the limits of jq's support for large integer arithmetic
'''Works with jaq within the limits of jaq's support for large integers'''
The main point of interest of this entry is probably the use of the
Fibonacci encoding of positive integers (see
e.g. https://en.wikipedia.org/wiki/Fibonacci_coding and
[[:Category:jq/fibonacci.jq]]). This is the focus of the first
subsection. The second subsection focuses on the "n 0s" encoding.
The Go implementation of jq supports indefinitely large integers and
so, apart from machine limitations, the programs shown here should
work using gojq without further qualification.
The C implementation of jq, as of version 1.6, supports arbitrarily
large literal integers, and the `tonumber` filter retains precision
allowing seamless translation between strings and numbers.
The following is slightly more verbose than it need be but for the
sake of compatibility with jaq. Also note that trivial changes would
be required if using jaq as jaq does not (as of this writing in 2024)
support the `include` or `module` directives.
===Map based on Fibonacci encoding===
Since each Fibonacci-encoded integer ends with "11" and
contains no other instances of "11" before the end,
the original sequence of integers can trivially be recovered after
simple concatenation of the encodings. However, the Fibonacci
encoding of an integer can begin with 0s, so here we simply prefix
the binary string with a "1".
For example: 1 2 3 => 11 011 0011 => 1110110011
In the following, we will simply interpret
this as an integer in base 2 to avoid unnecessary complications
arising from implementation-specific limits.
<syntaxhighlight lang="jq">
include "fibonacci" {search: "./"}; # see https://rosettacode.org/wiki/Category:Jq/fibonacci.jq
# Input: an array of integers
# Output: an integer-valued binary string, being the reverse of the concatenated Fibonacci-encoded values
def rank:
map(fibencode | map(tostring) | join(""))
| "1" + join("");
# Input a bitstring or 0-1 integer interpreted as a bitstring
# Output: an array of integers
def unrank:
tostring
| .[1:]
| split("11")
| .[:-1]
| map(. + "11" | fibdecode) ;
# Output: a PRN in range(0;$n) where $n is .
def prn:
if . == 1 then 0
else . as $n
| (($n-1)|tostring|length) as $w
| [limit($w; inputs) | tostring] | join("") | sub("^0+";"") | tonumber
| if . < $n then . else $n | prn end
end;
### The task
# Encode and decode a random number of distinct positive numbers chosen at random.
# Produce a JSON object showing the set of numbers, their encoding, and
# the result of comparing the original set with the reconstructed set.
def task:
(11 | prn) + 1
| . as $numbers
| [range(0;$numbers) | 100000 | prn + 1]
| . as $numbers
| rank
| . as $encoded
# now decode:
| unrank
| {$numbers, encoded: ($encoded|tonumber), check: ($numbers == .)}
;
task
</syntaxhighlight>
'''Invocation''':
<pre>
< /dev/random tr -cd '0-9' | fold -w 1 | jq -nrf index-finite-lists-of-positive-integers.jq
</pre>
{{output}}
<pre>
{
"numbers": [
92408,
42641,
35563,
17028,
49093
],
"encoded": 101000101000001010101000111000001010001000100101100010101010000000010011001001001001000101011000101010100000010000011,
"check": true
}
</pre>
===Bijective map based on "n 0s" encoding===
<syntaxhighlight lang="jq">
### Infrastructure
# Input: a string in base $b (2 to 35 inclusive)
# Output: the decimal value
def frombase($b):
def decimalValue:
if 48 <= . and . <= 57 then . - 48
elif 65 <= . and . <= 90 then . - 55 # (10+.-65)
elif 97 <= . and . <= 122 then . - 87 # (10+.-97)
else "decimalValue" | error
end;
reduce (explode|reverse[]|decimalValue) as $x ({p:1};
.value += (.p * $x)
| .p *= $b)
| .value ;
def binary_digits:
if . == 0 then 0
else [recurse( if . == 0 then empty else ./2 | floor end ) % 2 | tostring]
| reverse
| .[1:] # remove the leading 0
| join("")
end ;
### rank and unrank
# Each integer n in the list is mapped to '1' plus n '0's.
# The empty list is mapped to '0'
def rank:
if length == 0 then 0
else reduce .[] as $i ("";
. += "1" + ("0" * $i))
| frombase(2)
end ;
def unrank:
if . == 0 then []
else binary_digits
| split("1")
| .[1:]
| map(length)
end ;
### Illustration
range(1;11)
| . as $i
| unrank
| . as $unrank
| [$i, $unrank, rank]
</syntaxhighlight>
{{output}}
<pre>
[1,[0],1]
[2,[1],2]
[3,[0,0],3]
[4,[2],4]
[5,[1,0],5]
[6,[0,1],6]
[7,[0,0,0],7]
[8,[3],8]
[9,[2,0],9]
[10,[1,1],10]
</pre>
=={{header|Julia}}==
{{trans|Python}}
<
LinearAlgebra.rank(x::Vector{<:Integer}) = parse(BigInt, "1a" * join(x, 'a'), base=11)
function unrank(n::Integer)
Line 585 ⟶ 756:
n = rank(v)
v = unrank(n)
println("# v = $v\n -> n = $n\n -> v = $v")</
{{out}}
Line 593 ⟶ 764:
=={{header|Kotlin}}==
<
import java.math.BigInteger
Line 646 ⟶ 817:
println("${"%2d".format(i)} -> ${li.toString().padEnd(9)} -> ${rank2(li)}")
}
}</
{{out}}
Line 674 ⟶ 845:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
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]</
{{out}}
<pre>4886947482322057719812858634706703
Line 688 ⟶ 859:
{{trans|Go}}
{{libheader|bignum}}
<
import bignum
Line 718 ⟶ 889:
let u = b.unrank()
let r = u.rank()
echo &"\n{b}\n{u}\n{r}"</
{{out}}
Line 741 ⟶ 912:
{{trans|Raku}}
{{libheader|ntheory}}
<
use ntheory qw(fromdigits todigitstring);
use feature 'say';
Line 750 ⟶ 921:
say join ' ', @n = qw<12 11 0 7 9 15 15 5 7 13 5 5>;
say $n = rank(@n);
say join ' ', unrank $n;</
{{out}}
<pre>12 11 0 7 9 15 15 5 7 13 5 5
Line 761 ⟶ 932:
{{libheader|Phix/mpfr}}
Note this is ''not'' supported under pwa/p2js because mpz_set_str() currently only handles bases 2, 8, 10, and 16.
<!--<
<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 ⟶ 957:
<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>
<!--</
{{out}}
<pre>
Line 794 ⟶ 965:
===bijective===
{{trans|Python}}
<!--<
<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 ⟶ 992:
<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 => %d => %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>
<!--</
{{out}}
<pre>
Line 839 ⟶ 1,010:
=={{header|Python}}==
<
def unrank(n):
Line 851 ⟶ 1,022:
print n
l = unrank(n)
print l</
{{out}}
<pre>
Line 861 ⟶ 1,032:
=== 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.
<
return map(len, bin(n)[3:].split("0")) if n else []
Line 873 ⟶ 1,044:
x = [1, 2, 3, 5, 8];
print x, rank(x), unrank(rank(x))
</syntaxhighlight>
{{out}}
<pre>
Line 893 ⟶ 1,064:
=={{header|Quackery}}==
<
witheach
[ number$
Line 912 ⟶ 1,083:
else join ]
drop ] is unrank ( n --> [ )
</syntaxhighlight>
{{out}}
Line 938 ⟶ 1,109:
{{trans|Tcl}} (which gives credit to [[#D]])
<
(require (only-in racket/string string-join string-split))
Line 959 ⟶ 1,130:
(displayln loi)
(displayln rnk)
(displayln urk))</
{{out}}
Line 970 ⟶ 1,141:
(formerly Perl 6)
Here is a cheap solution using a base-11 encoding and string operations:
<syntaxhighlight lang="raku"
sub unrank(Int $n) { $n.base(11).split('A') }
say my @n = (1..20).roll(12);
say my $n = rank(@n);
say unrank $n;</
{{out}}
<pre>1 11 16 1 3 9 0 2 15 7 19 10
Line 983 ⟶ 1,154:
Here is a bijective solution that does not use string operations.
<syntaxhighlight lang="raku"
multi infix:<rad> ($a) { $a }
multi infix:<rad> ($a, $b) { $a * $*RADIX + $b }
Line 1,023 ⟶ 1,194:
my @unrank = unrank $_;
say "$_ -> [$@unrank] -> {rank @unrank}";
}</
{{out}}
Line 1,042 ⟶ 1,213:
No checks are made that the numbers are non-negative integers or malformed integers.
<
parse arg $ /*obtain optional argument (int list).*/
if $='' | $="," then $=3 14 159 265358979323846 /*Not specified? Then use the default.*/
Line 1,055 ⟶ 1,226:
/*──────────────────────────────────────────────────────────────────────────────────────*/
rank: return x2d( translate( space( arg(1) ), 'c', ",") )
unrank: return space( translate( d2x( arg(1) ), ',', "C") )</
{{out|output|text= when using the default input:}}
<pre>
Line 1,065 ⟶ 1,236:
=={{header|Ruby}}==
{{trans|Python}}
<
arr.join('a').to_i(11)
end
Line 1,078 ⟶ 1,249:
p n
l = unrank(n)
p l</
{{out}}
<pre>
Line 1,087 ⟶ 1,258:
=== Bijection ===
{{trans|Python}}
<
return [0] if n==1
n.to_s(2)[1..-1].split('0',-1).map(&:size)
Line 1,103 ⟶ 1,274:
puts
x = [1, 2, 3, 5, 8]
puts "#{x} => #{rank(x)} => #{unrank(rank(x))}"</
{{out}}
<pre>
Line 1,123 ⟶ 1,294:
=={{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)].
<
val (defBase, s) = (10, Seq(1, 2, 3, 10, 100, 987654321))
Line 1,138 ⟶ 1,309:
println(unrank(ranked).mkString("[", ", ", "]"))
}</
=={{header|Sidef}}==
{{trans|Ruby}}
<
Number(arr.join('a'), 11)
}
Line 1,155 ⟶ 1,326:
say n
var l = unrank(n)
say l</
{{out}}
<pre>[1, 2, 3, 10, 100, 987654321]
Line 1,162 ⟶ 1,333:
'''Bijection:'''
<
n == 1 ? [0]
: n.base(2).substr(1).split('0', -1).map{.len}
Line 1,178 ⟶ 1,349:
say ''
var x = [1, 2, 3, 5, 8]
say "#{x} => #{rank(x)} => #{unrank(rank(x))}"</
{{out}}
<pre> 0 : [] : 0
Line 1,197 ⟶ 1,368:
{{works with|Tcl|8.6}}
Inspired by the [[#D|D solution]].
<
proc rank {integers} {
Line 1,205 ⟶ 1,376:
proc unrank {codedValue} {
lmap i [split $codedValue 8] {scan $i %llo}
}</
Demonstrating:
<
puts "prior: $s"
set c [rank $s]
puts "encoded: $c"
set t [unrank $c]
puts "after: $t"</
{{out}}
<pre>
Line 1,223 ⟶ 1,394:
{{trans|Kotlin}}
{{libheader|Wren-big}}
<
// Separates each integer in the list with an 'a' then encodes in base 11.
Line 1,263 ⟶ 1,434:
System.print("Rank = %(r)")
li = unrank2.call(r)
System.print("After unranking : %(li)")</
{{out}}
Line 1,280 ⟶ 1,451:
=={{header|zkl}}==
Using GMP, base 11 and sometimes strings to represent big ints.
<
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") }</
<
ns.println();
rank(ns).println();
Line 1,291 ⟶ 1,462:
}
rankz(T(1,2,3,10,100,987654321));
rankz(T(1,2,3,10,100,987654321,"135792468107264516704251",7),True);</
{{out}}
<pre>
|