How to find matching time intervals for more than 2 users

后端 未结 5 1682
自闭症患者
自闭症患者 2021-02-10 06:42

Find best suitable time from given time interval of different users.

Rows: 5
fid  userid  FromDateTime           ToDateTime          flag
62   1   2012-07-18 01:         


        
5条回答
  •  自闭症患者
    2021-02-10 07:27

    I created a 1D line-segment intersection algorithm in PHP utilizing a sweep line (Wikipedia). It works because datetimes can be mapped to a number-line: for example using "milliseconds since epoch".

    See the implementation here: http://pastebin.com/iLwJQEF0

    The algorithm outputs an array of line-segment intersections (which are also line-segments) that also have a list of all the users available for the duration. You can sort the intersections by your definition of "best" (and reverse it for descending): first by the number of available users and then by their durations. (Already implemented!)

    It runs in O(n * log n), where n is the number of time-periods.

    Notes:

    • If you don't want to mess around with datetime-to-millisecond conversions, you can replace the subtract and greater-than/less-than operators. (I left some comments for you.)
    • It is important to watch out for line-segments that start/end at the same place:
      • The sweep-line must encounter end-points before start-points of the same value.
      • Also notice that it won't create extraneous results when two line-segments end at the same value.
    • I'm sure this can be re-implemented inside a database engine (if you think it's worth it). A number of database vendors have geometric extensions.

提交回复
热议问题