playgrounds/ learn to code 2/ 3 gems, 4 switches/ problem with conditons in while loop

hello all,


I am at the beginning of learning swift with the ipad playgrounds.


in the chapter, where you have to go through a labyrinth till you collected 3 gems and toggled 4 switches, I have the following problem.


ar numberGem = 0
var numberSwitch = 0

}

func direction() {
    if isBlocked && isBlockedLeft {
        turnRight()
    } else if isBlocked && isBlockedRight {
        turnLeft()
    }
}
func gemSwitchVar() {
    if isOnGem {
        collectGem()
        numberGem += 1
    } else if isOnClosedSwitch {
        toggleSwitch()
        numberSwitch += 1
    }
}
while numberGem < 4 && numberSwitch < 5 {
    gemSwitchVar()
    direction()
    moveForward()
}


the while loop always stops after the figure collected 3 gems. It does not continue till it also toggled 4 switches. I always thought that with AND both conditions had to be fullfilled. And the OR operator would display the behaviour it does now.


I had the same problem with a while loop in an earlier chapter where I tried a while loop like


while !isBlocked && !isBlockLeft && !isBlockedRight


to make my figure walk till the end of the course, which was blocked in the upper way.


Where is my thought error.

Replies

Do you necessarily need to set both the number of gems && number of switches as a condition for continuing? IIRC, you collect all of the gems before you toggle all of the switches, so you can have you line 22 as:


while numberSwitch < 5 {


as the number of gems collected is irrelevant - you have to keep going until all switches have been toggled.


(If I got it the wrong way round, and the last item to collect is a gem, not a switch, simply set line 22 as 'while numberGem < 4 }'

guys this the the answer for this question:

var gemCounter = 0

var switchCounter = 0

func direction() {

    if isBlocked && isBlockedLeft {

        turnRight()

    } else if isBlocked && isBlockedRight {

        turnLeft()

    }

}

func gemVar() {

    if isOnGem {

        collectGem()

        gemCounter += 1

    }

func switchVar() {

    if isOnClosedSwitch {

    toggleSwitch()

        switchCounter += 1

}

}

while !isBlocked || !isBlockedLeft ||  !isBlockedRight && switchCounter != 4{

    moveForward()  

    direction()

    if gemCounter < 3 {

        gemVar()

    } else if switchCounter < 4{

        switchVar()

    }

}