From cd350a33c56dce01fad81fa5ebb2f1258d2f2455 Mon Sep 17 00:00:00 2001 From: Dimitri Sokolyuk Date: Sat, 27 Aug 2016 21:09:12 +0200 Subject: Solve crypto --- go/crypto-square/crypto_square.go | 58 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 go/crypto-square/crypto_square.go (limited to 'go/crypto-square') diff --git a/go/crypto-square/crypto_square.go b/go/crypto-square/crypto_square.go new file mode 100644 index 0000000..afb94f7 --- /dev/null +++ b/go/crypto-square/crypto_square.go @@ -0,0 +1,58 @@ +package cryptosquare + +import ( + "math" + "strings" + "unicode" +) + +const testVersion = 2 + +func normalize(s string) string { + var r []rune + for _, v := range s { + if unicode.IsLetter(v) || unicode.IsNumber(v) { + r = append(r, unicode.ToLower(v)) + } + } + return string(r) +} + +func split(s string) []string { + cols := int(math.Ceil(math.Sqrt(float64(len(s))))) + rows := len(s) / cols + if len(s)%cols != 0 { + rows++ + } + r := make([]string, rows) + for i := range r { + start := i * cols + end := start + cols + if end > len(s) { + end = len(s) + } + r[i] = s[start:end] + } + return r +} + +func transpose(s []string) []string { + r := make([][]byte, len(s[0])) + for j := 0; j < len(s); j++ { + for i := 0; i < len(s[j]); i++ { + r[i] = append(r[i], s[j][i]) + } + } + ret := make([]string, len(s[0])) + for i := range ret { + ret[i] = string(r[i]) + } + return ret +} + +func Encode(s string) string { + if len(s) == 0 { + return "" + } + return strings.Join(transpose(split(normalize(s))), " ") +} -- cgit v1.2.3