2

这是什么是分组计划的后续问题,以便每两个人只分组一次?

基本上,我实现了循环算法


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

例如,我们有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)

遵循算法,代码非常简单。有更好的实现吗?

4

3 回答 3

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)|]|]
*)
于 2013-12-03T13:58:37.907 回答
1

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

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

于 2013-12-03T10:10:08.183 回答
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
于 2014-01-13T12:17:24.780 回答