Rice coding: Difference between revisions

→‎{{header|raku}}: no need to create a module here
(→‎{{header|raku}}: no need to create a module here)
Line 109:
=={{header|raku}}==
 
<syntaxhighlight lang="raku">unit modulepackage Rice; {
 
our sub encode(Int $n, UInt :$k = 2) {
my $d = 2**$k;
my $q = $n div $d;
my $b = sign(1 + sign($q));
my $m = abs($q) + $b;
flat
$b xx $m, 1 - $b,
($n mod $d).polymod(2 xx $k - 1).reverse
}
 
our sub decode(@bits is copy, UInt :$k = 2) {
my $d = 2**$k;
my $b = @bits.shift;
my $m = 1;
$m++ while @bits and @bits.shift == $b;
my $q = $b ?? $m - 1 !! -$m;
$q*$d + @bits.reduce(2 * * + *);
}
 
our sub decode(@bits is copy, UInt :$k = 2) {
my $d = 2**$k;
my $b = @bits.shift;
my $m = 1;
$m++ while @bits and @bits.shift == $b;
my $q = $b ?? $m - 1 !! -$m;
$q*$d + @bits.reduce(2 * * + *);
}
 
use Test;
CHECK {
constant N = 100;
use Test;
plan constant 2*N =+ 1001;
is $_, Rice::decode Rice::encode $_ for -N..N;</syntaxhighlight>
plan 2*N + 1;
is $_, decode encode $_ for -N..N;
}</syntaxhighlight>
 
=={{header|Wren}}==
1,934

edits