Solving 'The Python Challenge' with Ruby
Level 1 - what about making trans?
URL for Level 1 is here.
In the webpage, a picture with the followings drawn on a paper is shown:
K -> M
O -> Q
E -> G
and there are also the following messages:
everybody thinks twice before solving this.
g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq
glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb.
lmu ynnjw ml rfc spj.
After thinking, I know I need to translate the strange message above with the rule drawn on the paper. So what is the rule? After thinking again (totally thinking twice :)), I find that I need to replace every letter by the letter 2 places after it. Then I write the following function to do it:
def translate(str)
str.split(//).map do |c|
case c
when 'a'..'x': c.next.next
when 'y': 'a'
when 'z': 'b'
else c
end
end
end
Passing the strange message to this function, I get:
i hope you didnt translate it by hand. thats what computers are for. doing it in by hand is
inefficient and that's why this text is so long. using string.maketrans() is recommended.
now apply on the url.
It tells me to apply the same translation on the URL: 'map', which gives 'ocr'. Therefore the url for level 2 is here.
Updated: there is built-in string function to do the same thing:
String#tr(fromString, toString)
So:
"map".tr('a-z','c-zab')
will give 'ocr'.