Swap the Alphabet

48

9

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

Downgoat

Posted 2016-01-03T19:25:51.527

Reputation: 27 116

24+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." – cat – 2016-01-03T19:31:40.320

11

Some Trivia: this is Atbash, a known cipher as old as the bible.

– Jacob – 2016-01-04T09:21:05.597

6"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. – Bart – 2016-01-05T22:03:57.993

Kiltiznnrmt Kfaaovh & Xlwv Tlou should be the new site for "Programming Trivials & Code Bowling"... – Erik the Outgolfer – 2016-08-03T17:09:14.253

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. – Esolanging Fruit – 2017-05-07T05:32:07.333

The specifications do not say whether we keep the capitalisation or not – Stan Strum – 2017-09-08T04:46:07.153

Answers

11

Pyth, 8 bytes

XXzG)rG1

@xnor suggested this simpler approach on @FryAmTheEggman's Pyth answer, then I translated it to Pyth.

This uses the handy behavior of X (translate) when given only two arguments: it translates from the second argument to the reversed second argument. We do this first with the lowercase alphabet (G), and then with uppercased G.

lirtosiast

Posted 2016-01-03T19:25:51.527

Reputation: 20 331

16

C, 59 bytes

Sorry for bringing up C again, but I was a bit disappointed to see only C functions here. I was under the impression OP was looking for a usable product.

main(c){while(~(c=getchar()))putchar(isalpha(c)?c+4^31:c);}

Compiled on Ubuntu 14.04 with a simple:

cc swalpha.c

The resulting executable reads any number of lines from stdin, and writes the result to stdout.

Thanks to so many of the other posters for the XOR trick.

Ruud Helderman

Posted 2016-01-03T19:25:51.527

Reputation: 571

11

JavaScript (ES6), 69 67 bytes

x=>x.replace(/[A-Z]/gi,c=>String.fromCharCode(c.charCodeAt()+4^31))

Uses the same strategy as my Japt answer:

x=>x.replace(/[A-Z]/gi,C=>   // Replace each letter C with
 String.fromCharCode(        //  the character with char code
  C.charCodeAt()+4^31))      //   the char code of C, plus 4, with the last 5 bits flipped.

Curse your incredibly long property names, JS...

ETHproductions

Posted 2016-01-03T19:25:51.527

Reputation: 47 880

1+1 for mentioning JS's excruciatingly long property names. My favorite is still the infamous document.getElementById – Cyoce – 2016-01-05T07:04:47.687

2@Cyoce Try document.getElementsByClassName or, on Firefox and Chrome, document.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC – Ismael Miguel – 2016-01-06T10:28:58.673

This seems to only be 66 bytes not 67 – Downgoat – 2016-01-06T23:28:06.737

@Doᴡɴɢᴏᴀᴛ You're right about that, thanks! – ETHproductions – 2016-01-06T23:28:51.997

It looks like you are missing a closing bracket on the end of the golfed code. – starbeamrainbowlabs – 2016-01-07T06:56:58.273

@starbeamrainbowlabs Thanks! I wondered why I had miscounted... – ETHproductions – 2016-01-07T15:20:32.947

11

CJam, 17 bytes

I wanted to help GamrCorps golf his CJam solution, but the result ended up so different that I decided to make a separate answer.

q'[,_el^_W%32f^er

Try it online.

Explanation

q     e# Read all input.
'[,   e# Get a character range from the null byte up to and including "Z".
_el   e# Duplicate and convert to lowercase.
^     e# Symmetric set difference. Due to the lowercase operation only letters will not
      e# appear in both sets, and so we get a string with all uppercase letters followed
      e# by all lowercase letters, i.e "ABC...XYZabc...xyz".
_W%   e# Duplicate and reverse. Gives: "zyx...cbaZYX...CBA".
32f^  e# Take each character XOR 32 which swaps the case, so now we have:
      e#                               "ZYX...CBAzyx...cba"
er    e# Transliterate: substitute each character in the first string with the correspoding
      e# character in the second string.

Martin Ender

Posted 2016-01-03T19:25:51.527

