Skip to content

Instantly share code, notes, and snippets.

@tsak
Last active June 18, 2019 17:14
Show Gist options
  • Save tsak/42b26d15a81a4f9984c0973c4498d1dd to your computer and use it in GitHub Desktop.
Save tsak/42b26d15a81a4f9984c0973c4498d1dd to your computer and use it in GitHub Desktop.
How long does it take to enter a number for a given keypad
package main
import "fmt"
type Keypad struct {
matrix [3][3]string
}
func NewKeypad(keypad string) Keypad {
var result Keypad
x, y := 0, 0
for _, c := range keypad {
result.matrix[y][x] = string(c)
x++
if (x > 2) {
y++
x = 0
}
}
return result
}
func (k *Keypad) Print() {
fmt.Print("-------\n")
for _, row := range k.matrix {
for _, letter := range row {
fmt.Print("|" + string(letter))
}
fmt.Print("|\n-------\n")
}
}
func (k *Keypad) Coord(key string) (int, int) {
for x, row := range k.matrix {
for y, letter := range row {
if string(letter) == key {
return x, y
}
}
}
return -1, -1
}
func (k *Keypad) Distance(s1, s2 string) int {
if s1 == s2 {
return 0
}
x1, y1 := k.Coord(s1)
x2, y2 := k.Coord(s2)
// Manhattan distance
dist := abs(x2 - x1) + abs(y2 - y1)
// Diagonal distance is 2, should be 1 for our case
if abs(x2 - x1) == 1 && abs(y2 - y1) == 1 {
dist = 1
}
return dist
}
// Absolute value for integers
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
func entryTime(s string, keypad string) int32 {
var result int32 = 0
k := NewKeypad(keypad)
for i := 0; i < len(s)-1; i++ {
key := string(s[i])
nextKey := string(s[i+1])
dist := k.Distance(key, nextKey)
if dist == 1 {
result += 1
}
if dist > 1 {
result += 2
}
}
return result
}
func main() {
fmt.Println("= test", entryTime("423692", "923857614"), "expected", 8)
fmt.Println("= test", entryTime("5111", "752961348"), "expected", 1)
fmt.Println("= test", entryTime("91566165", "639485712"), "expected", 11)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment