48
\$\begingroup\$

In this challenge, you will be "reversing" the alphabet or swapping a-z with z-a. This is commonly known as the Atbash cypher.

Because this transformation makes the output look like some foreign language, your code will need to be as short as possible.


Examples

abcdefghijklmnopqrstuvwxyz
zyxwvutsrqponmlkjihgfedcba

Programming Puzzles & Code Golf
Kiltiznnrmt Kfaaovh & Xlwv Tlou

Hello, World!
Svool, Dliow!

Specification

  • The input may contain multiple lines, and will be ASCII-only
  • No additional whitespace should be added to the output
  • Case must be preserved

Leaderboard

var QUESTION_ID=68504,OVERRIDE_USER=40695;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>


This is so shortest code in bytes wins

\$\endgroup\$
  • 24
    \$\begingroup\$ +1 for the justification "Because this transformation makes the output look like some foreign language, your code will need to be as short as possible." \$\endgroup\$ – cat Jan 3 '16 at 19:31
  • 11
    \$\begingroup\$ Some Trivia: this is Atbash, a known cipher as old as the bible. \$\endgroup\$ – Jacob Jan 4 '16 at 9:21
  • 6
    \$\begingroup\$ "Because this transformation makes the output look like some foreign language, your code will need to be as short as possible." What kind of logic is that?? Because your description raises about as much question marks as if it was written in some foreign language your answer to this question should be in intelligible natural language and some verbosity is appreciated. \$\endgroup\$ – Bart Jan 5 '16 at 22:03
  • \$\begingroup\$ Kiltiznnrmt Kfaaovh & Xlwv Tlou should be the new site for "Programming Trivials & Code Bowling"... \$\endgroup\$ – Erik the Outgolfer Aug 3 '16 at 17:09
  • \$\begingroup\$ Why don't you allow additional whitespace? That makes it impossible in some languages that always have a trailing newline. I can't see it adding anything to the challenge. \$\endgroup\$ – Esolanging Fruit May 7 '17 at 5:32

50 Answers 50

1
\$\begingroup\$

PHP, 73 bytes

<?=strtr($argv[1],($b=strtolower($a=join(range(A,Z)))).$a,strrev($a.$b));

do this need any comments?

\$\endgroup\$
1
\$\begingroup\$

Perl 5, 28 bytes

27 bytes of code + 1 for -p

s/[a-z]/chr(4+ord$&^31)/gie

Try it online!

\$\endgroup\$
0
\$\begingroup\$

CJam, 33 bytes

q['a{_)}25*]_eu+['z{_(}25*]_eu+er

Explanation:

q                   e# Read all input an put string to the stack
[                   e# Start array (char)
    'a              e# Put 'a' char to the stack
    {               e# Begin of code block
        _           e# Duplicate top element on the stack
        )           e# Increment the duplicate
    }               e# End of code block
    25*             e# Repeat code block 25 times
]                   e# End array
_                   e# Duplicate array
eu                  e# Uppercase the duplicate
+                   e# And join arrays
['z{_(}25*]_eu+     e# Repeat the same thing back from Z
er                  e# Replace A-z with z-A in the input
\$\endgroup\$
0
\$\begingroup\$

Python 2, 104 bytes

Pretty simple using str.translate and string.maketrans.

from string import*
u=ascii_uppercase
l=u.lower()
f=lambda x:x.translate(maketrans(u+l,u[::-1]+l[::-1]))

Try it online

This last line would also work, since string is imported:

f=lambda x:translate(x,maketrans(u+l,u[::-1]+l[::-1]))
\$\endgroup\$
0
\$\begingroup\$

Python 3, 141 bytes

Similar to @cat, but uses a dict to map letters and uses a simpler comprehension for the print:

a=__import__('string').ascii_letters;l,u=a[:26],a[26:];m=dict(zip(a,l[::-1]+u[::-1]));print(''.join(m[c] if c in a else c for c in input()))

Ungolfed:

a = __import__('string').ascii_letters; # import alphabet
l, u = a[:26],a[26:];                   # separate lower/uppercase
m = dict(zip(a, l[::-1] + u[::-1]));    # create map a-z+A-Z -> z-a+Z-A
print(''.join(m[c] if c in a else c     # if input char in map, map it
                   for c in input()))   # otherwise leave it alone
\$\endgroup\$
0
\$\begingroup\$

Oracle SQL 11.2, 105 bytes

SELECT TRANSLATE(:1,a||UPPER(a),REVERSE(UPPER(a)||a))FROM(SELECT'abcdefghijklmnopqrstuvwxyz'a FROM DUAL);
\$\endgroup\$
0
\$\begingroup\$

Factor, 92 bytes

[ [ 65 90 [a,b] dup >lower 2dup [ reverse ] bi@ append -rot append zip >hashtable at ] map ]

An anonymous function. Making it case insensitive is... expensive.

\$\endgroup\$
0
\$\begingroup\$

JavaScript ES6, 96 bytes

var R=i=>i.replace(/[A-z]/g,s=>String.fromCharCode(155-s.charCodeAt(0)+(/[a-z]/.test(s)?64:0)))

Not as good as the other JavaScript answer, but I thought I'd try myself.

\$\endgroup\$
  • \$\begingroup\$ Your A-z regex matches [\]^_`, none of which should be modified. You'll probably want A-Za-z. \$\endgroup\$ – Martin Ender Nov 21 '16 at 15:33
0
\$\begingroup\$

PHP, 69 bytes

while(""<$c=$argv[1][$i++])echo ctype_alpha($c)?chr(ord($c)+4^31):$c;

mapping stolen from ETHproductions

\$\endgroup\$
0
\$\begingroup\$

Racket 332 bytes

(let p((l(map char->integer(string->list s)))(ol'())(g(λ(n a b)(and(> n a)(< n b))))(t first)(c cons))
(cond[(empty? l)(list->string(map integer->char(reverse ol)))][(and(not(g(t l)96 123))(not(g(t l)64 91)))(p(rest l)(c(t l)ol)g t c)]
[(>(t l)95)(p(rest l)(c(- 122(-(t l)97))ol)g t c)][else(p(rest l)(c(- 90(-(t l)65))ol)g t c)]))

Ungolfed:

(define(f s)
  (let p ((l (map char->integer (string->list s)))
             (ol '())
             (g (λ (n a b) (and (> n a) (< n b))))
             (t first)
             (c cons))
    (cond
      [(empty? l)
       (list->string (map integer->char (reverse ol)))]
      [(and(not (g (t l) 96 123)) (not(g(t l) 64 91)))
       (p (rest l) (c (t l) ol) g t c)]
      [(> (t l) 95)
       (p (rest l) (c (- 122 (- (t l) 97)) ol) g t c)]
      [else
       (p (rest l) (c (- 90 (- (t l) 65)) ol) g t c)]
      )))

Testing:

(f "abcdefghijklmnopqrstuvwxyz")
(f "Programming Puzzles & Code Golf")
(f "Hello, World!")

Output:

"zyxwvutsrqponmlkjihgfedcba"
"Kiltiznnrmt Kfaaovh & Xlwv Tlou"
"Svool, Dliow!"
\$\endgroup\$
0
\$\begingroup\$

C#, 234 Bytes

Golfed:

string A(string s){string a="abcdefghijklmnopqrstuvwxyz",z=string.Concat(a.Reverse()),o="";s.ToList().ForEach(c=>o+=!z.Contains(char.ToLower(c))?c:char.IsLower(c)?z[a.IndexOf(c)]:char.ToUpper(z[a.IndexOf(char.ToLower(c))]));return o;}

Ungolfed:

public string A(string s)
{
  string a = "abcdefghijklmnopqrstuvwxyz",
    z = string.Concat(a.Reverse()), o = "";
  s.ToList().ForEach(c => o += !z.Contains(char.ToLower(c)) ? c :
  char.IsLower(c) ? z[a.IndexOf(c)] :
  char.ToUpper(z[a.IndexOf(char.ToLower(c))]));
  return o;
}

Testing:

Console.WriteLine(new Atbash().A("Programming Puzzles & Code Golf"));
Kiltiznnrmt Kfaaovh & Xlwv Tlou

Console.WriteLine(new Atbash().A("Hello, World!"));
Svool, Dliow!
\$\endgroup\$
0
\$\begingroup\$

05AB1E, 5 bytes (Non-competing?)

žižk‡

Try it online!

       # Push input.
 ži    # Push [a-zA-Z]
   žk  # Push [z-aZ-A]
     ‡ # Transliterate a#(b -> c)
\$\endgroup\$
  • \$\begingroup\$ Implicit input... you can remove the I. \$\endgroup\$ – Oliver Ni Nov 22 '16 at 3:12
0
\$\begingroup\$

REXX, 88 bytes

b=xrange(a,z)
a=lower(b)
do forever
  parse pull n
  say translate(n,reverse(b||a),a||b)
end
\$\endgroup\$
0
\$\begingroup\$

Mathematica 89 Bytes

StringReplace[#,Thread[#~Join~#3@#->#2@#~Join~#2@#3@#]&[Alphabet[],Reverse,ToUpperCase]]&

48 Bytes of this is just long function names

\$\endgroup\$
0
\$\begingroup\$

Lua, 116 bytes

t={}for i=65,90 do a=('').char(i)b=a.char(155-i)t[a],t[a:lower()]=b,b:lower()end print((io.read"*all"):gsub("%a",t))`
\$\endgroup\$
0
\$\begingroup\$

JavaScript, 57 bytes

s=>{var k;for(var a=s.length-1;a>0;a--){k+=s[a]}return k}
\$\endgroup\$
  • 1
    \$\begingroup\$ Does it work? How? s[s.length] === undefined \$\endgroup\$ – Tymek May 6 '17 at 11:12
0
\$\begingroup\$

Jelly, 11 bytes

ØAµ,Uµ;Œsðy

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Common Lisp, 110 bytes

(lambda(s)(map-into s(lambda(x)(if(alpha-char-p x)(code-char(-(if(upper-case-p x)155 219)(char-code x)))x))s))

Try it online!

Very straightforward solution.

\$\endgroup\$
0
\$\begingroup\$

PowerShell, 65 bytes

-join($args|% t*y|%{[char]($_,(($_-bxor31)-4))[$_-match'[a-z]']})

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Wolfram Language (Mathematica), 114 bytes

(a=Alphabet[];b=Capitalize/@a;r:=Reverse;u=AssociationThread[a~Join~b->r@a~Join~r@b];StringJoin[Characters@#/.u])&

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.