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 code-golf so shortest code in bytes wins
-
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– cat2016年01月03日 19:31:40 +00:00Commented Jan 3, 2016 at 19:31
-
13\$\begingroup\$ Some Trivia: this is Atbash, a known cipher as old as the bible. \$\endgroup\$Jacob– Jacob2016年01月04日 09:21:05 +00:00Commented 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– Bart2016年01月05日 22:03:57 +00:00Commented Jan 5, 2016 at 22:03
-
1\$\begingroup\$ Kiltiznnrmt Kfaaovh & Xlwv Tlou should be the new site for "Programming Trivials & Code Bowling"... \$\endgroup\$Erik the Outgolfer– Erik the Outgolfer2016年08月03日 17:09:14 +00:00Commented 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\$Esolanging Fruit– Esolanging Fruit2017年05月07日 05:32:07 +00:00Commented May 7, 2017 at 5:32
60 Answers 60
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.
-
\$\begingroup\$ This was the most extreme compact program that does something remarkably amazing like this! @Ruud Helderman this was extremely well done! \$\endgroup\$Jane– Jane2021年02月17日 17:45:29 +00:00Commented Feb 17, 2021 at 17:45
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.
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...
-
1\$\begingroup\$ +1 for mentioning JS's excruciatingly long property names. My favorite is still the infamous
document.getElementById\$\endgroup\$Cyoce– Cyoce2016年01月05日 07:04:47 +00:00Commented Jan 5, 2016 at 7:04 -
2\$\begingroup\$ @Cyoce Try
document.getElementsByClassNameor, on Firefox and Chrome,document.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC\$\endgroup\$Ismael Miguel– Ismael Miguel2016年01月06日 10:28:58 +00:00Commented Jan 6, 2016 at 10:28 -
\$\begingroup\$ This seems to only be 66 bytes not 67 \$\endgroup\$Downgoat– Downgoat2016年01月06日 23:28:06 +00:00Commented Jan 6, 2016 at 23:28
-
\$\begingroup\$ It looks like you are missing a closing bracket on the end of the golfed code. \$\endgroup\$starbeamrainbowlabs– starbeamrainbowlabs2016年01月07日 06:56:58 +00:00Commented Jan 7, 2016 at 6:56
-
\$\begingroup\$ @starbeamrainbowlabs Thanks! I wondered why I had miscounted... \$\endgroup\$ETHproductions– ETHproductions2016年01月07日 15:20:32 +00:00Commented Jan 7, 2016 at 15:20
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
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.
-
4\$\begingroup\$ Well, 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! \$\endgroup\$GamrCorps– GamrCorps2016年01月03日 20:19:24 +00:00Commented Jan 3, 2016 at 20:19
-
1\$\begingroup\$ SE's syntax highlighting hates esolangs. \$\endgroup\$Cyoce– Cyoce2016年01月05日 06:58:47 +00:00Commented Jan 5, 2016 at 6:58
-
\$\begingroup\$ @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 ///. \$\endgroup\$Esolanging Fruit– Esolanging Fruit2017年05月07日 05:22:40 +00:00Commented May 7, 2017 at 5:22
-
\$\begingroup\$ @Challenger5 afaik, the syntax highlighting just uses Google's prettify, do support for various esolangs would have to be added there. \$\endgroup\$Martin Ender– Martin Ender2017年05月07日 05:24:25 +00:00Commented May 7, 2017 at 5:24
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.
-
2\$\begingroup\$ Lucky you that I recently added
\. Unlucky you that I didn't get around to adding character classes for letters and reversed character classes yet. \$\endgroup\$Martin Ender– Martin Ender2016年01月03日 20:19:41 +00:00Commented Jan 3, 2016 at 20:19 -
\$\begingroup\$ @MartinBüttner Very lucky indeed, that almost invalidated my answer :) \$\endgroup\$Adnan– Adnan2016年01月03日 20:36:03 +00:00Commented Jan 3, 2016 at 20:36
-
\$\begingroup\$ For reference, as of Retina 0.7.2 you could do
\T`lL`RlRL. \$\endgroup\$Martin Ender– Martin Ender2016年01月07日 11:11:29 +00:00Commented Jan 7, 2016 at 11:11
Pyth, (削除) 10 (削除ここまで) 9
uXGr;H)2z
Thanks to Jakube for saving a byte with the new feature of ;!
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.
-
1\$\begingroup\$ 9 bytes due to a new feature (not even a day old):
uXGr;H)2z\$\endgroup\$Jakube– Jakube2016年01月03日 20:05:28 +00:00Commented Jan 3, 2016 at 20:05 -
5\$\begingroup\$ Can you add an explanation? \$\endgroup\$TanMath– TanMath2016年01月03日 20:20:35 +00:00Commented Jan 3, 2016 at 20:20
-
1\$\begingroup\$ Can't you use
Xwith the alphabet and then with the capitalized alphabet? \$\endgroup\$xnor– xnor2016年01月03日 20:49:23 +00:00Commented Jan 3, 2016 at 20:49 -
1\$\begingroup\$ @xnor
XXzG)rG1? That seems to work. \$\endgroup\$lirtosiast– lirtosiast2016年01月03日 21:03:00 +00:00Commented Jan 3, 2016 at 21:03 -
\$\begingroup\$ Or, maybe do X on the lowercase and uppercase alphabets concatenated, then swap case? That's probably longer, actually. \$\endgroup\$xnor– xnor2016年01月03日 21:05:35 +00:00Commented Jan 3, 2016 at 21:05
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.
-
\$\begingroup\$ 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 inreplace. \$\endgroup\$niczky12– niczky122018年04月13日 14:33:11 +00:00Commented Apr 13, 2018 at 14:33
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.
-
\$\begingroup\$ Just wrote the exact same thing haha \$\endgroup\$sagiksp– sagiksp2017年05月07日 05:25:47 +00:00Commented May 7, 2017 at 5:25
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.
-
\$\begingroup\$ 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. \$\endgroup\$wizzwizz4– wizzwizz42016年01月04日 10:33:02 +00:00Commented Jan 4, 2016 at 10:33 -
\$\begingroup\$ Ahh you are right! I will regolf this one \$\endgroup\$Danwakeem– Danwakeem2016年01月04日 10:35:30 +00:00Commented Jan 4, 2016 at 10:35
-
1\$\begingroup\$ Do you think you could have a go at my challenge? Analyse your Chair \$\endgroup\$wizzwizz4– wizzwizz42016年01月04日 10:54:25 +00:00Commented Jan 4, 2016 at 10:54
-
1\$\begingroup\$ Yes 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. \$\endgroup\$Danwakeem– Danwakeem2016年01月04日 16:05:42 +00:00Commented Jan 4, 2016 at 16:05
-
1\$\begingroup\$ 107 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]);}}\$\endgroup\$Spikatrix– Spikatrix2016年01月04日 16:29:09 +00:00Commented Jan 4, 2016 at 16:29
Japt, (削除) 23 (削除ここまで) 22 bytes
Ur"[A-Za-z]"_c +4^31 d
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
-
\$\begingroup\$ Nice idea (which I borrowed...) to use XOR for this \$\endgroup\$Luis Mendo– Luis Mendo2016年01月04日 01:12:53 +00:00Commented Jan 4, 2016 at 1:12
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
-
1\$\begingroup\$
c;t(char*p){for(;c=*p;)*p++=c>64&c<91|c>96&c<123?(c^31)-4:c;}\$\endgroup\$Spikatrix– Spikatrix2016年01月04日 12:33:37 +00:00Commented Jan 4, 2016 at 12:33 -
\$\begingroup\$ @CoolGuy right, but I don't like the global inside a function... it's just me \$\endgroup\$edc65– edc652016年01月04日 12:59:52 +00:00Commented Jan 4, 2016 at 12:59
-
\$\begingroup\$ Isn't this 64 bytes? \$\endgroup\$Downgoat– Downgoat2016年01月07日 02:37:20 +00:00Commented Jan 7, 2016 at 2:37
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.
-
1\$\begingroup\$
intToUtf8(c(122:97,90:65))instead of therawconversions, and you can get rid of thecatas well. I'm making it a bit of a habit to come golf 1+ year old answers of yours... \$\endgroup\$Giuseppe– Giuseppe2017年09月07日 14:31:30 +00:00Commented Sep 7, 2017 at 14:31
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"
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
-
\$\begingroup\$ The word for this is "transliteration," FYI. \$\endgroup\$a spaghetto– a spaghetto2016年01月04日 18:43:03 +00:00Commented Jan 4, 2016 at 18:43
ESMin 2, 12 chars / 26 bytes (non-competitive)
ïĪ(ᶐ+ɒ,ᶐᴙ+ɒᴙ
Added transliterate function after the challenge was posted.
Explanation
ïĪ(ᶐ+ɒ,ᶐᴙ+ɒᴙ // implicit: ï=input
ïĪ( // transliterate ï...
ᶐ+ɒ, // from uppercase+lowercase alphabet...
ᶐᴙ+ɒᴙ // ... to reversed uppercase+reversed lowercase alphabet
// implicit output
-
\$\begingroup\$ I thought ESMin 2 was going to be called ES ∞? \$\endgroup\$Downgoat– Downgoat2016年01月03日 22:01:20 +00:00Commented Jan 3, 2016 at 22:01
-
1\$\begingroup\$ No, I decided to save that for a complementary (but different) language for ESMin. \$\endgroup\$Mama Fun Roll– Mama Fun Roll2016年01月03日 22:02:11 +00:00Commented Jan 3, 2016 at 22:02
-
\$\begingroup\$ IIRC There is a blackboard bold 2. \$\endgroup\$Conor O'Brien– Conor O'Brien2016年01月04日 18:46:40 +00:00Commented Jan 4, 2016 at 18:46
-
\$\begingroup\$ @ՊՓԼՃՐՊՃՈԲՍԼ Call it ESMax (in doublestruck). \$\endgroup\$mbomb007– mbomb0072016年01月04日 20:35:37 +00:00Commented Jan 4, 2016 at 20:35
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).
-
\$\begingroup\$ Does this output a trailing newline? \$\endgroup\$LegionMammal978– LegionMammal9782016年01月04日 00:26:52 +00:00Commented Jan 4, 2016 at 0:26
-
\$\begingroup\$ @LegionMammal978 It shouldn't unless aditsu changed how the stack is outputted. \$\endgroup\$GamrCorps– GamrCorps2016年01月04日 00:29:56 +00:00Commented Jan 4, 2016 at 0:29
-
\$\begingroup\$ @LegionMammal978 I doesn't. \$\endgroup\$Martin Ender– Martin Ender2016年01月04日 10:05:14 +00:00Commented Jan 4, 2016 at 10:05
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.
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
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
Output:
╔══════════════════════════════════╦═════════════════════════════════╗
║ s ║ translate ║
╠══════════════════════════════════╬═════════════════════════════════╣
║ Hello, World! ║ Svool, Dliow! ║
║ Programming Puzzles & Code Golf ║ Kiltiznnrmt Kfaaovh & Xlwv Tlou ║
║ abcdefghijklmnopqrstuvwxyz ║ zyxwvutsrqponmlkjihgfedcba ║
╚══════════════════════════════════╩═════════════════════════════════╝
-
\$\begingroup\$ Hey lad2025, I think this is shorter than 118, but I am no expert in the counting rules \$\endgroup\$t-clausen.dk– t-clausen.dk2016年05月05日 11:04:11 +00:00Commented May 5, 2016 at 11:04
05AB1E, 5 bytes
žnžo‡
Uses CP-1252 character set.
Explanation:
žn - Push [A-Za-z]
žo - Push [Z-Az-a]
‡ - Transliterate.
-
\$\begingroup\$ Why is this noncompeting? \$\endgroup\$Esolanging Fruit– Esolanging Fruit2017年05月07日 05:24:10 +00:00Commented May 7, 2017 at 5:24
Seriously, 31 bytes
úúû+╗úRúûR+╝,`;╜íuWD╛E(X0WX`Mεj
Hex Dump:
a3a3962bbba352a396522bbc2c603bbda1755744be452858305758604dee6a
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.
-
1\$\begingroup\$ What does
ESACREPPUesacrewolmean? \$\endgroup\$Downgoat– Downgoat2016年01月03日 20:56:51 +00:00Commented Jan 3, 2016 at 20:56 -
3\$\begingroup\$ @Doᴡɴɢᴏᴀᴛ UPPERCASE reversed LOWERCASE reversed \$\endgroup\$Mama Fun Roll– Mama Fun Roll2016年01月03日 21:01:28 +00:00Commented Jan 3, 2016 at 21:01
-
2\$\begingroup\$ the reversed uppercase alphabet prepended to the reversed lowercase alphabet \$\endgroup\$quintopia– quintopia2016年01月03日 21:01:34 +00:00Commented Jan 3, 2016 at 21:01
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()
))
-
1\$\begingroup\$ You can save 2 bytes by removing the outermost
[]fromjoin. \$\endgroup\$Trang Oul– Trang Oul2016年01月04日 13:03:40 +00:00Commented Jan 4, 2016 at 13:03 -
\$\begingroup\$ @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 \$\endgroup\$cat– cat2016年01月04日 13:25:06 +00:00Commented Jan 4, 2016 at 13:25 -
\$\begingroup\$ Any iterable [containing
strvalues] can be passed tojoin()function. \$\endgroup\$Trang Oul– Trang Oul2016年01月04日 13:42:34 +00:00Commented Jan 4, 2016 at 13:42
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]))
This last line would also work, since string is imported:
f=lambda x:translate(x,maketrans(u+l,u[::-1]+l[::-1]))
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.
-
\$\begingroup\$ Some golfing tips: a) no need to use
let. Start directly withc=fromEnum. Use(155-c x)and(219-c x). c)Truecan be replaced by1<2. -- The code fails to load for me with the "ambigious type variable" error for functionscands(ghci 7.10.2), but this can easily be fixed withf[]=""instead off[]=[]. \$\endgroup\$nimi– nimi2016年01月07日 19:13:29 +00:00Commented Jan 7, 2016 at 19:13 -
\$\begingroup\$ Thanks!, i was actually wondering if it was valid without "let", since it doesnt run directly on GHC. \$\endgroup\$fluffy ears– fluffy ears2016年01月22日 06:34:13 +00:00Commented Jan 22, 2016 at 6:34
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
-
\$\begingroup\$ 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? \$\endgroup\$Downgoat– Downgoat2016年02月05日 06:31:38 +00:00Commented Feb 5, 2016 at 6:31 -
\$\begingroup\$ @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\$\endgroup\$Brad Gilbert b2gills– Brad Gilbert b2gills2016年02月05日 06:34:25 +00:00Commented Feb 5, 2016 at 6:34 -
\$\begingroup\$ Ah okay, apparently I can't read :P \$\endgroup\$Downgoat– Downgoat2016年02月05日 06:35:15 +00:00Commented Feb 5, 2016 at 6:35
-
\$\begingroup\$ @Doᴡɴɢᴏᴀᴛ I added a note that you can test it on #perl6 on freenode \$\endgroup\$Brad Gilbert b2gills– Brad Gilbert b2gills2016年02月05日 06:36:35 +00:00Commented Feb 5, 2016 at 6:36
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.
-
1\$\begingroup\$ Java's is a meme here actually \$\endgroup\$Downgoat– Downgoat2016年02月05日 19:55:17 +00:00Commented Feb 5, 2016 at 19:55
-
\$\begingroup\$ 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) \$\endgroup\$Kevin Cruijssen– Kevin Cruijssen2017年09月07日 14:14:38 +00:00Commented Sep 7, 2017 at 14:14 -
\$\begingroup\$ 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) \$\endgroup\$Kevin Cruijssen– Kevin Cruijssen2017年09月07日 14:15:01 +00:00Commented Sep 7, 2017 at 14:15 -
1\$\begingroup\$ @KevinCruijssen You can also rearrange the calculations to negate the need for parentheses by making
90-(c-65)into-c+65+90and122-(c-97)into-c+97+122, which saves a byte each. \$\endgroup\$Zavada– Zavada2017年09月09日 05:03:24 +00:00Commented Sep 9, 2017 at 5:03
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.
-
3\$\begingroup\$ I think its fine to claim shell or bash as a language, and common utilities (
tris in coreutils) as the standard library. See countless of my answers ;-) \$\endgroup\$Digital Trauma– Digital Trauma2016年01月04日 15:54:19 +00:00Commented Jan 4, 2016 at 15:54 -
1\$\begingroup\$ But it doesn't work:
tr: range-endpoints of 'Z-A' are in reverse collating sequence order. I think you have to do something liketr A-Za-z $(printf %s {Z..A} {z..a})(and replace$( )with backticks) \$\endgroup\$Digital Trauma– Digital Trauma2016年01月04日 15:55:18 +00:00Commented Jan 4, 2016 at 15:55 -
\$\begingroup\$ @DigitalTrauma but not everyone has printf on their system. \$\endgroup\$user48538– user485382016年01月04日 16:35:19 +00:00Commented Jan 4, 2016 at 16:35
-
7\$\begingroup\$ 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 code-golf - not everyone has CJam on their system either ;-) \$\endgroup\$Digital Trauma– Digital Trauma2016年01月04日 20:20:11 +00:00Commented Jan 4, 2016 at 20:20 -
1\$\begingroup\$ The space between
}and{is required - otherwise the expansion becomes something likeZz Zy Zx ... Za Yz ... Aa\$\endgroup\$Digital Trauma– Digital Trauma2016年01月07日 19:06:49 +00:00Commented Jan 7, 2016 at 19:06
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
PHP, 73 bytes
<?=strtr($argv[1],($b=strtolower($a=join(range(A,Z)))).$a,strrev($a.$b));
do this need any comments?
PowerShell, 65 bytes
-join($args|% t*y|%{[char]($_,(($_-bxor31)-4))[$_-match'[a-z]']})