Rice coding: Difference between revisions
Content added Content deleted
(julia example) |
(Made this into a draft task and added a Wren example.) |
||
Line 1: | Line 1: | ||
{{draft task}} |
|||
'''Rice coding''' is a variant of [[w:Golomb coding|Golomb coding]] where the parameter is a power of two. This makes it easier to encode the remainder of the euclidean division. |
'''Rice coding''' is a variant of [[w:Golomb coding|Golomb coding]] where the parameter is a power of two. This makes it easier to encode the remainder of the euclidean division. |
||
Line 104: | Line 105: | ||
is $_, decode encode $_ for -N..N; |
is $_, decode encode $_ for -N..N; |
||
}</syntaxhighlight> |
}</syntaxhighlight> |
||
=={{header|Wren}}== |
|||
{{trans|Julia}} |
|||
{{libheader|Wren-math}} |
|||
{{libheader|Wren-check}} |
|||
{{libheader|Wren-fmt}} |
|||
<syntaxhighlight lang="ecmascript">import "./math" for Int, Math |
|||
import "./check" for Check |
|||
import "./fmt" for Fmt |
|||
class Rice { |
|||
static encode(n, k) { |
|||
Check.nonNegInt("n", n) |
|||
var m = 1 << k |
|||
var q = Int.quo(n, m) |
|||
var r = n % m |
|||
var res = List.filled(q, 1) |
|||
res.add(0) |
|||
var digits = Int.digits(r, 2) |
|||
var dc = digits.count |
|||
if (dc < k + 1) res.addAll([0] * (k + 1 - dc)) |
|||
res.addAll(digits) |
|||
return res |
|||
} |
|||
static encodeEx(n, k) { encode(n < 0 ? -2 * n - 1 : 2 * n, k) } |
|||
static decode(a, k) { |
|||
var m = 1 << k |
|||
var q = a.indexOf(0) |
|||
if (q == -1) q = 0 |
|||
var r = Math.evalPoly(a[q..-1], 2) |
|||
return q * m + r |
|||
} |
|||
static decodeEx(a, k) { |
|||
var i = decode(a, k) |
|||
return i % 2 == 1 ? -Int.quo(i+1, 2) : Int.quo(i, 2) |
|||
} |
|||
} |
|||
System.print("Basic Rice coding:") |
|||
for (i in 0..10) { |
|||
var res = Rice.encode(i, 2) |
|||
Fmt.print("$2d -> $-6s -> $d", i, res.join(""), Rice.decode(res, 2)) |
|||
} |
|||
System.print("\nExtended Rice coding") |
|||
for (i in -10..10) { |
|||
var res = Rice.encodeEx(i, 2) |
|||
Fmt.print("$3d -> $-9s -> $ d", i, res.join(""), Rice.decodeEx(res, 2)) |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Basic Rice coding: |
|||
0 -> 0000 -> 0 |
|||
1 -> 0001 -> 1 |
|||
2 -> 0010 -> 2 |
|||
3 -> 0011 -> 3 |
|||
4 -> 10000 -> 4 |
|||
5 -> 10001 -> 5 |
|||
6 -> 10010 -> 6 |
|||
7 -> 10011 -> 7 |
|||
8 -> 110000 -> 8 |
|||
9 -> 110001 -> 9 |
|||
10 -> 110010 -> 10 |
|||
Extended Rice coding |
|||
-10 -> 11110011 -> -10 |
|||
-9 -> 11110001 -> -9 |
|||
-8 -> 1110011 -> -8 |
|||
-7 -> 1110001 -> -7 |
|||
-6 -> 110011 -> -6 |
|||
-5 -> 110001 -> -5 |
|||
-4 -> 10011 -> -4 |
|||
-3 -> 10001 -> -3 |
|||
-2 -> 0011 -> -2 |
|||
-1 -> 0001 -> -1 |
|||
0 -> 0000 -> 0 |
|||
1 -> 0010 -> 1 |
|||
2 -> 10000 -> 2 |
|||
3 -> 10010 -> 3 |
|||
4 -> 110000 -> 4 |
|||
5 -> 110010 -> 5 |
|||
6 -> 1110000 -> 6 |
|||
7 -> 1110010 -> 7 |
|||
8 -> 11110000 -> 8 |
|||
9 -> 11110010 -> 9 |
|||
10 -> 111110000 -> 10 |
|||
</pre> |