Last active
December 20, 2017 19:19
-
-
Save rtoal/5075fd521727498520440943320c704d to your computer and use it in GitHub Desktop.
Smart TV Virtual Keyboard Trace
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
struct Coordinate { | |
var row: Int = 0 | |
var col: Int = 0 | |
} | |
var coordinateMapping: [Character: Coordinate] = { | |
var mapping: [Character: Coordinate] = [:] | |
for (index, letter) in "ABCDEFGHIJKLMNOPQRSTUVWXYZ".enumerated() { | |
mapping[letter] = Coordinate(row: index / 5, col: index % 5) | |
} | |
return mapping | |
}() | |
func instructions(for word: String) -> String? { | |
var result: String = "" | |
guard var current: Coordinate = coordinateMapping["A"] else { | |
return nil | |
} | |
for letter in word.uppercased() { | |
guard let target: Coordinate = coordinateMapping[letter] else { | |
return nil | |
} | |
// Order matters, must do L before D and must do U before R | |
result += String(repeating: "L", count: max(current.col - target.col, 0)) | |
result += String(repeating: "D", count: max(target.row - current.row, 0)) | |
result += String(repeating: "U", count: max(current.row - target.row, 0)) | |
result += String(repeating: "R", count: max(target.col - current.col, 0)) | |
result += "E" | |
current = target | |
} | |
return result | |
} | |
assert(instructions(for: "A") == "E") | |
assert(instructions(for: "BAT") == "RELEDDDRRRRE") | |
assert(instructions(for: "8rh4") == nil) | |
assert(instructions(for: "Zoo") == "DDDDDEUUURRRREE") | |
assert(instructions(for: "hazy") == "DRRELLUEDDDDDEURRRRE") | |
print("All tests passed") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great job!