Rice coding: Difference between revisions
→{{header|Lua}}: Simplify
(Added Algol 68) |
(→{{header|Lua}}: Simplify) |
||
Line 239:
{{Trans|Julia|Using strings to represent the bit vector}}
<syntaxhighlight lang="lua">
do -- Rice encoding -
local result = {}▼
for i = 1, q do result[ #result + 1 ] = "1" end▼
result[ #result + 1 ] = "0"▼
digits = digits + 1▼
table.insert( result, dPos, d ~= 0 and "1" or "0" )▼
end▼
for pad = digits + 1, k do table.insert( result, dPos, "0" ) 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
▲ end
▲ while #result < k do result[ #result + 1 ] = "0" end
▲ for i = 1, q do result[ #result + 1 ] = "1" 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 )
|