summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDimitri Sokolyuk <demon@dim13.org>2016-08-27 21:09:12 +0200
committerDimitri Sokolyuk <demon@dim13.org>2016-08-27 21:09:12 +0200
commitcd350a33c56dce01fad81fa5ebb2f1258d2f2455 (patch)
tree4ca20d64d935732cb5686220373465c9f8b20368
parente6fc4f9d5b2116b187da38d49629a0637b954d39 (diff)
Solve crypto
-rw-r--r--go/crypto-square/crypto_square.go58
1 files changed, 58 insertions, 0 deletions
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))), " ")
+}