57
\$\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\$
6
  • 29
    \$\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
  • 12
    \$\begingroup\$ Some Trivia: this is Atbash, a known cipher as old as the bible. \$\endgroup\$
    – Jacob
    Jan 4 '16 at 9:21
  • 10
    \$\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
  • 1
    \$\begingroup\$ Kiltiznnrmt Kfaaovh & Xlwv Tlou should be the new site for "Programming Trivials & Code Bowling"... \$\endgroup\$ 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\$ May 7 '17 at 5:32

56 Answers 56

1
2
1
\$\begingroup\$

Perl 6, 40 39 bytes

Since everyone else is doing anonymous functions:

my &f=*.trans(/\w/=>{chr $/.ord+4+^31})

(Thanks @b2gills for the tip)

Uses the same bit flipping voodoo as some of the other posts. I wasn't sure whether to include the variable/function declaration in the byte count, so I did just in case. Without it this solution is only 34 bytes.

Usage:

> f "zyxwvutsrqponmlkjihgfedcba"
abcdefghijklmnopqrstuvwxyz
> f "Kiltiznnrmt Kfaaovh & Xlwv Tlou"
Programming Puzzles & Code Golf
> f "Svool, Dliow!"
Hello, World!
\$\endgroup\$
1
  • \$\begingroup\$ You can use *.trans(…) to make it shorter. \$\endgroup\$ Feb 5 '16 at 6:04
1
\$\begingroup\$

Python 3, 164 159 bytes

def f(t,a="abcdefghijklmnopqrstuvwxyz",b=""):
 for c in t:u=64<ord(c)<91;c=c.lower();c=a[::-1][a.index(c)] if c in a else c;b+=c.upper() if u else c
 return b
\$\endgroup\$
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\$

Jelly, 11 bytes

ØAµ,Uµ;Œsðy

Try it online!

\$\endgroup\$
1
\$\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\$
1
\$\begingroup\$

PowerShell, 65 bytes

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

Try it online!

\$\endgroup\$
1
\$\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\$
1
\$\begingroup\$

Husk, 22 bytes

σ…'A'Z…'Z'Aσ…'a'z…'z'a

Try it online!

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

C, 112 98 bytes

i;main(){char x[99];gets(x);for(;x[i];i++)if(isalpha(x[i]))x[i]=(x[i]>90?219:155)-x[i];puts(x);}

I know that gets() is deprecated and unsafe, but scanf() doesn't accept whitespace and I need to include stdio.h if I want to fgets (since stdin is defined in stdio.h). I assume this program wouldn't work if the user tried to enter a string more than 99 characters.

EDIT: Changing printf("%s",x) to puts(x) saves 7 bytes and changing i<strlen(x) to x[i] saves another 7 bytes.

\$\endgroup\$
1
  • \$\begingroup\$ I find it interesting that I can't replace i;main(){char x[99]; with i,x[99];main{ (This changes the type to an int, which seems to cause the program to output garbled text). Can anyone explain this? \$\endgroup\$
    – neondev1
    Apr 27 at 19:55
1
\$\begingroup\$

K (ngn/k), 32 bytes

{x^'![t,_t;(|t),|_t:`c$65+!26]x}

Try it online!

Builds a dictionary mapping the letters to their "reverses", filling any non-letter character with what was in the input.

  • t:`c$65+!26 build a list of the letters from "A" through "Z", storing in t
  • ![t,_t;(|t),|_t:...] build a dictionary mapping the letters to their reverses
  • x^'![...]x index into that dictionary with the input. non-letter characters in the input get replaced with " "'s, so replace those spaces with whatever was in the input

k4, 24 bytes

{x^![|,/|l;,/l:.Q`a`A]x}

Similar to the above, but benefits from using the built-in lists of characters; .Q.A for uppercase letters, and .Q.a for the lower case ones.

\$\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\$
1
  • 1
    \$\begingroup\$ Your A-z regex matches [\]^_`, none of which should be modified. You'll probably want A-Za-z. \$\endgroup\$ 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\$
1
  • \$\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
  • 1
    \$\begingroup\$ Does it work? How? s[s.length] === undefined \$\endgroup\$
    – Tymek
    May 6 '17 at 11:12
0
\$\begingroup\$

Python3

This is my first post on Code Golf; but I think I understood your question successfully;

This python3 code replaces abc -> xyz (as you specified above)

def ASUB(m,A,B):o = m.maketrans(A,B);r = m.translate(o);return(r);
ASUB(m="Programming Puzzles & Code Golf",
     A="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
     B="zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA")
#'Svool, Dliow!'
#'Kiltiznnrmt Kfaaovh & Xlwv Tlou'

the output of the both messages (Hello, World! and the other one) is in # comments

EDIT: Thanks for clarifying caird coinheringaahing!

Improved:

def A(m):o=m.maketrans("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ","zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA");return m.translate(o);
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Welcome to the site! This is a nice first answer, but there are a couple of issues. First, we require answers to code golf challenges to attempt to golf as much as possible, which, for Python, includes 1 letter variable names, and removing unnecessary whitespace. Secondly, as this calls for 1 input (m), your function shouldn't take A and B as parameters, rather you should include the full strings in your answer. Here is a version of your answer that's slightly more golfed (156 bytes), and follows the site rules on functions \$\endgroup\$ Oct 27 '20 at 14:45
  • \$\begingroup\$ Oh, thanks so much for the kind and clear, as swell as detailed explanation! and the other version! I can't thank you enough! Should I edit or remove my post because of these issues? Thanks again! \$\endgroup\$ Oct 27 '20 at 14:51
  • 1
    \$\begingroup\$ This is a perfectly valid answer, just needs a little bit of improvement, which is exactly what SE's edit feature is for! \$\endgroup\$ Oct 27 '20 at 14:52
0
\$\begingroup\$

Jelly, 8 bytes

ØẠŒsU,Ɗy

Try it online!

How it works

ØẠŒsU,Ɗy - Main link. Takes S on the left
ØẠ       - Yield "ABC...XYZabc...xyz"
      Ɗ  - Last three links as a monad f("ABC...XYZabc...xyz"):
  Œs     -   Swapcase
    U    -   Reverse
     ,   -   Pair
       y - Translate S by this mapping
\$\endgroup\$
1
2

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.