Skip to content

Instantly share code, notes, and snippets.

@rtoal
Last active December 20, 2017 19:19
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 rtoal/5075fd521727498520440943320c704d to your computer and use it in GitHub Desktop.
Save rtoal/5075fd521727498520440943320c704d to your computer and use it in GitHub Desktop.
Smart TV Virtual Keyboard Trace
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")
@JeremyHi
Copy link

Great job!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment