Tell me more ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

The challenge: To read an input of arbitrary length and produce the ROT13 of the input. All characters besides A-Z should be copied to the output verbatim, and case should be preserved if possible.

Any language that can read and write standard streams is fair game.

share|improve this question
3  
The problem shouldn't be a tag, so I removed ROT13, just an FYI – Nick Berardi Jan 27 '11 at 21:18
2  
Don't you mean A-Za-z (to count both upper- and lower-case) ? – Joey Adams Jan 27 '11 at 21:33
1  
and make sure they don't use rot13 in standard library? like the PHP one – SHiNKiROU Jan 28 '11 at 2:45
8  
Saying xor is not encryption is like saying a+b is not math. – Nakilon Jan 30 '11 at 19:02
1  
@Chris Jester-Young, I thought arithmetic is part of math ,.) – Nakilon Jan 30 '11 at 19:05
show 5 more comments

25 Answers

Canonical 23-character answer:

tr A-Za-z N-ZA-Mn-za-m
share|improve this answer
1  
I'm without access to bash at the moment, but I think this should work: tr A-za-m N-ZA-z (16 chars) – Nabb Feb 2 '11 at 7:24
1  
@Nabb: Nice to see you, GolfScript-meister! :-D I think your solution here would break the stipulation that "All characters besides A-Z should be copied to the output verbatim". – Chris Jester-Young Feb 2 '11 at 12:07
@Chris: Yep, looks like you're right. – Nabb Feb 3 '11 at 2:22
@Nabb: No, to me it looks as if he's wrong. Or may you show an example? – user unknown Feb 6 '11 at 5:56
1  
@user unknown: Type in [\\]^_` in the input. It will come back as NOPQRS rather than [\\]^_`, at least in the version of tr I have. (Those are the six characters in ASCII that lie between Z and a. Obviously, all other characters will work correctly.) – Chris Jester-Young Feb 6 '11 at 7:07
show 1 more comment

Ruby - 60 57 38 37 chars

Edit: And just realised Ruby strings have a tr method.

puts$<.read.tr'A-Za-z','N-ZA-Mn-za-m'

Test

input = "The challenge: To read an input of arbitrary length and produce the ROT13 of the input. All characters besides A-Z should be copied to the output verbatim, and case should be preserved if possible.

Any language that can read and write standard streams is fair game."

output = `echo '#{input}' | ruby golf-rot13.rb`

puts "Input:"
puts input
puts "-------"
puts "Output:"
puts output

Gives:

Input:
The challenge: To read an input of arbitrary length and produce the ROT13 of the input. All characters besides A-Z should be copied to the output verbatim, and case should be preserved if possible.

Any language that can read and write standard streams is fair game.
-------
Output:
Gur punyyratr: Gb ernq na vachg bs neovgenel yratgu naq cebqhpr gur EBG13 bs gur vachg. Nyy punenpgref orfvqrf N-M fubhyq or pbcvrq gb gur bhgchg ireongvz, naq pnfr fubhyq or cerfreirq vs cbffvoyr.

Nal ynathntr gung pna ernq naq jevgr fgnaqneq fgernzf vf snve tnzr.
share|improve this answer
You don't need the space after puts, and 'A-z' is a shortcut for 'A-Za-z' – Ventero Feb 2 '11 at 14:52
1  
@Ventro: Thanks, after a bit of testing it seems 'A-z' is actually 'A-Z[\]^_a-z', damn ascii having characters between Z` and a. – Nemo157 Feb 2 '11 at 20:50
Essentially the same but 35 characters: puts gets.tr'A-Za-z','N-ZA-Mn-za-m'. – Michael Kohl Mar 13 '11 at 23:43
@Michael: Except gets only returns the first line, using $<.read reads until EOF. The question doesn't say anything about whether the input can contain new lines so I just erred on the side of caution. – Nemo157 Mar 14 '11 at 0:22
Fair enough, but since the exercise specification only mentioned "arbitrary length" but said nothing about newlines, I'd rather err on the side of brevity in codegolf ;-) – Michael Kohl Mar 14 '11 at 7:32

Befunge - 7x30 = 210 6x26 = 156 characters

New streaming version that supports both upper and lower case and should support unlimited input.

v,<               <<     <
  ^-4-9<    >:"A"\`|
     >:"a"\`|     #>:"Z"`|
>~:0`| #    >:"z"`|
,    @ |    <`"m":<v`"M":<
^  +4+9<    ^      <

The old version

This stores the values inside its own source code. Really shows off how horrible it is to try and output stored values in the same order that you receive them. Only supports lowercase characters.

vp0p11:+1g11<      < <
v                    ^-4-9<
v    >:"a"\`|>:"z"`|>:"m"`|
>~:0`|      >^     >^#
                     ^+4+9<
     >$011g1+0p>12g1+:12p0g:v
               ^           ,_@

I'm not sure exactly what limitations this has, using http://www.quirkster.com/js/befunge.html as the interpreter it does appear to break with large inputs.

share|improve this answer
the link to the interpreter is dead – heinrich5991 Jul 17 '12 at 9:35

Python (117 bytes)

Here's a Python version that avoids the rot13()-method.

import sys
print"".join([chr(x/32*32+1+(x%32+12)%26if 64<x<91or 96<x<123 else x)for x in map(ord,sys.stdin.read())])
share|improve this answer
raw_input returns one line not all input. – Alexandru Jan 27 '11 at 23:34
you need to import sys and use sys.stdin.read(). – Alexandru Jan 27 '11 at 23:41
@Alexandru: will do – JPvdMerwe Jan 27 '11 at 23:46

Bash - 5 chars

rot13

 

share|improve this answer
8  
Two downvotes so far (with no comments), but no downvotes for the question. I assume that means it's ok to ask trivial codegolfs but not to give the trivial answer. Harder codegolfs please! – gnibbler Jan 30 '11 at 20:49
7  
Which bash-version? I don't have a build-in rot13. bash --version GNU bash, Version 4.0.33(1)-release (i486-pc-linux-gnu) – user unknown Feb 6 '11 at 5:21
2  
I'd have submitted this as rot13 - 0 chars... ;) – boothby Mar 9 at 18:10

I've got 34 chars on python:

print raw_input().encode('rot13')
share|improve this answer
1  
-1 I think it is cheating that you are using a built in library. – Glenn Nelson Jan 27 '11 at 21:23
3  
I've used them in every code golf I took part in... Also if using python's standard lib is cheating, how is using tr not? – Juan Jan 27 '11 at 21:27
1  
@Juan: There's no real "hard line", but a lot of it is about how specific the library is. Using transliteration to carry out ROT13 is fine, using the ROT13 builtin is cheating (or at best, a "joke solution"). – Anon. Jan 27 '11 at 21:33
1  
@Anon In any case, it's an anwser you just ignore.. It's not off target, there's not any rules set by the OP nor by the community. Sure, maybe mine is not an award winning solution, like the one using tr that kicks ass. But it's not a joke, I'm leveraging the power of python to reduce the count, just like any other would do. – Juan Jan 27 '11 at 21:37
5  
@Glenn, I think library functions are fair game. It's up to the golf question to be interesting enough to not be in anyone's library or to specifically exclude. – gnibbler Jan 28 '11 at 2:09
show 3 more comments

C - 83 79 characters

main(c,b){while((c=getchar())>=0)b=c&96,putchar(isalpha(c)?b+1+(c-b+12)%26:c);}

Readable version:

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

int main(void)
{
    int c, base;

    while ((c = getchar()) >= 0) {
        if (isalpha(c)) {
            base = (c & 96) + 1; /* First letter of the upper or lower case. */
            c = base + (c - base + 13) % 26;
        }
        putchar(c);
    }

    return 0;
}
share|improve this answer
1  
Are you including the headers you include in your count? – JPvdMerwe Jan 27 '11 at 22:18
@JPvdMerwe: I didn't include any headers in the golfed version, nor did I need to. – Joey Adams Jan 27 '11 at 22:34
You can use the coma operator before putchar to remove a pair of braces. – Alexandru Jan 27 '11 at 23:05
Could you explain main(c,b)? It's the first time i see this. – Alexandru Jan 27 '11 at 23:11
2  
@Alexandru most C compilers support main with any parameters. Also, the original C standard defines that an argument with no type is an int. Thus you get to declare ints without actually writing int. – Juan Jan 27 '11 at 23:31
show 3 more comments

tr/// solution in Perl (39 characters), boilerplate can be removed with -p:

while(<>){y/a-zA-Z/n-za-mN-ZA-M/;print}

Using -p (23 characters including the extra switch):

perl -pe'y/a-zA-Z/n-za-mN-ZA-M/'
share|improve this answer
Add 1 char for the p, but please remove the boilerplate! – J B Feb 6 '11 at 21:04

DC (111 108 for the dc itself)

Ok, here it is in (mostly) dc and some sed and od magic to get it into the right format for the code. If you don't count the input thing (echo -n MESSAGE |) it's 160 bytes:

od -An -t dC|sed 's/^\ *//;s/\ \{2,3\}/\n/g'|dc -e'[13+26%]sm[65-lmx65+]su[97-lmx97+]sl[96<b64<dPc]sa[91>c]sd[123>e]sb[lux]sc[llxdd]se[ddddlaxlrx]sy[?z0<y]dsrx'

As a point of interest, the dc programme itself is only a 108 bytes long, shorter than the non-library python version. It even preserves case and punctuation, and beats Javascript in the above submission! If only I could better parse the output of od, or better yet replace it altogether.

EDIT: It's worth noting that the question doesn't indicate a trailing new line 10P which saves me three further bytes.

EDIT 2: There's no specification for the format of the input, so I assume it's taken in as is convenient for my programme :P

share|improve this answer

Perl6 (54)

$*IN.lines».trans("a..zA..Z"=>"n..za..mN..ZA..M").say
share|improve this answer

Haskell, 100 characters

a%b=([a..b]++)
main=interact$map$toEnum.((0%64$78%90$65%77$91%96$110%122$97%109$[123..])!!).fromEnum
share|improve this answer

Javascript (177)

This assumes that there are two functions, print and readLine:

f=String.fromCharCode;print(readLine().replace(/[a-z]/g,function(a){return f((a.charCodeAt(0)-84)%25+97);}).replace(/[A-Z]/g,function(a){return f((a.charCodeAt(0)-52)%25+65);}))
share|improve this answer

PHP - 41 Characters

while($r=fgets(STDIN))echo str_rot13($r);
share|improve this answer
1  
-1 for rep-whoring. – Raynos Feb 3 '11 at 21:39

PHP - 103 98 80 characters

(not using str_rot13())

<?=preg_replace('#[a-zA-Z]#e','chr(($x=ord("\0"))-$x%32+1+($x%32+12)%26)',`cat`);
share|improve this answer

Delphi, 110

var c:Char;begin repeat Read(c);Write(Chr(Ord(c)+(Ord(c in['A'..'M'])-Ord(c in['N'..'Z']))*13));until EOF;end.
share|improve this answer
var c:Char;begin repeat Read(c);Write(Chr(Ord(c)+(Ord(c in['A'..'M'])-Ord(c in['N'..'Z']))*13));until EOF;end. saves one character :) – Wouter van Nifterick Mar 13 '11 at 21:36
@Wouter van Nifterick : Good spot! I'll update it accordingly – PatrickvL Mar 13 '11 at 23:28

Java 251 chars

public class r{public static void main(String[] a){String s = a[0];for(int i=0;i<s.length();){char c=s.charAt(i++);if(c>='a'&&c<='m')c+=13;else if(c>='n'&&c<='z')c-= 13;else if(c>='A'&&c<='M')c+=13;else if(c>='A'&&c <='Z')c-=13;System.out.print(c);}}}
share|improve this answer

Python 3 (107)

Ok, I promise to stop answering this question now, but I felt compelled to beat the DC answer in Python. This probably reflects poorly on me as a person :).

import sys;[print(x.isalpha()and chr((ord(x)&96)+1+(ord(x)%32+12)%26)or x,end='')for x in sys.stdin.read()]
share|improve this answer

Haskell - 112 characters

r l=drop 13 l++take 13 l
t=['a'..'z']
s=['A'..'Z']
main=interact$map(\x->maybe x id$lookup x$zip(t++s)$r t++r s)
share|improve this answer

JavaScript 1.8, 106

alert(prompt().replace(/\w/g,function(c)String.fromCharCode(c.charCodeAt()+(c.toLowerCase()<'n'?13:-13))))

JavaScript, 115

alert(prompt().replace(/\w/g,function(c){return String.fromCharCode(c.charCodeAt()+(c.toLowerCase()<'n'?13:-13))}))

This solution solves the problem by adding 13 to the character code if the character in question is in the first half of the alphabet, or subtracting 13 if it's in the second half.

share|improve this answer

C: 69 68 characters

Alright, I know this thread is long dead, but I couldn't stand the (long) C-solution which doesn't even compile on Clang (but does on GCC).

main(c){putchar(isalpha(c=getchar())*((c|32)<110?13:-13)+c);main();}

It is probably almost still squeezable. It certainly was squeezable. And not only was it squeezable, it was possible to make it recursive.

share|improve this answer

PHP – 18 characters

str_rot13('text');
share|improve this answer
I think it is cheating that you are using a built in library. – oenone Aug 15 '11 at 13:02
1  
@oenone If using a built-in library is cheating, how is using tr not cheating? The OP didn't say we can't use built-in libraries. – nyuszika7h Aug 15 '11 at 18:53

Scala 108

def m(a:Int,z:Int,c:Int)=if(c>=a&&c<z)a+((c-a+13)%26)else c
"Ok?".map(c=>print(m(65,91,m(97,123,c)).toChar))

ungolfed:

def m (a: Int, z:Int, c:Int) = if (c >= a && c <= z) a+((c-a+13)%26) else c
"Ok?".foreach (c => print (m ('A', 'Z', m ('a', 'z', c)).toChar))

result:

Bx?
share|improve this answer

Mathematica 102

StringReplace[Input[],
Join@@Table[Rule@@FromCharacterCode/@{i+c,Mod[i+13,26]+c},{c,{65,97}},{i,0,25}]]
share|improve this answer

K, 31

{x^(,/{x!(13_x),13#x}'.Q`A`a)x}
share|improve this answer

Tcl, 74 chars

package require [set c tcl::transform::rot];$c 13 stdin;fcopy stdin stdout
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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