Rice coding: Difference between revisions

From Rosetta Code
Content added Content deleted
(new task)
 
mNo edit summary
Line 1: Line 1:
'''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.


Implement Rice coding in your programming and verify that you can consistently encode and decode a list of examples (for instance numbers from 0 to 10 or something).
Implement Rice coding in your programming language and verify that you can consistently encode and decode a list of examples (for instance numbers from 0 to 10 or something).


Rice coding is initially meant to encode [[w:natural numbers|natural numbers]], but since [[w:relative numbers|relative numbers]] are [[w:countable|countable]], it is fairly easy to modify Rice coding to encode them too. You can do that for extra credit.
Rice coding is initially meant to encode [[w:natural numbers|natural numbers]], but since [[w:relative numbers|relative numbers]] are [[w:countable|countable]], it is fairly easy to modify Rice coding to encode them too. You can do that for extra credit.

Revision as of 11:01, 20 September 2023

Rice coding is a variant of Golomb coding where the parameter is a power of two. This makes it easier to encode the remainder of the euclidean division.

Implement Rice coding in your programming language and verify that you can consistently encode and decode a list of examples (for instance numbers from 0 to 10 or something).

Rice coding is initially meant to encode natural numbers, but since relative numbers are countable, it is fairly easy to modify Rice coding to encode them too. You can do that for extra credit.

raku

unit module 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 * * + *);
}

CHECK {
  use Test;
  constant N = 100;
  plan 2*N + 1;
  is $_, decode encode $_ for -N..N;
}