Created
May 19, 2012 09:25
-
-
Save shim0mura/2730240 to your computer and use it in GitHub Desktop.
rubyでシーザー暗号解読
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#http://vipprog.net/wiki/exercise.html#h54a0395 | |
class Caesar | |
def initialize(str, hint) | |
@key = nil | |
@str = str | |
@base = "abcdefghijklmnopqrstuvwxyz .,-" | |
@hint = hint | |
end | |
def analyze | |
1.upto(@base.size-1) do |key| | |
@key = key | |
hint = shift_hint(@hint) | |
next unless @str.index(hint) | |
@key = -1 * @key | |
break | |
end | |
end | |
def shift_hint(str) | |
base_arr = @base.split("") | |
str_arr = str.split("") | |
shifted = "" | |
base_size = base_arr.size | |
str_arr.each_with_index do |char, i| | |
next unless charnum = get_charnum(char) | |
next_char = base_arr[(charnum + @key) % base_size] | |
shifted << next_char | |
end | |
shifted | |
end | |
def get_charnum(char) | |
@base.split("").index(char) | |
end | |
end | |
c = Caesar.new("qdq-gi.q-a ziatmxxitmdqibtqi-ustbi ri.qmoqrcxi.qbubu zir -ibtqi-qp-qaai ripmymsqkir -ibtqi-qy dmxi ri.cnxuoi rruoumxakir -ibtqiqzmobyqzbkii-q.qmxi -imyqzpyqzbi rixmeaki -puzmzoqai -i-qscxmbu zaimzpir -i btq-iymbbq-a;iz -iatmxximzgi.q-a zinqiuzimzgiemgipuao-uyuzmbqpimsmuzabir -ia. za -uzsiacotiimi.qbubu zj", "person") | |
c.analyze |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment