Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find at least one element that exists in all three lists in OCaml

We have three lists which contain people's names.

All three lists have been sorted alphabetically.

Now we need to find at least one name which appear in all three lists.


The algorithm I am thinking is like this:

I get three heads out of three lists.

if the three heads are not equal to each other, then I keep the max one and get two new heads from the lists from which I just dropped the heads.

Continue above procedure until I find such an element as described in the beginning.

Is this algorithm correct?


The problem is that I am not sure how to use ocaml to write the function.

like image 240
Jackson Tale Avatar asked Dec 26 '22 11:12

Jackson Tale


2 Answers

Here is an OCaml function that does the intersection of two sorted list using your algorithm (which is indeed the good way to solve this problem).

let rec intersect l1 l2 = match l1, l2 with
| [], _ | _, [] -> []
| h1 :: t1, h2 :: t2 ->
  if h1 < h2 then intersect t1 l2
  else if h1 = h2 then h1 :: (intersect t1 t2)
  else intersect l1 t2
like image 149
Thomash Avatar answered May 24 '23 21:05

Thomash


Thomash's algorithm will do the job with two calls of intersect and creating intermediate lists so it isn't very efficient.

Your algorithm is essentially correct. An extra bit is that sometimes you have two heads are equal to max and you should drop only the remaining head.

Here is the revised algorithm written in OCaml:

let rec intersect xs ys zs =
    match xs, ys, zs with
    | [], _, _ | _, [], _ | _, _, [] -> None
    | x::xs', y::ys', z::zs' -> 
       if x = y && y = z then Some x
       else 
           let m = max x (max y z) in
           if x = m && y = m then intersect xs ys zs'
           else if x = m && z = m then intersect xs ys' zs
           else if y = m && z = m then intersect xs' ys zs
           else if x = m then intersect xs ys' zs'
           else if y = m then intersect xs' ys zs'
           else intersect xs' ys' zs
like image 43
pad Avatar answered May 24 '23 21:05

pad