第七章|算法
-
- 1. 右手定则
- 2. 调整算法
- 3. 征服迷宫
- 4. 左转还是右转?
- 5. 向左走,向右走
1. 右手定则
func navigateAroundWall() {
if isBlockedRight {
moveForward()
} else {
turnRight()
moveForward()
}
}
func turnAround(){
turnLeft()
turnLeft()
}
while !isOnClosedSwitch{
navigateAroundWall()
if isOnGem{
collectGem()
turnAround()
}
}
toggleSwitch()
2. 调整算法
func navigateAroundWall() {
if isBlockedRight && !isBlocked {
moveForward()
} else if !isBlockedRight {
turnRight()
moveForward()
} else if isBlocked {
turnLeft()
}
}
func turnAround(){
//转身
turnLeft()
turnLeft()
}
while !isOnClosedSwitch {
navigateAroundWall()
if isOnGem {
collectGem()
turnAround()
}
}
toggleSwitch()
3. 征服迷宫
func wonderWay() {
if isBlockedRight {
while isBlocked {
turnLeft()
}
} else {
turnRight()
}
moveForward()
}
while !isOnGem {
wonderWay()
}
collectGem()
4. 左转还是右转?
func button() {
while isOnClosedSwitch {
if !isBlocked {
toggleSwitch()
turnRight()
} else {
toggleSwitch()
turnLeft()
}
}
}
while !isOnGem {
moveForward()
button()
}
collectGem()
5. 向左走,向右走
func runWay() {
if isBlocked && isBlockedLeft {
turnRight()
} else if isBlocked && isBlockedRight {
turnLeft()
}
}
func gemSwitch() {
if isOnGem {
collectGem()
} else if isOnClosedSwitch {
toggleSwitch()
}
}
func frontBlock() {
if isBlocked {
turnLeft()
}
}
while !isBlocked || !isBlockedLeft || !isBlockedRight {
moveForward()
gemSwitch()
runWay()
frontBlock()
}