Skip to content

Instantly share code, notes, and snippets.

@argent-smith
Created May 2, 2020 17:16
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 argent-smith/56b2ca739c42ebc83a13e2a3c9f60f9f to your computer and use it in GitHub Desktop.
Save argent-smith/56b2ca739c42ebc83a13e2a3c9f60f9f to your computer and use it in GitHub Desktop.
Maximally functionalized imperative algo
exception Enough
let n_ints_from_stdin ~n =
let reader count =
try
if count = n then raise Enough else Some(read_int ())
with
| Enough -> None
| err -> raise err
in
Stream.from reader
let loop ~n f =
List.init n (fun _ -> ())
|> List.to_seq
|> Seq.iter f
let pair_of_n_ints ~n ~ints ~factor =
let r = Array.make factor 0
and left = ref 0
and right = ref 0 in
let process () =
let a = Stream.next ints in
let p = a mod factor in
let mod_diff_index = (factor - p) mod factor in
if r.(mod_diff_index) > a && r.(mod_diff_index) > (!left + !right)
then (left := r.(mod_diff_index); right := a);
if a > r.(p) then r.(p) <- a
in
loop ~n process;
(!left, !right)
let () =
let n = read_int () in
let ints = n_ints_from_stdin ~n
and factor = 120 in
let (a, b) = pair_of_n_ints ~n ~ints ~factor in
Printf.printf "(%i, %i)\n" a b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment