Another solution for easy understanding, hope it helps.
var gemCounter = 0
var switchCounter = 0
while gemCounter >= switchCounter {
moveForward()
if isBlocked && isBlockedLeft {
turnRight()
}
while isOnGem {
collectGem()
gemCounter += 1
}
while isOnClosedSwitch && switchCounter != gemCounter {
toggleSwitch()
switchCounter += 1
if switchCounter == gemCounter {
switchCounter += 1
}
}
}
Selecting any option will automatically load the page