Last active
February 24, 2019 03:29
-
-
Save rayfix/96bb966d0cbda25cff3eb60f6053817a to your computer and use it in GitHub Desktop.
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
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) | |
enum RobotError: Error { | |
case illegalPosition | |
} | |
struct Robot { | |
var x = 0 | |
var y = 0 | |
var direction = Direction.north | |
mutating func move() throws { | |
let oldX = self.x | |
let oldY = self.y | |
switch direction { | |
case .north: y += 1 | |
case .east: x += 1 | |
case .south: y -= 1 | |
case .west: x -= 1 | |
} | |
guard board.contains(x), board.contains(y) else { | |
x = oldX | |
y = oldY | |
throw RobotError.illegalPosition | |
} | |
} | |
func report() { | |
print(x,y,direction) | |
} | |
} | |
protocol RobotCommand { | |
func execute(on robot: inout Robot) throws | |
} | |
struct Place: RobotCommand { | |
var x, y: Int | |
var direction: Direction | |
func execute(on robot: inout Robot) { | |
robot.x = x | |
robot.y = y | |
robot.direction = direction | |
} | |
} | |
struct Move: RobotCommand { | |
func execute(on robot: inout Robot) throws { | |
try robot.move() | |
} | |
} | |
struct Left: RobotCommand { | |
func execute(on robot: inout Robot) { | |
robot.direction.turnLeft() | |
} | |
} | |
struct Right: RobotCommand { | |
func execute(on robot: inout Robot) { | |
robot.direction.turnRight() | |
} | |
} | |
struct Report: RobotCommand { | |
func execute(on robot: inout Robot) { | |
robot.report() | |
} | |
} | |
let commands: [RobotCommand] = [Place(x: 0, y: 0, direction: .north), | |
Move(), Move(), Left(), Move(), Move(), Report()] | |
var robot = Robot() | |
for command in commands { | |
try? command.execute(on: &robot) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment