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()
}

 
11
Kudos
 
11
Kudos

Now read this

“Everything I know about business in one minute.”

by William Drenttel Focusing on making a partnership work is more profitable than focusing on making money. Love your employees more than you love your clients.  The best new business is your current business. Price projects by... Continue →