Calendar Conflicts

Problem

Given lists of events and their calendar, find all conflicted events source on YouTube

Php solution

This is solution from original youtube post
需要说明的是原题目里把continuous conflicted events放在一个组,这也是为什么下面有$temp = array()来flush temp array.

<?php  
$cal = [[1,2,'a'],
        [3,5,'b'], 
        [4,6,'c'],
        [7,10,'d'],
        [8,11,'e'], 
        [10,12,'f'],
        [13,14,'g']];
function findConflicts($cal) {  
    $conflicts = array();
    $temp = array($cal[0][2]);
    $end = $cal[0][1];
    for ( $ii = 1; $ii< count($cal); $ii++) {
        if ($cal[$ii][0] >= $end) {
            if(count($temp) > 1) {
                $conflicts[] = $temp;
            }
            $temp = array();
        }
        $end = max($cal[$ii][1], $end);
        $temp[] = $cal[$ii][2];
    }
    if (count($temp) > 1) {
        $conflicts[] = $temp;
    }
    return $conflicts;
}
$result = findConflicts($cal);
print_r($result);  
?>

三个点需要注意的: 1. php里向array里添加新元素有两种方式,上面用的是第二种。

$arr = array();
// 第一种
array_push($arr, 'test');  
// 第二种
$arr[] = 'test';
  1. temp array是用来存运行过程中的结果, 初始值设为了index 0 的值,所以后面for loop 从index 1 起。
  2. 最后的case是因为如果for loop run完如果最后一个item有conflict, 则需要收尾把需要的结果添加到conflicts里

Swift solution

这里是用swift写的solution,用了tuple来表示每个事件, index 0,1,2分别代表start,end time和event name.

let cal: [(Int,Int,String)] = [(1,2,"a"),  
                               (3,5,"b"),
                               (4,6,"c"),
                               (7,10,"d"),
                               (8,11,"e"),
                               (10,12,"f"),
                               (13,14,"g")]
func findConflicts(cal: [(Int,Int,String)]) -> [[String]] {  
    var conflicts = [[String]]()
    var temp = [String]()
    temp.append(cal[0].2)
    var end = cal[0].1

    for event in cal.dropFirst() {
        print(end)
        if event.0 >= end {
            if temp.count > 1 {
                conflicts.append(temp)
            }
            print(conflicts)
            temp.removeAll()
        }
        end = max(end, event.1)
        temp.append(event.2)
    }

    if temp.count > 1 {
        conflicts.append(temp)
    }
    return conflicts
}
let result = findConflicts(cal: cal)  
print(result)