System Design Practice – 1

題目:

有3種Routine:
(1)每個Routine有相同的屬性,但也有各別不同的屬性
(2)每個Routine可設定重複的次數
(3)一個Routine內可包含多個SubRoutine
(4) 給定某個Routine,求該Routine的depth

class AbstractRoutine {
    var repeatTime: Int
    var routineArr: [AbstractRoutine]
    init(_ repeatTime: Int, _ routineArr: [AbstractRoutine]) {
        self.repeatTime = repeatTime
        self.routineArr = routineArr
    }
    
    convenience init() {
        self.init(0, [])
    }
    
    func getDepth() -> Int {
        return getDepthHelper(self)
    }

    private func getDepthHelper(_ routine: AbstractRoutine) -> Int {
        let arr = routine.routineArr
        if arr.count == 0 {
            return 1
        } else {
            var max = 0
            for item in arr{
                let depth = getDepthHelper(item)
                if depth > max { max = depth }
            }
            return max + 1
        }
    }
}

class Routine1: AbstractRoutine {}

class Routine2: AbstractRoutine {}

class Routine3: AbstractRoutine {}

var routineArray: [AbstractRoutine] = []
let routineA = Routine1()
let routineB = Routine1()
let routineC = Routine2()
let routineD = Routine3()
let routineE = Routine3()
routineB.routineArr = [routineC, routineD]
routineC.routineArr = [routineE]
routineArray = [routineA, routineB]

// Check getDepth correctness
// Test case:
// routine
// routine -> [routine1]
// routine -> [routine1 -> [routine3], routine2]
assert(routineA.getDepth() == 1, "Error 1")
assert(routineC.getDepth() == 2, "Error 2")
assert(routineB.getDepth() == 3, "Error 3")
%d 位部落客按了讚: