Skip to content

Instantly share code, notes, and snippets.

@oisdk
Last active August 29, 2015 14:24
Show Gist options
  • Save oisdk/92deef5a8a0fa02e1fdb to your computer and use it in GitHub Desktop.
Save oisdk/92deef5a8a0fa02e1fdb to your computer and use it in GitHub Desktop.
struct Map {
private let matrix: [[String]]
private let locations: [String:(Int, Int)]
private let xBounds, yBounds: ClosedInterval<Int>
init(_ locs: [[String]]) {
matrix = locs
var dict: [String:(Int, Int)] = [:]
for (y, row) in locs.enumerate() {
guard row.endIndex == locs[0].endIndex else { fatalError("All rows must be equal length") }
for (x, loc) in row.enumerate() {
dict[loc] = (x, y)
}
}
locations = dict
xBounds = ClosedInterval(0, locs[0].endIndex - 1)
yBounds = ClosedInterval(0, locs.endIndex - 1)
}
func nameAt(x: Int, _ y: Int) -> String? {
return (xBounds ~= x && yBounds ~= y) ? matrix[y][x] : nil
}
subscript(loc: String) -> (Int, Int)? { return locations[loc] }
enum Direction: Int { case North = 0, East, South, West }
private func shift(dir: Direction)(_ from: (Int, Int)) -> (Int, Int) {
switch dir {
case .North: return (from.0, from.1 - 1)
case .South: return (from.0, from.1 + 1)
case .East: return (from.0 + 1, from.1)
case .West: return (from.0 - 1, from.1)
}
}
func adjacentTo(from: String)(_ dir: Direction) -> String? {
return locations[from]
.map(shift(dir))
.flatMap(nameAt)
}
func adjacentTo(from: String, dir: Direction) -> String? {return adjacentTo(from)(dir)}
func adjacentsOf(from: String) -> [String] {
return (0..<4)
.flatMap(Direction.init)
.flatMap(adjacentTo(from))
}
}
let places = Map([
["Home", "Work" , "School" ],
["Gym" , "Pub" , "Cafe" ],
["Pool", "Cinema", "Library"]
])
places.adjacentsOf("Pub")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment