Skip to content

Instantly share code, notes, and snippets.

@khzaw
Created February 2, 2015 14:30
Show Gist options
  • Save khzaw/b4c535c67879a02a2db0 to your computer and use it in GitHub Desktop.
Save khzaw/b4c535c67879a02a2db0 to your computer and use it in GitHub Desktop.
To get a historgram
let most_frequent_elt list =
let rec loop maxelt maxcount elt count = function
| [] -> if count > maxcount then elt else maxelt
| x::xs ->
if elt = x then loop maxelt maxcount elt (count + 1) xs
else if count > maxcount then loop elt count x 1 xs
else loop maxelt maxcount x 1 xs in
match List.sort compare list with
| [] -> None
| x::xs -> Some (loop x 0 x 1 xs);;
let pfactorsM (n:int) : (int * int) list =
let incrementCounter counters prime = match (List.exists (function
| x, y when x = prime -> true
| _ -> false
) counters) with
| true -> List.map (function
| x, y when x = prime -> (x, y+1)
| x, y -> (x, y)
) counters
| false -> (prime, 1)::counters
in List.rev (List.fold_left incrementCounter [] (pfactors n))
;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment