60
\$\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
  • 30
    \$\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
    Commented Jan 3, 2016 at 19:31
  • 13
    \$\begingroup\$ Some Trivia: this is Atbash, a known cipher as old as the bible. \$\endgroup\$
    – Jacob
    Commented Jan 4, 2016 at 9:21
  • 11
    \$\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
    Commented Jan 5, 2016 at 22:03
  • 1
    \$\begingroup\$ Kiltiznnrmt Kfaaovh & Xlwv Tlou should be the new site for "Programming Trivials & Code Bowling"... \$\endgroup\$ Commented Aug 3, 2016 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\$ Commented May 7, 2017 at 5:32

56 Answers 56

1
2
2
\$\begingroup\$

Vyxal, 5 bytes

kBklĿ

Try it Online!

Explanation:

kB     # Constant 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
  kl   # Constant 'ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba'
    Ŀ  # Transliterate a(b -> c)
       # Implicit output
\$\endgroup\$
2
\$\begingroup\$

Perl 5, 28 25 bytes

24 bytes of code + 1 for -p

s/\pL/chr(4+ord$&^31)/ge

Try it online!

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

MATL, 21 28 bytes

Uses version 6.0.0, which is earlier than this challenge. The code runs in Octave.

jttk2Y2mXK)o31Z~4-cK(

Example

>> matl
 > jttk2Y2mXK)o31Z~4-cK(
 >
> Hello, World!
Svool, Dliow!

Explanation

j             % input string
t             % duplicate
tk            % duplicate and convert to lowercase
2Y2           % string 'abc...xyz'
m             % "ismember" function: produces logical index of letter positions
XK            % copy to clipboard K
)             % index into string to get its letters
o31Z~4-       % bitwise XOR with 31 and subtract 4
c             % convert to char
K             % paste logical index from clipboard K
(             % put back modified letters into original string

Old approach, 28 bytes

j1Y2!tkh"t@2#m@0v27b-)wXK)K(
\$\endgroup\$
1
\$\begingroup\$

MATLAB, 61 bytes

@(x)[abs(-x+ismember(x,65:90)*155+ismember(x,97:122)*219),'']

I tried f=@ismember, and making the range a=65:90 a variable and do 32+a in the second ismember-call. All this shortened the code, but would result in a program and thus require both disp and input.

This gives:

ans('Hello, World!')
ans =
Svool, Dliow!

ans('Programming Puzzles & Code Golf')
ans =
Kiltiznnrmt Kfaaovh & Xlwv Tlou
\$\endgroup\$
1
\$\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\$
1
\$\begingroup\$

Brachylog, 66 bytes

_|hH(:64>:91<,77-H+78=X;H:96>:123<,109-H+110=X;HX),[X]:"~c"w,?b:0&

The lack of built-ins really hurts here, so we have to resort to good old ASCII codes computations.

The predicate brachylog_main expects a character codes string as input and no output, e.g. brachylog_main(`Hello, World!`,_).

Explanation

_                                                                  § If the input is empty,
                                                                   § return true
                                                                   §
 |                                                                 § Else
                                                                   §
  hH(                                            ),[X]:"~c"w       § Print variable X which
                                                                   § depends on the head of
                                                                   § the input as a char code
                                                                   §
                                                            ,?b:0& § Recursive call on the
                                                                   § tail of the input
                                                                   §
     :64>:91<,77-H+78=X                                            § If H is capital, X =
                                                                   § 77 - H + 78
                       ;                                           § Else if H is non-cap, X=
                        H:96>:123<,109-H+110=X                     § 109 - H + 110
                                              ;                    § Else (not a letter)
                                               HX                  § H = X    
\$\endgroup\$
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\$ Commented Feb 5, 2016 at 6:04
1
\$\begingroup\$

Oracle SQL 11.2, 105 bytes

SELECT TRANSLATE(:1,a||UPPER(a),REVERSE(UPPER(a)||a))FROM(SELECT'abcdefghijklmnopqrstuvwxyz'a FROM DUAL);
\$\endgroup\$
1
\$\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\$
1
\$\begingroup\$

PHP, 69 bytes

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

mapping stolen from ETHproductions

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

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\$

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

05AB1E, 5 bytes

ž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
    Commented Nov 22, 2016 at 3:12
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 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\$

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\$ Commented Nov 21, 2016 at 15:33
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
    Commented May 6, 2017 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\$ Commented Oct 27, 2020 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\$ Commented Oct 27, 2020 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\$ Commented Oct 27, 2020 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 and acknowledge you have read our privacy policy.

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