Swift — Random Gems Everywhere

This was a harsh level that took me forever to solve. I eked out a decent solution in 41 lines of code, but I knew it could be done better.

I sought out other solutions to appreciate different perspectives. One came in at 25% less lines of code, but the solution by Takemichi Shibuya was humbling with less than HALF my total lines of code. (Phew!) Impressive.

Takemichi taught me how complicated my mindset was, and that a truly simple solution was there if I removed some assumptions I created.

Objective: Turn each portal on and off as needed to get all gems.
5BA60680-BDD4-4D4D-98FD-DA529A00A025.png

My solution

let totalGems = randomNumberOfGems
var gemCount = 0
var stepCount = 0
func turnAround() {
turnLeft()
turnLeft()
moveForward()
}
func getGem() {
collectGem()
gemCount += 1
}
func stepForward() {
moveForward()
stepCount += 1
}
while gemCount <= totalGems {
stepForward()
getGem()
if stepCount == 1 {
pinkPortal.isActive = false
bluePortal.isActive = false
}
if stepCount == 6 {
pinkPortal.isActive = true
}
if stepCount == 9 {
pinkPortal.isActive = false
}
if stepCount == 21 {
bluePortal.isActive = true
moveForward()
bluePortal.isActive = false
}
if isBlocked {
turnAround()
}
if isBlockedLeft && !isBlockedRight {
turnRight()
}
}

Takemichi’s solution

let totalGems = randomNumberOfGems
var gemCount = 0
func checkTile() {
moveForward()
if isOnGem {
collectGem()
gemCount += 1
}
if isBlocked {
turnLeft()
turnLeft()
bluePortal.isActive = !bluePortal.isActive
pinkPortal.isActive = !pinkPortal.isActive
}
}
while gemCount < totalGems {
checkTile()
}

 
14
Kudos
 
14
Kudos

Now read this

Swift — Crank Up and Down

Objective: Initialize two monsters, then have one collect all gems with the other moving platforms up and down as needed. My assumption was to start with top left gems and then move down to lower level before finishing with far right top... Continue →