Skip to content

Instantly share code, notes, and snippets.

@phongphan
Created August 11, 2017 06:41
Show Gist options
  • Save phongphan/c8e92c36303e8541e8e38205c3f7f25d to your computer and use it in GitHub Desktop.
Save phongphan/c8e92c36303e8541e8e38205c3f7f25d to your computer and use it in GitHub Desktop.
OCaml version
(*
* ocamlfind ocamlc -package containers -linkpkg rangemerge.ml
*)
open Containers
open Printf
let normalize_range ranges =
List.sort (fun x y -> compare (fst x) (fst y)) ranges
|> List.fold_left (fun acc x ->
let src = List.hd acc in
if fst x >= fst src && fst x <= snd src then
(fst src, max (snd src) (snd x)) :: List.tl acc
else x::acc) [List.hd ranges]
|> List.rev
let parse_range line =
String.split "," line
|> List.map (fun arange ->
let pair = List.map (fun s -> String.trim s) (String.split "-" arange) in
if List.length pair = 1 then
let value = int_of_string (List.hd pair) in (value, value)
else
(int_of_string (List.hd pair), int_of_string (List.nth pair 1))
)
let format_range ranges =
let result = List.map (fun x ->
if fst x = snd x then (sprintf "%d" (fst x)) else (sprintf "%d-%d" (fst x) (snd x))) ranges in
String.concat "," result
let read_in () =
printf ">> ";
Scanf.scanf "%s\n" (fun line -> line)
let main() =
read_in()
|> parse_range
|> normalize_range
|> format_range
|> printf "%s\n"
;;
if !Sys.interactive then () else main ();;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment