Jump to content

Rice coding: Difference between revisions

Realize in F#
m (→‎{{header|Wren}}: Added colon.)
(Realize in F#)
Line 6:
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.
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
// Rice coding. Nigel Galloway: September 21st., 2023
let rec fN g=[match g with 0->() |_->yield 1; yield! fN(g-1)]
let fI n=let rec fI n g=match List.head g with 1->fI (n+1) (List.tail g) |_->(n,List.foldBack(fun i (n,g)->(n*2,g+n*i)) (List.tail g) (1,0)|>snd) in fI 0 n
let rec fG n g=[match n with 1->yield g%2 |_->yield g%2; yield! fG (n-1) (g/2)]
let encode n g=let q=g/pown 2 n in [yield! fN q; yield 0; yield! fG n g|>List.rev]
let decode n g=let a,b=fI g in a*pown 2 n+b
let test=let test=encode 4 in [for n in 0..17 do yield test n] //encode 0 to 17
test|>List.iter(fun n->n|>List.iter(printf "%d"); printf " -> "; printfn "%d" (decode 4 n)) //print the encoded values and the decoded values
</syntaxhighlight>
{{out}}
<pre>
00000 -> 0
00001 -> 1
00010 -> 2
00011 -> 3
00100 -> 4
00101 -> 5
00110 -> 6
00111 -> 7
01000 -> 8
01001 -> 9
01010 -> 10
01011 -> 11
01100 -> 12
01101 -> 13
01110 -> 14
01111 -> 15
100000 -> 16
100001 -> 17
</pre>
=={{header|Julia}}==
<syntaxhighlight lang="julia">""" Golomb-Rice encoding of a positive number to bit vector using M of 2^k"""
Line 74 ⟶ 106:
10 -> 111110000 -> 10
</pre>
 
 
=={{header|raku}}==
2,172

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.