algorithm - 在 OCaml 的所有三个列表中找到至少一个存在的元素

标签 algorithm functional-programming 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.


我想的算法是这样的:

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.

这个算法正确吗?


问题是我不确定如何使用ocaml来编写函数

最佳答案

这是一个 OCaml 函数,它使用您的算法对两个排序列表进行交集(这确实是解决此问题的好方法)。

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

关于algorithm - 在 OCaml 的所有三个列表中找到至少一个存在的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14385190/

相关文章:

haskell - 如果“任一个”可以是“左”或“右”,但不能同时是“左”或“右”,那么为什么在Curry-Howard对应中它对应于OR而不是XOR?

ocaml - 在 OCaml 中 sleep 不到一秒钟

algorithm - 如何修改后缀数组以搜索多个字符串?

相当于 Clojure 的 "reductions"或 python 的 itertools.accumulate 的 Javascript

javascript - 在 postgresql 数据库中存储 semver 版本字符串以进行范围查询

.net - 在签名文件中共享受歧视的联合

haskell - 保存我正在运行的顶层以供以后使用

ocaml - OCaml 中异步调用函数

c++ - 排序相关算法(用排序集合中的索引替换每个项目)

performance - 算法复杂度分析 : practically using Knuth's Ordinary Operations (oops) and Memory Operations (mems) method