OCaml中的循环算法

时间:2013-12-02 15:46:27

标签: algorithm ocaml round-robin

这是What's the grouping plan so that every two people are grouped together just once?

的后续问题

基本上,我实施了Round robin algorithm


通过该算法,它可以生成成对列表,其中每个可能的元素对恰好组合在一起。

例如,我们有a, b, c, d,然后是

第一天,我们

a b
c d

然后我们分组如[(a,c);(b,d)]。

然后我们将它顺时针旋转

a c
d b

然后我们分组如[(a,d);(c,b)]。

然后我们将它顺时针旋转

a d
b c

然后我们分组如[(a,b);(d,c)]。

(注意,a始终是固定的。)

最后我可以

[(A,C);(B,d)]
[(A,d);(C,B)]
[(A,B);(d,C)]


以下是ocaml代码:

let split = List.fold_left (fun (l1, l2) x -> (l2, x::l1)) ([], []) 

let round l1 l2 =
  match List.rev l1, l2 with
    | _, [] | [], _ -> raise Cant_round
    | hd1::tl1, hd2::tl2 ->
      hd2::(List.rev tl1), List.rev (hd1::List.rev tl2)

let rec robin fixed stopper acc = function
  | _, [] | [], _ -> raise Cant_robin
  | l1, (hd2::tl2 as l2) -> 
    if hd2 = stopper then acc
    else robin fixed stopper ((List.combine (fixed::l1) l2)::acc) (round l1 l2)

let round_robin = function
  | [] | _::[] -> raise Cant_round_robin
  | hd::tl ->
    let l1, l2 =  in
    match split tl with 
      | _, [] -> raise Cant_round_robin
      | l1, (hd2::_ as l2) -> 
    robin hd hd2 ((List.combine (hd::l1) l2)::[]) (round l1 l2)

遵循该算法,代码非常简单。 是否有更好的实施?

3 个答案:

答案 0 :(得分:1)

您不需要通过操作实际数据来计算顺时针旋转。您可以将其表示为固定数组中的拾取索引(旋转的内容):在旋转数组t r次之后,旋转数组中索引i处的元素将位于原始数组中的索引i+r,实际上(i+r) mod (Array.length t)包含环绕。

有了这个想法,您可以在不移动数据的情况下计算配对,只需递增一个表示到目前为止执行的旋转次数的计数器。事实上,你甚至可能想出一个纯粹的数值解决方案,它不会创建任何数据结构(旋转事物的数组),以及应用这种推理的各种索引的原因。

答案 1 :(得分:1)

let round_robin ~nplayers ~round i =
  (* only works for an even number of players *)
  assert (nplayers mod 2 = 0);
  assert (0 <= round && round < nplayers - 1);
  (* i is the position of a match,
     at each round there are nplayers/2 matches *)
  assert (0 <= i && i < nplayers / 2);
  let last = nplayers - 1 in
  let player pos =
    if pos = last then last
    else (pos + round) mod last
  in
  (player i, player (last - i))

let all_matches nplayers =
  Array.init (nplayers - 1) (fun round ->
    Array.init (nplayers / 2) (fun i ->
      round_robin ~nplayers ~round i))

let _ = all_matches 6;;
(**
[|[|(0, 5); (1, 4); (2, 3)|];
  [|(1, 5); (2, 0); (3, 4)|];
  [|(2, 5); (3, 1); (4, 0)|];
  [|(3, 5); (4, 2); (0, 1)|];
  [|(4, 5); (0, 3); (1, 2)|]|]
*)

答案 2 :(得分:0)

虽然这个问题已得到解答,但正确答案是必要的。

我终于找到了以下处理循环算法的方法,功能更简单。

let round l1 l2 = let move = List.hd l2 in move::l1, (List.tl l2)@[move]

let combine m l1 l2 =
  let rec comb i acc = function
    |[], _ | _, [] -> acc
    |_ when i >= m -> acc
    |hd1::tl1, hd2::tl2 -> comb (i+1) ((hd1,hd2)::acc) (tl1,tl2)
  in
  comb 0 [] (l1,l2)

let round_robin l =
  let fix = List.hd l in
  let half = (List.length l)/2 in
  List.fold_left (
      fun (acc, (l1, l2)) _ -> (combine half (fix::l1) l2)::acc, round l1 l2
    ) ([], (List.tl l, List.rev l)) l |> fst |> List.tl