21 October 2020

Learn to Code 1 - เฉลยแบบฝึกหัด Roll Right, Roll Left

เฉลยแบบฝึกหัด Learn to Code 1

บทที่ 7 Algorithms

แบบฝึกหัด Roll Right, Roll Left


โจทย์ Implement the most efficient algorithm to collect the gems and activate the switches.

คำแปล จงสร้างอัลกอริทึมที่มีประสิทธิภาพที่สุดเพื่อเก็บอัญมณีและเปิดสวิตช์





เฉลย 

var gemCounter = 0

var swCounter = 1


func moveIfBlocked() {

    if !isBlocked {

        moveForward()

    } else if !isBlockedRight {

        turnRight()

        moveForward()

    } else if isBlockedRight {

        turnLeft()

    }

}


func getAndCount() {

    if isOnClosedSwitch {

        toggleSwitch()

        swCounter += 1

    } else if isOnGem {

        collectGem()

        gemCounter += 1

    }

}


while gemCounter != 8 {

    while swCounter != 7 {

        moveIfBlocked()

        getAndCount()

    }

    moveIfBlocked()

    getAndCount()

}




ขอบคุณภาพจาก Swift Playgrounds

-- ดีบี --