Skip to main content
Code Review

Return to Question

Post Reopened by Malachi
edited tags
Link
Vogel612
  • 25.5k
  • 7
  • 59
  • 141
Post Closed as "Not suitable for this site" by Dan Oberlam, Sᴀᴍ Onᴇᴌᴀ , Billal BEGUERADJ, Stephen Rauch, Daniel
edited tags
Link
200_success
  • 145.5k
  • 22
  • 190
  • 478
Tweeted twitter.com/#!/StackCodeReview/status/263534847715328000
Source Link
ceth
  • 802
  • 4
  • 13

My first Go program: Caesar Cipher

I'm learning Go at this moment and it is my first program in Go, so I will be thankfull for any suggestion, remarks and observations.

package main
import (
 "fmt"
)
const ascii = "abcdefghijklmnopqrstuvwxyz"
var goodness_values = []float32 { .0817,.0149,.0278,.0425,.1270,.0223,.0202, .0609,.0697,.0015,.0077,.0402,.0241,.0675, .0751,.0193,.0009,.0599,.0633,.0906,.0276, .0098,.0236,.0015,.0197,.0007 }
func zip(s1 string, s2 string) map[string]string {
 result := make(map[string] string)
 for i, v := range s1 {
 result[string(v)] = string(s2[i])
 }
 return result
}
func crypt(s string, table map[string]string) string {
 result := ""
 for _, v := range s {
 result += table[string(v)] 
 }
 
 return result
}
func encode(message string, key int) string {
 shifted_ascii := ascii[key:] + ascii[:key]
 trans_table := zip(ascii, shifted_ascii)
 
 return crypt(message, trans_table)
}
func decode(secret string, key int) string {
 shifted_ascii := ascii[key:] + ascii[:key]
 trans_table := zip(shifted_ascii, ascii)
 return crypt(secret, trans_table)
}
func goodness(version string, letter_goodness map[string] float32) float32 {
 var result float32 = 0.0
 for _, v := range version {
 result += letter_goodness[string(v)]
 }
 return result
}
func crack(secret string) string {
 var best_score float32 = 0.0
 result := ""
 letter_goodness := make(map[string] float32)
 for i, v := range ascii {
 letter_goodness[string(v)] = goodness_values[i]
 }
 for i := 0; i <= 26; i++ { 
 version := decode(secret, i);
 score := goodness(version, letter_goodness);
 if(score > best_score) {
 best_score = score
 result = version
 }
 }
 return result
}
func main() {
 fmt.Printf("%s\n", encode("hello", 10))
 fmt.Printf("%s\n", decode("rovvy", 10))
 fmt.Printf("%s\n", crack("pybrscpexnkwoxdkvmyxdbsledsyxcdydronopsxsdsyxkxnnocsqxypzbyqbkwwsxqvkxqekqoc"))
}
lang-golang

AltStyle によって変換されたページ (->オリジナル) /