Skip to content

Instantly share code, notes, and snippets.

@banyan
Created December 27, 2009 17:30
Show Gist options
  • Save banyan/264342 to your computer and use it in GitHub Desktop.
Save banyan/264342 to your computer and use it in GitHub Desktop.
# [問題 6.1]
# シーザー暗号の暗号化,複合化を行うプログラムを作りなさい.
# http://www.aoni.waseda.jp/ichiji/2009/second-term/ruby-06-1.html
# irb(main):122:0> string2 = caesar(string,3)
# => "Lq fubswrjudskb, d Fdhvdu flskhu, dovr nqrzq dv d Fdhvdu'v flskhu, wkh vkliw flskhu, Fdhvdu'v frgh ru Fdhvdu vkliw,
# lv rqh ri wkh vlpsohvw dqg prvw zlghob nqrzq hqfubswlrq whfkqltxhv."
# irb(main):123:0> caesar(string2,-3)
# => "In cryptography, a Caesar cipher, also known as a Caesar's cipher, the shift cipher, Caesar's code or Caesar shift,
# is one of the simplest and most widely known encryption techniques."
def caesar(string, i)
buf = []
h = {}
h['down'] = ('a'..'z').to_a
h['upper'] = ('A'..'Z').to_a
string.each_byte do | s |
if s.chr =~ /[a-z]/
buf << h['down'][h['down'].index(s.chr) + i]
elsif s.chr =~ /[A-Z]/
buf << h['upper'][h['upper'].index(s.chr) + i]
else
buf << s.chr
end
end
buf.to_s
end
s = "In cryptography, a Caesar cipher, also known as a Caesar's cipher, the shift cipher, Caesar's code or Caesar shift, is one of the simplest and most widely known encryption techniques."
s2 = "Lq fubswrjudskb, d Fdhvdu flskhu, dovr nqrzq dv d Fdhvdu'v flskhu, wkh vkliw flskhu, Fdhvdu'v frgh ru Fdhvdu vkliw, lv rqh ri wkh vlpsohvw dqg prvw zlghob nqrzq hqfubswlrq whfkqltxhv."
p caesar(s, 3)
p caesar(s2, -3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment