exercism/go/ocr-numbers/ocr.go

66 lines
1.6 KiB
Go

package ocr
import "strings"
// recognizeDigit takes a 3x4 grid of pipes, underscores, and spaces
// and determines the digit represented.
func recognizeDigit(in string) string {
switch in {
case "\n _ \n| |\n|_|\n ":
return "0"
case "\n \n |\n |\n ":
return "1"
case "\n _ \n _|\n|_ \n ":
return "2"
case "\n _ \n _|\n _|\n ":
return "3"
case "\n \n|_|\n |\n ":
return "4"
case "\n _ \n|_ \n _|\n ":
return "5"
case "\n _ \n|_ \n|_|\n ":
return "6"
case "\n _ \n |\n |\n ":
return "7"
case "\n _ \n|_|\n|_|\n ":
return "8"
case "\n _ \n|_|\n _|\n ":
return "9"
}
return "?"
}
// parseChar takes 3 lines and a number and returns
// the string value of that character
func parseChar(lines []string, num int) string {
startIdx := 3 * num
lenNeed := startIdx + 3
if len(lines[0]) < lenNeed || len(lines[1]) < lenNeed {
return ""
}
char := "\n" + lines[0][(startIdx+0):(startIdx+3)]
char += "\n" + lines[1][(startIdx+0):(startIdx+3)]
char += "\n" + lines[2][(startIdx+0):(startIdx+3)]
char += "\n" + lines[3][(startIdx+0):(startIdx+3)]
return recognizeDigit(char)
}
// Recognize takes a string, splits it up by \n and
// then sends 4 line chunks and calls parseChar on it
func Recognize(in string) []string {
var ret []string
lines := strings.Split(in, "\n")
numRet := len(lines) / 4
for i := 0; i < numRet; i++ {
var retString string
startIdx := (i * 4) + 1
procLines := lines[startIdx : startIdx+4]
numChars := len(lines[startIdx]) / 3
for j := 0; j < numChars; j++ {
retString += parseChar(procLines, j)
}
ret = append(ret, retString)
}
return ret
}