February 20, 2013

Coding challenge: Maman les petits avions

So Olivier Croisier created a little challenge on his website via this blog post “Coding challenge: Maman les petits avions

This is my answer in OCaml to this challenge:

(*
See: http://thecodersbreakfast.net/index.php?post/2013/02/18/Coding-challenge-maman-les-petits-avions
---
compile & run:
$ ocamlfind ocamlc -package batteries -linkpkg avions.ml -o avions
$ ./avions
*)
open Batteries;;

(* The syracuse suite *)
let syracuse n =
    let rec urs n l = match n with
        | 1 -> l
        | n when n mod 2 = 0 -> urs (n/2) ((n/2)::l)
        | n -> urs (3*n+1) ((3*n+1)::l)
    in List.rev ((urs n []) @ [n]);;

(* Compute the statistics for a given name *)
let stats name =
    let chars = List.map Char.code (String.to_list name) in (* get characters code *)
    let n = List.fold_left (+) 0 chars in (* sum codes *)
    let l = syracuse n in (* compute syracuse suite *)
    let values = [|List.length l; List.length (List.take_while ((<=) n) l); List.max l|] in (* stats *)
    Printf.printf "Prototype: %s\n" name;
    Printf.printf "Temps de vol total: %d\n" values.(0);
    Printf.printf "Temps de vol en altitude: %d\n" values.(1);
    Printf.printf "Altitude max: %d\n" values.(2)
;;

stats "FauconMillenium";;
stats "Enterprise";;
stats "R2D2";;
stats "Delorean";;

(* Output:
---
Prototype: FauconMillenium
Temps de vol total: 123
Temps de vol en altitude: 1
Altitude max: 9232
Prototype: Enterprise
Temps de vol total: 81
Temps de vol en altitude: 3
Altitude max: 9232
Prototype: R2D2
Temps de vol total: 110
Temps de vol en altitude: 1
Altitude max: 9232
Prototype: Delorean
Temps de vol total: 29
Temps de vol en altitude: 1
Altitude max: 1216
*)

https://gist.github.com/agrison/4994484

Cheers!

Alexandre Grison - //grison.me - @algrison