About Nesting Swift Playground While Statements

Asked 2 years ago, Updated 2 years ago, 49 views

I've been learning from swift playgrounds several times.
I typed the cord as shown in the picture, and it went smoothly to the red jewel, but it didn't stop at the jewel square, so I just passed by.
Is the nesting of while sentences not good?
When !isOngem is released (when you come to the jewel mass), I would like you to remove the while statement from the outer frame and collectGem, but I will walk straight.
I would appreciate it if you could let me know.
Thank you.Enter a description of the image here

Here are the pre-resolved codes:

func move(){
    toggleSwitch()
    if isBlocked {
        turnLeft()
    } else if!isBlockedRight{
        turnRight()
    }
}
while!isOnGem{
    while!isOnClosedSwitch{
        moveForward()       
    }
    move()    
}
collectGem()

swift algorithm

2022-09-30 18:29

2 Answers

Based on the advice Nekketsuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
Thank you!

func move(){
    moveForward()
    if isOnClosedSwitch {
        toggleSwitch()
    }
    if isBlocked {
        turnLeft()
    }
    if!isBlockedRight{
        turnRight()
    }
}

while!isOnGem{
    move()
}
collectGem()


2022-09-30 18:29

Tip: !isOnClosedSwitch is stuck in the inner while loop until it is satisfied and is not checked for isOnGem.


2022-09-30 18:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.