How can I check two “pointers” meet each other when going through a list?

时光总嘲笑我的痴心妄想 提交于 2019-12-25 05:32:21

问题


For example, I have a list [1; 2; 1; 3; 2; 4; 1; 5; 6; 8;...]. The list has duplicate elements.

Then we go through the list by two virtual pointers.

One pointer a goes from the beginning and has speed of 2.

The other pointer b goes from somewhere in the middle of list and has speed of 1.

So how can I check whether a meeting with b?


For example:

a starts from [1; 2; 1; 3; 2; 4; 1; 5; 6; 8;...]

b starts from index 1, which is [2; 1; 3; 2; 4; 1; 5; 6; 8;...]

So after one time move, both a and b will arrive at index 2 and they meet.

How can I check whether meet or not by the element only, without info of index?

We can just compare the value of the two elements, as there might be duplicates inside.


In term of code:

let l = [1; 2; 1; 3; 2; 4; 1; 5; 6; 8;...]

let find_middle_start l n = 
  let rec aux i = function
    | [] -> []
    | _::tl when i >= n -> tl
    | _::tl -> aux (i+1) tl
  in
  aux 0 l

let parallel_travel l =
  Random.self_init();
  let b_start = find_middle_start l (Random.int (List.length l)) in
  let rec go = function
    | [], _::_ | _::_, [] | _::[], _::_ -> print_endline "Never meet"
    | x::x1::xs, y::ys ->
      if check_meet x y then print_endline "Meet"
      else go xs ys
  in
  go l b_start

How can I implement check_meet? i can't just do x == y right?


回答1:


Bind the lists, and compare them by identity (with ==).

| ((_::_::xs) as a)), ((_::ys) as b) ->
  if a == b then ...
  else ...

Note that if you are trying to determine whether a list shares a tail with another list, this method is not sufficient (the slow pointer can reach the end before the fast pointer catches up with it).



来源:https://stackoverflow.com/questions/29121354/how-can-i-check-two-pointers-meet-each-other-when-going-through-a-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!