Gray code: Difference between revisions

Content deleted Content added
Markjreed (talk | contribs)
Markjreed (talk | contribs)
→‎{{header|Erlang}}: Adopt decode algorithm from Euphoria.
Line 552:
 
=={{header|Erlang}}==
{{trans|TclEuphoria}}
<lang erlang>-module(gray).
-export([encode/1, decode/1]).
-import(math, [log/1]).
 
ceil(X) ->
T = erlang:trunc(X),
case (X - T) of
Neg when Neg < 0 -> T;
Pos when Pos > 0 -> T + 1;
_ -> T
end.
 
encode(N) -> N bxor (N bsr 1).
 
decode(0N) -> decode(N,0;).
decode(G) -> I = 1 bsl ceil(log(G)/log(2)),
decode(G, I, G band I).
 
decode(G,I,B) -> decode(G,I,B,B).
 
decode(_,0,B,_) -> B;
 
decode(0,G,I,B,P) -> NP = (G band I) bxor (P bsr 1),;
decode(N,G,) I-> bsr 1decode(trunc(N/2), BG borbxor NP, NPN).</lang>
</lang>
 
Demonstration code: