Last active
November 5, 2015 11:37
-
-
Save obecker/af06c46051b59a21240f to your computer and use it in GitHub Desktop.
Solving the shortest grid path problem in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
indirect enum Route : CustomStringConvertible { | |
case End | |
case Down(Route) | |
case Left(Route) | |
var description: String { | |
switch self { | |
case .End: return "" | |
case .Down(let way): return "⬇︎\(way)" | |
case .Left(let way): return "⬅︎\(way)" | |
} | |
} | |
static func findRoutesFrom(x: Int, _ y: Int) -> [Route] { | |
switch (x, y) { | |
case _ where x < 0 || y < 0: | |
return [] | |
case (0, 0): | |
return [ .End ] | |
default: | |
return findRoutesFrom(x, y - 1).map() { .Down($0) } + findRoutesFrom(x - 1, y).map() { .Left($0) } | |
} | |
} | |
} | |
let routes = Route.findRoutesFrom(5, 3) | |
print("Found \(routes.count) routes") | |
for i in 0 ..< routes.count / 4 { | |
print(routes[i * 4 ..< (i + 1) * 4]) | |
} | |
if routes.count % 4 != 0 { | |
print(routes.suffix(routes.count % 4)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code belongs to http://www.obqo.de/blog/2015/11/04/how-many-ways-to-find-a-way/