Swiftで書く「問題解決のPythonプログラミング」P.16,17

Swiftで書く「問題解決のPythonプログラミング」P.16,17

Playgroundで実施出来ます。

import Cocoa

var sched = [(6, 8), (6, 12), (6, 7), (7, 8),
             (7, 10), (8, 9), (8, 10), (9, 12),
             (9, 10), (10, 11), (10, 12), (11, 12)]

func bestTimeToParty(schedule:[(Int, Int)]) {
    var start = schedule[0].0
    var end = schedule[0].1
    for c in schedule {
        start = min(c.0, start)
        end = max(c.1, end)
    }
    var count = celebrityDensity(sched: schedule, start: start, end: end)
    var maxcount = 0
    var time = 0
    for i in start...end {
        if count[i] > maxcount {
            maxcount = count[i]
            time = i
        }
    }
    print("Best time to attend the party is at \(time) o'clock : \(maxcount) celebrities will be attending!")
}

func celebrityDensity(sched:[(Int, Int)], start:Int, end:Int) -> [Int] {
    var count = [Int](repeating: 0, count: end + 1)
    for i in start...end {
        for c in sched {
            if (c.0 <= i) && (c.1 > i) {
                count[i] = count[i] + 1
            }
        }
    }
    return count
}

bestTimeToParty(schedule: sched)


問題解決のPythonプログラミング ―数学パズルで鍛えるアルゴリズム的思考

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です