Puzzle with function and loop in swift playground

Hello,

I’m learning Swift grammar with Apple’s “Swift Playgrounds” and I’ve just learned about function, if in loop and while one, etc.

In combining those acquisition, I have to solve the puzzle as below :

And here is my solution :

while !isBlocked {
    moveForward()
    if isOnClosedSwitch {
        toggleSwitch()
    } 
}

if isBlocked {
    turnRight()
    moveForward()
    turnRight()
} 

while !isBlocked {
    moveForward()
    if isOnGem {
        collectGem()
    } 
}

if isBlocked {
    turnLeft()
    moveForward()
    turnLeft()
} 

while !isBlocked {
    moveForward()
    if isOnClosedSwitch {
        toggleSwitch()
    } 
} 

Can anyone knows whether there is more simple and short solution than mine ? Thank you for your attention!

Hello @gopre

I think you have a good solution.
The point is to learn Swift coding by doing. :slightly_smiling_face:
Trying to find a minimal solution is good, but can come later. :slight_smile:
Many of the puzzles have only one obvious solution, as I remember.?.

Sincerely

Hey,

Thank you for your encouragement!

Have a nice day. :slight_smile:

You don’t have. to. use !isBlocked multiple times

if isBlocked && isBlockedLeft {
turnRight()
moveForward()

else if isBlocked {
turnLeft()

Your answer works, and as long as ur code solves the problem ur job is done.

But at the same time looking for an easier and more efficient solution is also useful.

what you could have done is first put a while block which will move forward as long as it is not blocked front .

then put 2 if blocks inside the while block which check for switches or gems and acts accordingly.

then put another if block which turns around left or right with regards to how its blocked.

something like this

Blockquote
while !isblocked{
moveForward()
if isOnGem {
collectGem()
}
if isOnClosedSwitch {
toggleSwitch()
}
if isBlocked && isBlockedRight {
turnLeft()
}
}

Hope This Helps