Skip to content

Instantly share code, notes, and snippets.

@rayfix
Created February 24, 2019 03:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rayfix/f44a335c4f87f22f10044438c7b4bfa2 to your computer and use it in GitHub Desktop.
Save rayfix/f44a335c4f87f22f10044438c7b4bfa2 to your computer and use it in GitHub Desktop.
enum Direction {
case north, east, south, west
var left: Direction {
switch self {
case .north: return .west
case .west: return .south
case .south: return .east
case .east: return .north
}
}
var right: Direction {
return left.left.left
}
mutating func turnLeft() {
self = left
}
mutating func turnRight() {
self = right
}
}
let board = (0...4)
struct Robot {
let x, y: Int
let direction: Direction
init?(x: Int, y: Int, direction: Direction) {
guard board.contains(x), board.contains(y) else {
return nil
}
self.x = x
self.y = y
self.direction = direction
}
}
typealias Command = (Robot?) -> Robot?
let move: Command = { robot in
guard let robot = robot else {
return nil
}
let dx, dy: Int
switch robot.direction {
case .north:
dx = 0; dy = 1
case .east:
dx = 1; dy = 0
case .south:
dx = 0; dy = -1
case .west:
dx = -1; dy = 0
}
return Robot(x: robot.x+dx, y: robot.y+dy, direction: robot.direction)
}
let turnLeft: Command = { robot in
guard let robot = robot else {
return nil
}
return Robot(x: robot.x, y: robot.y, direction: robot.direction.left)
}
let turnRight: Command = { robot in
guard let robot = robot else {
return nil
}
return Robot(x: robot.x, y: robot.y, direction: robot.direction.right)
}
let report: Command = { robot in
guard let robot = robot else {
return nil
}
print("Report", robot.x, robot.y, robot.direction)
return robot
}
func makePlace(x: Int, y: Int, direction: Direction) -> Command {
return { robot in
return Robot(x: x, y: y, direction: direction)
}
}
let commands: [Command] = [
makePlace(x: 0, y: 0, direction: .north),
move,
move,
turnLeft,
move,
move
]
let robot = commands.reduce(Robot?.none) { robot, command in
return command(robot) ?? robot
}
report(robot)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment