2020年4月16日木曜日

開発環境

入門Goプログラミング (Nathan Youngman(著)、Roger Peppé(著)、吉川 邦夫(監修, 翻訳)、翔泳社)のUNIT 2(型)、LESSON 11(チャレンジ:ヴィジュネル暗号化)の練習問題-2の解答を求めてみる。

コード

package main

import (
 "fmt"
 "strings"
)

func main() {
 cipherText := "CSOITEUIWUIZNSROCNKFD"
 keyword := "GOLANG"

 // strings.Repeat関数を使った版

 // rangeを使った版
 keywordRepeat := strings.Repeat(keyword, len(cipherText)/len(keyword)+1)
 text := ""
 for i, r := range cipherText {
  shift := keywordRepeat[i] - 'A'
  t := r - 'A'
  c := (t-rune(shift)+26)%26 + 'A'
  text += string(c)
 }
 fmt.Println(text)

 // rangeを使わない版
 text = ""
 for i := 0; i < len(cipherText); i++ {
  shift := keywordRepeat[i] - 'A'
  t := cipherText[i] - 'A'
  c := (t-shift+26)%26 + 'A'
  text += string(c)
 }
 fmt.Println(text)

 // strings.Repeat関数を使わない、fmtパッケージのみ使った版

 // rangeを使った版
 text = ""
 for i, r := range cipherText {
  shift := keywordRepeat[i%len(keyword)] - 'A'
  t := r - 'A'
  c := (t-rune(shift)+26)%26 + 'A'
  text += string(c)
 }
 fmt.Println(text)

 // rangeを使わない版
 text = ""
 for i := 0; i < len(cipherText); i++ {
  shift := keywordRepeat[i%len(keyword)] - 'A'
  t := cipherText[i] - 'A'
  c := (t-shift+26)%26 + 'A'
  text += string(c)
 }
 fmt.Println(text)

 fmt.Println(cipherText)
}

入出力結果(Zsh、PowerShell、Terminal)

% go build cipher.go 
% ./cipher 
SAJRZYMEPGRAIQHHRLY
YOURMESSAGEGOESHERE
your message goes here
%

0 コメント:

コメントを投稿