Rice coding: Difference between revisions

(Added Algol 68)
Line 239:
{{Trans|Julia|Using strings to represent the bit vector}}
<syntaxhighlight lang="lua">
do -- Rice encoding - translatedtranslation fromof the Julia sample
 
-- Golomb-Rice encoding helper function
local function do_rice_encode( q, r, k )
local result = {}
for i = 1, q do result[ #result + 1 ] = "1" end
result[ #result + 1 ] = "0"
local dPos, digits, v = #result + 1, 0, r
while v > 0 do
digits = digits + 1
local d = v % 2
v = math.floor( v / 2 )
table.insert( result, dPos, d ~= 0 and "1" or "0" )
end
for pad = digits + 1, k do table.insert( result, dPos, "0" ) end
return table.concat( result, "" )
end
-- Golomb-Rice encoding of a positive number to a bit vector (string of 0s and 1s) using M of 2^k
local function rice_encode( n, k )
Line 261 ⟶ 246:
k = k or 2
local m = math.floor( 2^k )
local result, q, r = {}, math.floor( n / m ), n % m
returnwhile do_rice_encode(r q, r,> k0 )do
table.insert(result[ #result, dPos,+ d1 ] ~= r % 2 == 0 and "10" or "01" )
digitsr = digitsmath.floor( +r 1/ 2 )
end
while #result < k do result[ #result + 1 ] = "0" end
localresult[ #result + 1 ] = {}"0"
for i = 1, q do result[ #result + 1 ] = "1" end
forreturn pad = digits + 1, k dostring.reverse( table.insertconcat( result, dPos, "0" ) end)
end
-- see wikipedia.org/wiki/Golomb_coding#Use_with_signed_integers
Line 286 ⟶ 278:
 
local function extended_rice_decode( a, k )
k = k or 2
local i = rice_decode( a, k )
return math.floor( i % 2 == 1 and - ( ( i + 1 ) / 2 ) or i / 2 )
3,043

edits