(*Assumindo a solução do ponto anterior *)
open List

let add_one st = "1"^st
let add_zero st = "0"^st

let rec gray_aux n acc = 
if n <= 0 then acc
else  gray_aux (n-1) ((map add_zero acc)@(map add_one (rev acc)))

let gray n =
  if n <0 then failwith "negative argument" else gray_aux n [""]


(* alínea 2 *)

let log2 n = int_of_float (log (float_of_int n) /. log 2.0)

let gray_code n = List.nth (gray ((log2 n)+1)) n

let () =
  let n = print_string "Give an int: ";read_int () in 
  Printf.printf "gray_code %d = %s\n" n (gray_code n)

(* Esta solução é simples, mas muito ineficiente (gera todos os
códigos de um determinado tamanho e escolhe um deles).
Existem métodos mais directos e no entanto igualmente simples, 
ver o site "wikipedia".
*)

This document was generated using caml2html