exercism/go/crypto-square/crypto_square.go

46 lines
977 B
Go
Raw Normal View History

2016-08-13 23:20:14 +00:00
package cryptosquare
import (
"math"
"regexp"
"strings"
)
// TestVersion is an exercism thing
const TestVersion = 1
// Encode implements the classic method for composing
// secret messages called a square code
func Encode(txt string) string {
r := regexp.MustCompile("[^a-zA-Z0-9]+")
nrm := strings.ToLower(r.ReplaceAllString(txt, ""))
// The string should be normalized now (alphanumeric, lower case)
sqrt := int(math.Ceil(math.Sqrt(float64(len(nrm)))))
var square, ret []string
var tmp string
// Build the initial square
for i := 0; i < len(nrm); i++ {
if i%sqrt == 0 && len(tmp) != 0 {
square = append(square, tmp)
tmp = ""
}
tmp += string(nrm[i])
}
square = append(square, tmp)
tmp = ""
// Now rebuild the string by columns
for i := 0; i < len(square[0]); i++ {
for j := 0; j < len(square); j++ {
if i < len(square[j]) {
tmp += string(square[j][i])
}
}
ret = append(ret, tmp)
tmp = ""
}
return strings.Join(ret, " ")
}