Swift playground, Land of Bounty solution

Hi, I’m a swift beginner and started to learn Swift with Swift playground. I can’t solve Land of Bounty using while loop. What I wrote works well until the Byte gets at the beginning of the third row in front of the first switch and then it gets stuck, I can’t figure out why. Could anybody tell me what I do wrong, please?

Thanks a lot


while !isBlocked && !isBlockedRight {

moveForward ()

if isOnClosedSwitch {

toggleSwitch ()

} else if isOnGem {

collectGem

}

if isBlocked && isBlockedLeft

turnRight ()

moveForward ()

turnRight ()

}

if isBlocked {

turnLeft ()

moveForward ()

turnLeft ()

}

}

For easier understanding I enclose a link to buildingrainbows that solves that but not using while loop. https://buildingrainbows.com/land-of-bounty-swift-playgrounds/

So this was posted a year ago but i wanted to answer just in case someone else is looking at the moment of later. Heres the solution to the problem you just needed to remove the "&& !isBlockedRight" cause when you get to the 3rd row it is blocked on the right , also on your second "if" you needed to add "&& !isBlockedRight" so it doesn't get stuck on the infinite loop. So just basically change the "&& !isBlockedRight" to the second "if" and it works perfectly.

while !isBlocked {

    if isOnGem {

        collectGem()

    }else if isOnClosedSwitch {

        toggleSwitch()

    }

    moveForward()

    if isBlocked && isBlockedLeft {

        turnRight()

        moveForward()

        turnRight()

    }else if isBlocked && !isBlockedRight{

        turnLeft()

        moveForward()

        turnLeft()

    }

}

@ijcharly has already told you what is wrong, here is my take on a simple solution that can be understood easily.

Using a for loop and a while loop:

func toggleOrCollect() {
    if isOnClosedSwitch {
        toggleSwitch()
    } else if isOnGem {
        collectGem()
    } else {
        moveForward()
    }
}

for i in 1 ... 3 {
    while !isBlocked {
        toggleOrCollect()
    } 
    if i == 1 {
        turnRight()
        moveForward()
        turnRight()
    } else if i == 2 {
        turnLeft()
        moveForward()
        turnLeft()
    }
}

Using ONLY while loop:

func toggleOrCollect() {
    if isOnClosedSwitch {
        toggleSwitch()
    } else if isOnGem {
        collectGem()
    } else {
        moveForward()
    }
}

while !isBlocked {
    toggleOrCollect()
}

turnRight()
moveForward()
turnRight()

while !isBlocked {
    toggleOrCollect()
}

turnLeft()
moveForward()
turnLeft()

while !isBlocked {
    toggleOrCollect()
}
Swift playground, Land of Bounty solution
 
 
Q