August 23, 2024

P49 - Gray code.

An n-bit Gray code is a sequence of n-bit strings constructed according to certain rules. For example,n = 1: C(1) = ("0", "1").n = 2: C(2) = ("00", "01", "11", "10").n = 3: C(3) = ("000", "001", "011", "010", "110", "111", "101", "100").

Find out the construction rules and write a function to generate Gray codes.

> p49:gray(3).
    ["000","001","010","011","100","101","110","111"]

See if you can use memoization to make the function more efficient.

erlang

%Gray code.
-module(p49).
-export([gray/1]).

gray(1) ->
    ["0", "1"];

gray(A) ->
    [[X] ++ B || X <- "01" , B <- gray(A - 1)].
    
Be first to comment
Leave a reply