Reputation: 184 808

4Well, I'm glad you were trying to help! That is the solution that I was trying to make, I just couldn't figure out the XOR. Nice Job! – GamrCorps – 2016-01-03T20:19:24.497

1SE's syntax highlighting hates esolangs. – Cyoce – 2016-01-05T06:58:47.420

@Cyoce They probably don't have time; given how many languages are on this site. That said, CJam is probably one of the easier ones, as it's not self-modifying and has a pretty clear structure. I'd like to see them try to add syntax-highlighting to a self-modifying language like ///. – Esolanging Fruit – 2017-05-07T05:22:40.850

@Challenger5 afaik, the syntax highlighting just uses Google's prettify, do support for various esolangs would have to be added there. – Martin Ender – 2017-05-07T05:24:25.533

10

Retina, 17 14 13 bytes

Code:

\T`w`_dZ-Az-a

Explanation:

\             # This suppresses the trailing linefeed
 T            # Switches to transliterate mode
  `w          # w is short for _0-9A-Za-z
    `_d       # d is short for 0-9
       Z-Az-a # Z-Az-a

This does some magic stuff and completes the task.

Try it here.

Adnan

Posted 2016-01-03T19:25:51.527

Reputation: 41 965

2Lucky you that I recently added \. Unlucky you that I didn't get around to adding character classes for letters and reversed character classes yet. – Martin Ender – 2016-01-03T20:19:41.630

@MartinBüttner Very lucky indeed, that almost invalidated my answer :) – Adnan – 2016-01-03T20:36:03.230

For reference, as of Retina 0.7.2 you could do \T\lL`RlRL`. – Martin Ender – 2016-01-07T11:11:29.137

9

Pyth, 10 9

uXGr;H)2z

Thanks to Jakube for saving a byte with the new feature of ;!

Test Suite

A quick explanation: reduce starting with the input over the numbers 0 and 1. The operation to be performed is translate the lower case alphabet with either r...0 or r...1 which are the lower and upper functions from python, respectively, applied to it, and then reversed.

FryAmTheEggman

Posted 2016-01-03T19:25:51.527

Reputation: 16 206

19 bytes due to a new feature (not even a day old): uXGr;H)2z – Jakube – 2016-01-03T20:05:28.400

5Can you add an explanation? – TanMath – 2016-01-03T20:20:35.013

1Can't you use X with the alphabet and then with the capitalized alphabet? – xnor – 2016-01-03T20:49:23.227

1@xnor XXzG)rG1? That seems to work. – lirtosiast – 2016-01-03T21:03:00.997

Or, maybe do X on the lowercase and uppercase alphabets concatenated, then swap case? That's probably longer, actually. – xnor – 2016-01-03T21:05:35.440

I'll post as CW. – lirtosiast – 2016-01-03T21:47:50.400

@xnor your second idea seems to give me 10: rXzsrBG1)2 – FryAmTheEggman – 2016-01-03T21:50:36.737

6

Julia, 74 61 47 bytes

s->replace(s,r"[a-z]"i,t->Char(31$Int(t[1])-4))

This is a lambda function that accepts a string and returns a string. To call it, assign it to a variable.

We match each letter using a regular expression and replace each letter with the ASCII character corresponding to 31 XOR the ASCII code for the letter, minus 4.

Alex A.

Posted 2016-01-03T19:25:51.527

Reputation: 23 761

Wow, this is very elegant. I get a deprecation warning for $ so you might want to update that to . Didn't know that you can use a function in replace. – niczky12 – 2018-04-13T14:33:11.907

5

Japt, 23 22 bytes

Ur"[A-Za-z]"_c +4^31 d

Try it online!

How it works

Ur"[A-Za-z]"_  // Take the input and replace each letter with:
 c +4          //  Take its char code and add 4. This results in
               //  the string      "ABC...XYZabc...xyz"
               //  becoming        "EFG...\]^efg...|}~".
 ^31           //  XOR the result by 31. This flips its last five 5 bits.
               //  We now have     "ZYX...CBAzyx...cba".
 d             //  Convert back from a char code.
               // Implicit: output last expression

ETHproductions

Posted 2016-01-03T19:25:51.527

Reputation: 47 880

Nice idea (which I borrowed...) to use XOR for this – Luis Mendo – 2016-01-04T01:12:53.293

5

C, 150 129 Bytes

void rev(char*s){int i,t;for(i=0;i<strlen(s);i++){t=s[i]+25;t=t<116?180-t:244-t;isalpha(s[i])?printf("%c",t):printf("%c",s[i]);}}

This function just converts char to int and adds the appropriate offset to the int before printing. I know it's not the shortest but I didn't see a C implementation.

Example usage

#include<stdio.h>
#include<string.h>
#include<ctype.h>

void rev(char*s){int i,temp;for(i=0;i<strlen(s);i++){temp=s[i]+25;temp=temp<116?180-temp:244-temp;isalpha(s[i])?printf("%c",temp):printf("%c",s[i]);}}


int main(){
   char *s = "hello, there";
   rev(s);
   return 0;
}

UPDATE: shortened a variable name.

Danwakeem

Posted 2016-01-03T19:25:51.527

Reputation: 141

Welcome to Programming Puzzles and Code Golf Stack Exchange! This is a very good approach. It could be golfed more by making all variables (including temp) exactly one character long. – wizzwizz4 – 2016-01-04T10:33:02.707

Ahh you are right! I will regolf this one – Danwakeem – 2016-01-04T10:35:30.367

If you need any help using some comment features like replying (@username), chat, notifications or anything else, feel free to just ask. (Anyone.) – wizzwizz4 – 2016-01-04T10:37:38.197

Okay will do! Thanks @wizzwizz4 – Danwakeem – 2016-01-04T10:40:24.747

1

Do you think you could have a go at my challenge? Analyse your Chair

– wizzwizz4 – 2016-01-04T10:54:25.350

@edc65 No need. The code would work without that (Assuming no extra compiler flags) – Spikatrix – 2016-01-04T12:35:45.700

1Yes it will work without the headers you just get a compiler warning @edc65 I figured since it compiles and runs it wouldn't be considered cheating but in real world use you should always include the headers. – Danwakeem – 2016-01-04T16:05:42.333

I will be sure to give your challenge a go sometime tonight. I have an idea for it. @wizzwizz4 – Danwakeem – 2016-01-04T16:22:20.687

1107 bytes: i,t;r(char*s){for(;i<strlen(s);i++){t=s[i]+25;t=t<116?180-t:244-t;isalpha(s[i])?putchar(t):putchar(s[i]);}} – Spikatrix – 2016-01-04T16:29:09.420

Oh yeah putchar that is a good call! Thanks @CoolGuy – Danwakeem – 2016-01-04T16:31:13.827

5

R, 69 61 bytes

Thanks to @Giuseppe for shaving off some extra bytes:

function(s)cat(chartr("a-zA-Z",intToUtf8(c(122:97,90:65)),s))

Previous version:

function(s)cat(chartr("a-zA-Z",rawToChar(as.raw(c(122:97,90:65))),s))

This is an anonymous function. Usage:

> f=function(s)cat(chartr("a-zA-Z",rawToChar(as.raw(c(122:97,90:65))),s))
> f("Hello, World!")
Svool, Dliow!
> f("Programming Puzzles & Code Golf")
Kiltiznnrmt Kfaaovh & Xlwv Tlou
> f("This is
+ a multiline
+ example.")
Gsrh rh
z nfogrormv
vcznkov.

plannapus

Posted 2016-01-03T19:25:51.527

Reputation: 8 610

1intToUtf8(c(122:97,90:65)) instead of the raw conversions, and you can get rid of the cat as well. I'm making it a bit of a habit to come golf 1+ year old answers of yours... – Giuseppe – 2017-09-07T14:31:30.990

5

C, 64

A void function that modify the string in place.

t(char*p){for(int c;c=*p;)*p++=c>64&c<91|c>96&c<123?(c^31)-4:c;}

Test: ideone

edc65

Posted 2016-01-03T19:25:51.527

Reputation: 31 086

1c;t(char*p){for(;c=*p;)*p++=c>64&c<91|c>96&c<123?(c^31)-4:c;} – Spikatrix – 2016-01-04T12:33:37.970

@CoolGuy right, but I don't like the global inside a function... it's just me – edc65 – 2016-01-04T12:59:52.243

Isn't this 64 bytes? – Downgoat – 2016-01-07T02:37:20.840

@Doᴡɴɢᴏᴀᴛ yes it is .. thanks .. – edc65 – 2016-01-07T07:05:11.640

4

Ruby, 40 bytes

New solution: Stole that bit flipping magic from some of the other posts here:

->s{s.gsub(/[a-z]/i){($&.ord+4^31).chr}}

Ruby, 55 46 bytes

->s{s.tr'a-zA-Z',[*?A..?Z,*?a..?z].reverse*''}

9 bytes off thanks to @manatwork


test run:

->s{s.gsub(/[a-z]/i){($&.ord+4^31).chr}}["Kiltiznnrmt Kfaaovh & Xlwv Tlou"]
=> "Programming Puzzles & Code Golf"

daniero

Posted 2016-01-03T19:25:51.527

Reputation: 17 193

4

Seriously, 31 bytes (non-competing)

úúû+╗úRúûR+╝,`;╜íuWD╛E(X0WX`Mεj

Hex Dump:

a3a3962bbba352a396522bbc2c603bbda1755744be452858305758604dee6a

Try It Online

Expl:

úúû+╗                             Put UPPERCASElowercase in reg0
     úRúûR+╝                      Put ESACREPPUesacrewol in reg1
            ,                     Fetch input.
             `             `Mεj   Map over the characters in string as list, joining result
              ;╜íu                Find 1-index of character in UPPERCASElowercase
                  W     0WX       If it is positive (present): 
                   D              Convert back to 0-index
                    ╛E            Look it up in ESACREPPUesacrewol
                      (X          Delete the original character.
                                  (Else just leave the original character unchanged.)

I just realized the spec say no additional whitespace, but there is no way to suppress trailing newlines in Seriously output, so there is no Seriously solution.

quintopia

Posted 2016-01-03T19:25:51.527

Reputation: 3 899

1What does ESACREPPUesacrewol mean? – Downgoat – 2016-01-03T20:56:51.793

3@Doᴡɴɢᴏᴀᴛ UPPERCASE reversed LOWERCASE reversed – Mama Fun Roll – 2016-01-03T21:01:28.527

2the reversed uppercase alphabet prepended to the reversed lowercase alphabet – quintopia – 2016-01-03T21:01:34.203

3

CJam, 21 bytes

q'[,65>__el_@+W%@@+er

Not an optimal solution... yet... Try it online

Its hard to explain without grouping things, so here is a general explanation: gets input, pushes uppercase alphabet twice and lowercase twice, rotates things around, combines uppercase and lowercase strings, reverses one, and uses transliteration (similar to the Retina answer).

GamrCorps

Posted 2016-01-03T19:25:51.527

Reputation: 7 058

Does this output a trailing newline? – LegionMammal978 – 2016-01-04T00:26:52.200

@LegionMammal978 It shouldn't unless aditsu changed how the stack is outputted. – GamrCorps – 2016-01-04T00:29:56.343

@LegionMammal978 I doesn't. – Martin Ender – 2016-01-04T10:05:14.847

3

Jolf, 15 bytes

~Ai+plpu+_pl_pu
~A              I don't know what to call this, besides "dictionary replace"
  i              the input
   +plpu         previous dictionary: lower + upper alphabet
        +_p1_pu  new dictionary: reversed lower + reversed upper

Test suite, or try it with your own input

Conor O'Brien

Posted 2016-01-03T19:25:51.527

Reputation: 36 228

The word for this is "transliteration," FYI. – a spaghetto – 2016-01-04T18:43:03.657

3

2, 12 chars / 26 bytes (non-competitive)

ïĪ(ᶐ+ᶛ,ᶐᴙ+ᶛᴙ

Try it here (Firefox only).

Added transliterate function after the challenge was posted.

Explanation

ïĪ(ᶐ+ᶛ,ᶐᴙ+ᶛᴙ // implicit: ï=input
ïĪ(           // transliterate ï...
   ᶐ+ᶛ,       // from uppercase+lowercase alphabet...
       ᶐᴙ+ᶛᴙ  // ... to reversed uppercase+reversed lowercase alphabet
              // implicit output

Mama Fun Roll

Posted 2016-01-03T19:25:51.527

Reputation: 7 234

I thought 2 was going to be called ∞? – Downgoat – 2016-01-03T22:01:20.350

1No, I decided to save that for a complementary (but different) language for . – Mama Fun Roll – 2016-01-03T22:02:11.203

IIRC There is a blackboard bold 2. – Conor O'Brien – 2016-01-04T18:46:40.093

@ՊՓԼՃՐՊՃՈԲՍԼ Call it ESMax (in doublestruck). – mbomb007 – 2016-01-04T20:35:37.493

3

C (function), 50

f(char*s){for(;*s;s++)*s=isalpha(*s)?*s+4^31:*s;}

This builds on all three previous C answers, so credit to @Ruud, @Danwakeem and @edc65.

This function modifies a char array in place.

My understanding is function entries are allowed unless explicitly banned in the question.

Try it online.

Digital Trauma

Posted 2016-01-03T19:25:51.527

Reputation: 64 644

3

PostgreSQL, 118 125 bytes

SELECT s,TRANSLATE(s,t||UPPER(t),REVERSE(t)||REVERSE(UPPER(t)))
FROM(SELECT text'Programming Puzzles & Code Golf's,text'abcdefghijklmnopqrstuvwxyz't)r

SqlFiddleDemo

Output:

╔══════════════════════════════════╦═════════════════════════════════╗
║                s                 ║            translate            ║
╠══════════════════════════════════╬═════════════════════════════════╣
║ Programming Puzzles & Code Golf  ║ Kiltiznnrmt Kfaaovh & Xlwv Tlou ║
╚══════════════════════════════════╩═════════════════════════════════╝

Input: SELECT text'...'s


EDIT:

Input as table:

SELECT s,TRANSLATE(s,t||UPPER(t),REVERSE(t)||REVERSE(UPPER(t)))
FROM i,(SELECT text'abcdefghijklmnopqrstuvwxyz't)r
GROUP BY s,t

SqlFiddleDemo

Output:

╔══════════════════════════════════╦═════════════════════════════════╗
║                s                 ║            translate            ║
╠══════════════════════════════════╬═════════════════════════════════╣
║ Hello, World!                    ║ Svool, Dliow!                   ║
║ Programming Puzzles & Code Golf  ║ Kiltiznnrmt Kfaaovh & Xlwv Tlou ║
║ abcdefghijklmnopqrstuvwxyz       ║ zyxwvutsrqponmlkjihgfedcba      ║
╚══════════════════════════════════╩═════════════════════════════════╝

lad2025

Posted 2016-01-03T19:25:51.527

Reputation: 379

Hey lad2025, I think this is shorter than 118, but I am no expert in the counting rules – t-clausen.dk – 2016-05-05T11:04:11.313

2

Python 3, 195 169 168 166 bytes

Thanks to @TrangOul for -2 bytes!

How didn't I see that I could have golfed that down before?

x=__import__('string').ascii_letters;y,z=x[26:],x[:26];a,b=y[::-1],z[::-1];print(''.join(b[z.index(i)]if i in b else a[y.index(i)]if i in a else i for i in input()))

(sorta) ungolfed:

x = __import__('string').ascii_letters;
y, z = x[26: ], x[: 26];
a, b = y[::-1], z[::-1];
print(''.join(b[z.index(i)]
    if i in b
    else a[y.index(i)]
    if i in a
    else i
    for i in input()
))

Try it on Ideone!

cat

Posted 2016-01-03T19:25:51.527

Reputation: 4 989

1You can save 2 bytes by removing the outermost [] from join. – Trang Oul – 2016-01-04T13:03:40.577

@TrangOul really? It's a list comprehension so I thought it needs to be a list or else you get generator object <genexpr> at..., but I will test it – cat – 2016-01-04T13:25:06.307

@TrangOul Nevermind, I learned something, thanks! – cat – 2016-01-04T13:26:13.137

Any iterable [containing str values] can be passed to join() function. – Trang Oul – 2016-01-04T13:42:34.267

2

Unix shell + tr + printf, 35 bytes

tr A-Za-z `printf %s {Z..A} {z..a}`

Here you are, a canonical answer in tr. I thought how could a question to transliterate the alphabet go without a canonical answer to transliterate the alphabet?

tr by itself does not even do a "Hello, World!" and as such isn't a programming language, so I marked the answer as noncompeting[1].

[1]: Edit: Actually, Unix shell is the language and tr is the standard library. Thanks to Downgoat and Digital Trauma for helping me spot this out.

user48538

Posted 2016-01-03T19:25:51.527

Reputation: 1 478

3I think its fine to claim shell or bash as a language, and common utilities (tr is in coreutils) as the standard library. See countless of my answers ;-) – Digital Trauma – 2016-01-04T15:54:19.153

1But it doesn't work: tr: range-endpoints of 'Z-A' are in reverse collating sequence order. I think you have to do something like tr A-Za-z $(printf %s {Z..A} {z..a}) (and replace $( ) with backticks) – Digital Trauma – 2016-01-04T15:55:18.147

@DigitalTrauma but not everyone has printf on their system. – user48538 – 2016-01-04T16:35:19.893

7

I think you'd have quite a hard time finding a Unix system that doesn't have printf - after all, its specified by Posix. Also its a builtin in bash which is pretty ubiquitous these days. Regardless, having something pre-installed on everyone's system is not a prerequisite for [tag:code-golf] - not everyone has CJam on their system either ;-)

– Digital Trauma – 2016-01-04T20:20:11.887

1The space between } and { is required - otherwise the expansion becomes something like Zz Zy Zx ... Za Yz ... Aa – Digital Trauma – 2016-01-07T19:06:49.777

2

Python, 61 bytes

lambda x:''.join([c,chr(ord(c)+4^31)][c.isalpha()]for c in x)

An anonymous function. On letters, does the reversing operation on the bit representation by adding 4, then flipping the last five bits, similar to ETHproductions' Javascript answer.

xnor

Posted 2016-01-03T19:25:51.527

Reputation: 115 687

Just wrote the exact same thing haha – sagiksp – 2017-05-07T05:25:47.373

2

Haskell, 119 104 bytes

Saved 15 bytes thanks to @nimi.

c=fromEnum;s=toEnum;f[]="";f(x:y)|64<c x&&c x<91=s(155-c x):f y|96<c x&&c x<123=s(219-c x):f y|0<1=x:f y

Usage:

f "abcdefghijklmnopqrstuvwxyz"
"zyxwvutsrqponmlkjihgfedcba"

f "Programming Puzzles & Code Golf"
"Kiltiznnrmt Kfaaovh & Xlwv Tlou"

f "Hello, World!"
"Svool, Dliow!"

Explanation

let c=fromEnum;s=toEnum;--wrap names for later use, fromEnum gets ascii code from char, toEnum gets char from ascii code
f[]=[];                 --feed empty list (of chars in this case), get empty list
f(x:y)                  --feed a list, separate the first element and...
|64<c x&&c x<91=        --if its an uppercase char (using ascii code range)...
s(c x*(-1)+155)         --  inverse its ascii code value, move it to the range of uppercase and get the new char
                        --  (like rotating half turn a ruler by the side and then sliding it to the space it previously occupied)
:f y                    --  feed the rest of the list and stick the new char in front of the result
|96<c x&&c x<123=       --if its a lowercase char (using ascii code range)...
s(c x*(-1)+219)         --  inverse its ascii code value, move it to the range of lowercase and get the new char
:f y                    --  feed the rest of the list and stick the new char in front of the result
|True=x:f y             --otherwise feed the rest of the list and stick the char in front of the result

I'm new to Haskell... to functional programming... and to the site, and i know there are (a lot of) better answers to this question, but bear with me.

fluffy ears

Posted 2016-01-03T19:25:51.527

Reputation: 21

Some golfing tips: a) no need to use let. Start directly with c=fromEnum. Use (155-c x) and (219-c x). c) Truecan be replaced by 1<2. -- The code fails to load for me with the "ambigious type variable" error for functions c and s (ghci 7.10.2), but this can easily be fixed with f[]="" instead of f[]=[]. – nimi – 2016-01-07T19:13:29.513

Thanks!, i was actually wondering if it was valid without "let", since it doesnt run directly on GHC. – fluffy ears – 2016-01-22T06:34:13.587

2

Perl 6, 28 bytes

{S:g/\w/{chr $/.ord+4+^31}/}

Usage:

# give it a lexical name
my &swap = { … }

say swap 'Programming Puzzles & Code Golf';
# Kiltiznnrmt Kfaaovh & Xlwv Tlou

say swap ('a'..'z').join
# zyxwvutsrqponmlkjihgfedcba

Brad Gilbert b2gills

Posted 2016-01-03T19:25:51.527

Reputation: 12 713

When I run this it says: Warning: Use of "ord" without parentheses is ambiguous at (eval 8)[/System/Library/Perl/5.18/perl5db.pl:732] line 2. I know nothing about perl so am I doing something wrong? How would I run this? – Downgoat – 2016-02-05T06:31:38.527

@Doᴡɴɢᴏᴀᴛ If you notice it says this is written in Perl 6 You can go to #perl6 on freenode and type m: my &swap = {S:g/\w/{chr $/.ord+4+^31}/}; say swap ('a'..'z').join

– Brad Gilbert b2gills – 2016-02-05T06:34:25.523

Ah okay, apparently I can't read :P – Downgoat – 2016-02-05T06:35:15.590

@Doᴡɴɢᴏᴀᴛ I added a note that you can test it on #perl6 on freenode – Brad Gilbert b2gills – 2016-02-05T06:36:35.160

2

Java, 136 bytes

void x(String i){for(char c:i.toCharArray()){if(Character.isLetter(c))c=c<91?(char)(90-(c-65)):(char)(122-(c-97));System.out.print(c);}}

Example usage:

class Test {
  static void x(String i){for(char c:i.toCharArray()){if(Character.isLetter(c))c=c<91?(char)(90-(c-65)):(char)(122-(c-97));System.out.print(c);}}
  public static void main(String[] args) {
    x("Programming Puzzles & Code Golf");
    // produces "Kiltiznnrmt Kfaaovh & Xlwv Tlou"
  }
}

Probably the worst commonly-used language in terms of byte size.

Sean

Posted 2016-01-03T19:25:51.527

Reputation: 41

1Java's is a meme here actually – Downgoat – 2016-02-05T19:55:17.347

I know this has been posted about 1.5 year ago, but you can golf quite a few things like this: void x(String i){for(Character c:i.toCharArray())System.out.print(c.isLetter(c)?(char)(c<91?90-(c-65):122-(c-97)):c);} (118 bytes) – Kevin Cruijssen – 2017-09-07T14:14:38.660

Or even shorter: void y(String i){for(int c:i.getBytes())System.out.print((char)(c>65&c<91|c>96&c<123?c<91?90-(c-65):122-(c-97):c));} (116 bytes) – Kevin Cruijssen – 2017-09-07T14:15:01.933

1@KevinCruijssen You can also rearrange the calculations to negate the need for parentheses by making 90-(c-65) into -c+65+90 and 122-(‌​c-97) into -c+97+122, which saves a byte each. – Zavada – 2017-09-09T05:03:24.417

2

05AB1E, 5 bytes [non-competing]

žnžo‡

Uses CP-1252 character set.

Try it online!

Explanation:

žn    - Push [A-Za-z]
  žo  - Push [Z-Az-a]
    ‡ - Transliterate.

George Gibson

Posted 2016-01-03T19:25:51.527

Reputation: 2 369

Why is this noncompeting? – Esolanging Fruit – 2017-05-07T05:24:10.567

1

PHP, 73 bytes

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

do this need any comments?

Titus

Posted 2016-01-03T19:25:51.527

Reputation: 13 814

1

Perl 5, 28 bytes

27 bytes of code + 1 for -p

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

Try it online!

Xcali

Posted 2016-01-03T19:25:51.527

Reputation: 7 671

1

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(

Luis Mendo

Posted 2016-01-03T19:25:51.527

Reputation: 87 464

1

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    

Fatalize

Posted 2016-01-03T19:25:51.527

Reputation: 32 976

1

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

Stewie Griffin

Posted 2016-01-03T19:25:51.527

Reputation: 43 471

1

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!

Hotkeys

Posted 2016-01-03T19:25:51.527

Reputation: 1 015

You can use *.trans(…) to make it shorter. – Brad Gilbert b2gills – 2016-02-05T06:04:53.230

1

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

Argenis García

Posted 2016-01-03T19:25:51.527

Reputation: 223

0

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.

Axel Matstoms

Posted 2016-01-03T19:25:51.527

Reputation: 61

Your A-z regex matches [\]^_\``, none of which should be modified. You'll probably wantA-Za-z`. – Martin Ender – 2016-11-21T15:33:44.807

0

PHP, 69 bytes

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

mapping stolen from ETHproductions

Titus

Posted 2016-01-03T19:25:51.527

Reputation: 13 814

0

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)

Magic Octopus Urn

Posted 2016-01-03T19:25:51.527

Reputation: 19 422

Implicit input... you can remove the I. – Oliver Ni – 2016-11-22T03:12:09.783

0

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!"

rnso

Posted 2016-01-03T19:25:51.527

Reputation: 1 635

0

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!

Pete Arden

Posted 2016-01-03T19:25:51.527

Reputation: 1 151

0

REXX, 88 bytes

b=xrange(a,z)
a=lower(b)
do forever
  parse pull n
  say translate(n,reverse(b||a),a||b)
end

idrougge

Posted 2016-01-03T19:25:51.527

Reputation: 641

0

JavaScript, 57 bytes

s=>{var k;for(var a=s.length-1;a>0;a--){k+=s[a]}return k}

thatoneuser

Posted 2016-01-03T19:25:51.527

Reputation: 23

1Does it work? How? s[s.length] === undefined – Tymek – 2017-05-06T11:12:19.507

0

Mathematica 89 Bytes

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

48 Bytes of this is just long function names

Kelly Lowder

Posted 2016-01-03T19:25:51.527

Reputation: 3 225

0

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))`

Waffle

Posted 2016-01-03T19:25:51.527

Reputation: 101

0

Jelly, 11 bytes

ØAµ,Uµ;Œsðy

Try it online!

fireflame241

Posted 2016-01-03T19:25:51.527

Reputation: 7 021

0

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.

Renzo

Posted 2016-01-03T19:25:51.527

Reputation: 2 260

0

PowerShell, 65 bytes

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

Try it online!

mazzy

Posted 2016-01-03T19:25:51.527

Reputation: 4 832

0

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!

Kai

Posted 2016-01-03T19:25:51.527

Reputation: 201

0

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

username.ak

Posted 2016-01-03T19:25:51.527

Reputation: 411

0

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

wflynny

Posted 2016-01-03T19:25:51.527

Reputation: 119

0

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]))

mbomb007

Posted 2016-01-03T19:25:51.527

Reputation: 21 944

0

Oracle SQL 11.2, 105 bytes

SELECT TRANSLATE(:1,a||UPPER(a),REVERSE(UPPER(a)||a))FROM(SELECT'abcdefghijklmnopqrstuvwxyz'a FROM DUAL);

Jeto

Posted 2016-01-03T19:25:51.527

Reputation: 1 601

0

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.

cat

Posted 2016-01-03T19:25:51.527

Reputation: 4 989