Skip to content

Instantly share code, notes, and snippets.

@mikaelbr
Created December 12, 2016 21:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikaelbr/a668bea03a8b2df145b9e843dc923993 to your computer and use it in GitHub Desktop.
Save mikaelbr/a668bea03a8b2df145b9e843dc923993 to your computer and use it in GitHub Desktop.
#load "str.cma";;
let message = "Your message was received with gratitude! We do not know about you, but Christmas is definitely our favourite holiday. The tree, the lights, all the presents to unwrap. Could there be anything more magical than that?! We wish you a happy holiday and a happy new year!";;
let roman_to_digit num =
match num with
| 0 -> "0"
| 1 -> "I"
| 2 -> "II"
| 3 -> "III"
| 4 -> "IV"
| 5 -> "V"
| 6 -> "VI"
| 7 -> "VII"
| 8 -> "VIII"
| 9 -> "IX"
| 10 -> "X"
| 11 -> "XI"
| 12 -> "XII"
| 13 -> "XIII"
| _ -> "_";;
let compose f g x = f (g x);;
let remove_nonalpha = (Str.global_replace (Str.regexp "[^a-zA-Z]+") "");;
let normalize = compose String.lowercase_ascii remove_nonalpha;;
let split_to_pair x =
let num = (int_of_char x) - 96 in
let n = num / 2 in
if num mod 2 == 0 then (n,n) else (n+1,n);;
let rec string_to_list = function
"" -> []
| s -> (String.get s 0) ::
string_to_list (String.sub s 1 ((String.length s) - 1));;
let split_list =
let rec split_msg (a, b) = function
[] -> (a, b)
| (n1, n2)::tl -> split_msg (a@[n1], b@[n2]) tl in
split_msg ([], []);;
let flatten_message_list (a, b) =
List.append a (List.rev b);;
let encode msg =
normalize msg
|> string_to_list
|> List.map split_to_pair
|> split_list
|> flatten_message_list
|> List.map roman_to_digit;;
encode message
|> String.concat ", "
|> print_string;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment