Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Write some code in any language that inputs a string such as "Today is a great day" (Note that there is no punctuation) and converts it to the "Secret Language". Here are the rules for the "Secret Language".

  • a=c, b=d, c=e and so on (y=a and z=b)
  • separate each word by a space
  • make sure there is proper capitalization


Input: "Today is a great day"

Output: "Vqfca ku c itgcv fca"

It is a popularity-contest. Other users should give points by looking for most "to the point" yet "unique" code.

CHALLENGE: I was looking up uncommon programming languages and I found a language called Piet (esolang). I challenge anyone to write it in this language.

share|improve this question
Shouldn't that be x=z, y=a, z=b? – squeamish ossifrage Feb 16 '14 at 0:46
you are right "duh" :) – Vik P Feb 16 '14 at 0:47
I was confused until I realized a=c is a -> c. – Justin Feb 16 '14 at 4:10
In other words, ROT2 it – Tobias Kienzler Feb 16 '14 at 8:39
Both rot13 and rot2 are both Caesar ciphers with different keys (13 and 2). – Sylwester Feb 16 '14 at 15:42

31 Answers 31

Smalltalk (Smalltalk/X), 29 27 chars

I am lucky - it is already in the String class:

'Today is a great day' rot:2
    -> 'Vqfca ku c itgcv fca'

adding I/O, this makes it:

(Stdin nextLine rot:2)print

in the spirit of doorknob's obfuscated example below, how about:

Parser evaluate:('(Uvfkp pgzvNkpg tqv:2)rtkpvPN' rot:-2)
share|improve this answer
I never thought I'd see a Smalltalk solution! – Toothbrush Feb 16 '14 at 22:46

Ruby, obfuscated edition (with commentary included!)

I suggest reading the entire thing; I find it quite amusing ;)

$s='';class Module;def const_missing c


              # My commentary ;)

ZZZY          # ?
YAYYY         # Oookay; you seem excited
Yaz           # Typo?
Yay           # Better
JEEEEEEF      # You misspelled Jeff's name
LAZZZY        # Yes, you are very lazy
Yax           # Another typo...
LLAMA         # Definitely not completely random at all...
EEEEEEEEEEEEE # Ouch my ears
IIIII         # Ouch stop
YUMMY         # ... you eat keyboards?
IIIII         # Stop!
YUMMYY        # Why are you eating your keyboard
LLAMA         # That doesn't make sense :(
VV            # :(
LLAMA         # Could you stop saying that?!
CODEGOLF      # Yay, one of my favorite SE sites! :D
VW            # I don't drive
ASDFASDFASDF  # Why do you keep banging on your keyboard?!?!
VVV           # Stop
HELLOo        #'s a little late for a greeting, isn't it?
DOGS          # ...
OOOOOo        # No, you're not a ghost.
HELLOOOO      # Just a *bit* late.
NNNNNNN       # Huh?
LLAMA         # I said to stop.

print eval$s

Hints on how it works (spoilers, hover to show):

This code builds a string and then evaluates it.

It uses const_missing in order to build the string character by character.

The string it ends up building is'A-Za-z','C-ZABc-zab'.

share|improve this answer
The commentary reads like some of the chats in this question:… – Hosch250 Feb 17 '14 at 3:15


The HQ requires, that from now on all agents shall receive communication in printed form only (as electronic channels proved too unreliable) using special top secret font. It is your responsibility to include this top secret procedure into prologue of our printing software:

/define_Secret_font {
    /Coronet findfont dup 
    /Encoding get 
    aload pop 256 array astore 
    /secret_proc {
        2 copy
        26 getinterval aload pop 
        26 -2 roll 26 array astore
    } def
    dup 65 secret_proc
    dup 97 secret_proc
    exch dup length dict dup
    3 -1 roll {put dup} forall
    exch /Encoding 4 -1 roll put 
    definefont pop
} def

And only that font is allowed, e.g.:

/Secret_font 36 selectfont
0 841 translate
20 -60 moveto
(Today is a great day) show
20 -120 moveto
(Programming Puzzles & Code Golf) show

And that's what it prints: enter image description here

share|improve this answer



tr A-Za-z C-ZABc-zab


$ tr A-Za-z C-ZABc-zab <<< "Today is a great day"
Vqfca ku c itgcv fca
share|improve this answer
I think you don't need the quotes. – marinus Feb 16 '14 at 11:20
@marinus You're right, I'll change it. – daniero Feb 16 '14 at 12:15

DFSORT (IBM Mainframe sorting program)


No SORT control statement can start in column one.

For the above to work on its own, you'd have to change the default installation alternate translation table, to offset all values for upper- and lower-case letters, wrapping around the final two letters.

Without changing the default table, it would require an ALTSEQ statement listing all the required pairs of hex values (from-hex-code immediately followed by to-hex-code, each pair of hex values separated by a comma):

 ALTSEQ CODE=(xxyy,...)

So to get upper-case EBCDIC A to C and B to D:


For the whole thing, that would be a lot of error-prone typing, of course, so you'd use another SORT step to generate the control cards for this step, and let SORT read them from the dataset created by that new step.

Of course, for any language which supports a "translation table", it is as easy as changing the translation table. Nice COBOL program, with a specific Codepage, and it could be done in one line of COBOL procedure code (plus the obligatory lines of COBOL that go with everything... not so many in this particular case).

Oh, the 1,80 is the "card image" which will contain the text. Probably all in upper-case on the first run...

share|improve this answer
+1. Using DFSORT for ROT2 is really unique. – Abhijit Feb 17 '14 at 6:43

C, 75 bytes



$echo "Today is a great day" |./a.out
Vqfca ku c itgcv fca
share|improve this answer
assuming EOF is -1 you may use the bitwise not ~(c=getchar()) to save 1 char – ace Feb 16 '14 at 1:08
and since the question says there are no punctuations the only non-alphabetical character is space, so you may test for it with c-32 instead, which saves you 6 chars – ace Feb 16 '14 at 2:08
This is a popularity contest and not code-golf – Mhmd Feb 16 '14 at 9:01
Code golf is antithetical to popularity now? – Desty Feb 16 '14 at 17:19
@user689 you're right, sorry I didn't read the question carefully. Since this code is written in a single line with ternary operator and no int, and even a char count is provided, I somehow assumed that it was code golf. Sorry. – ace Feb 16 '14 at 22:37


a = list('abcdefghijklmnopqrstuvwxyz')
b = list('yzabcdefghijklmnopqrstuvwx')

c = {}

#generate conversion dictionary

for i in range(len(a)):
    c[a[i]] = b[i]

instring = "the weather is very nice today"

outstring = ""

for i in list(instring):
        outstring += c[i]
        outstring += i

print outstring


rfc ucyrfcp gq tcpw lgac rmbyw

share|improve this answer
(1) It's +3, right? (2) You could inline a lot of stuff to make it more complicated. (that seems to be a trend here) – Simon Kuang Feb 16 '14 at 4:33
b = a[2:] + a[:2] would be less typo-prone, and there seems to be no need to convert the string a to a list – Tobias Kienzler Feb 16 '14 at 8:41
oh, and c = dict(zip(a,b)). And the except shouldn't be so generic, use an except KeyError – Tobias Kienzler Feb 16 '14 at 9:41
str concatenation is super slow. Create a list and join them together would be much better. – yegle Feb 20 '14 at 21:27


// setup alphabet and secret rotated alphabet
var alpha=' abcdefghijklmnopqrstuvwxyz'
var rotor=' cdefghijklmnopqrstuvwxyzab'

function encrypt(str) {
 return crypt(str, alpha, rotor)

function decrypt(str) {
 return crypt(str, rotor, alpha)

// swap position of char from one dictionary to the other
function crypt(msg, d1, d2) {
 var out=''
 var len=str.length
 for(var i=0; i < len; i++) {
  var c = msg.charAt(i)
  var j = d1.indexOf(c)
  out += d2.charAt(j)
 return out
share|improve this answer


Not the shortest one though!

Live example:

$str = 'Today is a great day';
$out = implode('', array_map(function ($val) {
  if ($val == ' ') return ' ';
  $c = ord($val)+2;

  if (ctype_lower($val)) {
    if ($c > ord('z')) {
      return chr(ord('`') + ($c - ord('z')));
    return chr($c);
  else {
    if ($c > ord('Z')) {
      return chr(ord('A') + ($c - ord('Z')));
    return chr($c);
}, str_split($str)));



ord('`') = ord('a') - 1
share|improve this answer

TI-Basic (the language that runs on TI-83 graphing calculators)

:" abcdefghijklmnopqrstuvwxyz" //all symbols that can be interpreted  
:Lbl 2  
:Lbl 1  
:if not(C)  
:Imput ">",Str2  
:if C  
:Imput "<",Str2  
:if not(C)  
:if not(C  
:if C  
:if C  
:Pause Str3  
:Goto A  

This is some nice encryption software (for a TI-83). By ti-83 I mean any calculator in the ti-83 or ti-84 family. "->" means "STORE" accessed by "STO>"

share|improve this answer

Ruby 40 32


update (as seen from danieros bash solution):

share|improve this answer

Java, it's actually understandable.

I know that anything with whitespace and parentheses has a hard time on CG, but here's a shot.

    class SecretLanguage {

    public static void main(String[] args) {
    for (String S : args) {
        for (char s : S.toCharArray()) {
        System.out.print((char) (s + ((s < 'y') ? 2 : -24)));
        System.out.print(" ");

There are separate contests for obfuscating code, but I can make mine ridiculous too.

class S{public static void main(String[]args){for(String str:args){for(char i:(str).toCharArray())System.out.print((char)(i+((i<'y')?2:-24)));System.out.print(" ");}}
share|improve this answer


var str = '';
var textInput = 'myString';
for (var i = 0; i < textInput.length; i++) {
    str += textInput.charAt(i).replace(/([a-zA-Z])[^a-zA-Z]*$/, function (a) {
        var c = a.charCodeAt(0);
        switch (c) {
            case 89:
                return 'A'; //Letter Y!
            case 90:
                return 'B'; //Letter Z!
            case 121:
                return 'a'; //Letter y!
            case 122: //Letter z!
                return 'b';
                return String.fromCharCode(c + 2); //If not y, Y, z, or Z, then just two more from the usual char code

What with all the comments, my hamster can understand this.

share|improve this answer

I think I'll ROT2 it!


function r(a,b){return++b?String.fromCharCode((a<"["?91:123)>(a=a.charCodeAt()+2)?a:a-26):a.replace(/[A-z]/g,r)}

share|improve this answer
I thought about something like that at first, but I never thought of [A-z]! – Toothbrush Feb 16 '14 at 22:51


Here's a lens based implementation. I'm using Iso to represent the isomorphism between regular text and text converted into the secret language. Unless you provide the --from option, the input is converted into the secret language. If the --from option is provided, the opposite conversion is performed.

module Main where
import Control.Lens
import System.Environment (getArgs)
import Data.Char          (ord, chr, isUpper, isSpace)
import Data.Word          (Word8)

ord8 :: Char -> Word8
ord8 = fromIntegral . ord

chr8 :: Word8 -> Char
chr8 = chr . fromIntegral

ordIso :: Iso' Char Word8
ordIso = iso ord8 chr8

firstLetterOrd :: Word8 -> Word8
firstLetterOrd n
  | n ^. from ordIso . to isUpper = ord8 'A'
  | otherwise                     = ord8 'a'

secretChar :: Iso' Char Char
secretChar =
  iso toSecret
    toSecret, fromSecret :: Char -> Char
    toSecret   = secretConversion   2
    fromSecret = secretConversion (-2)

secretConversion :: Int -> Char -> Char
secretConversion n c
  | isSpace c = c
  | otherwise = c & over ordIso (secretShift n)

secretShift :: Int -> Word8 -> Word8
secretShift shiftAmount =
  preserveLetters $ (`mod` 26) . (+ shiftAmount)

preserveLetters :: (Int -> Int) -> Word8 -> Word8
preserveLetters fn n =
  firstLetter + overWord8 fn (n - firstLetter)
    firstLetter = firstLetterOrd n

overWord8 :: (Int -> Int) -> Word8 -> Word8
overWord8 fn = fromIntegral . fn . fromIntegral

help :: IO ()
help =
  $ unlines
      ["SecretLang [--from]"
      ,"If the --from option is provided, the program"
      ,"converts from the secret language. Otherwise,"
      ,"it converts to the secret language."

convertContents :: (String -> String) -> IO ()
convertContents fn = do
  input <- getContents
  putStrLn . ("Output: " ++) $ fn input

main :: IO ()
main = do
  args <- getArgs

  case args of
    ("--from":_) ->
      convertContents (^. mapping (from secretChar))

    ("--help":_) -> help
    ("-h"    :_) -> help

    _            ->
      convertContents (^. mapping secretChar)


$ ./SecretLang
Today is a great day
Output: Vqfca ku c itgcv fca

$ ./SecretLang --from
Vqfca ku c itgcv fca
Output: Today is a great day
share|improve this answer



    int main()
    { char p[256];
    int i;
    fgets ( p, 256, stdin );
    for(i=0; i<256 ; i++)
   if ( p[i] == '\n' )
    p[i] = '\0';

    if((p[i] >= 'a' && p[i] <= 'x') || (p[i] >= 'A' && p[i] <= 'X') )
        p[i] +=2;

        case 'y':    p[i] = 'a';

       case 'Y':    p[i] = 'A';

       case 'z':    p[i] = 'b';
       case 'Z':    p[i] = 'B';
       case ' ':    p[i] = ' ';


printf("%s", p);

    return 0;
share|improve this answer
you can save a lot of code by using modulu arithmetic on the chars... – blabla999 Feb 16 '14 at 17:43
@blabla999 this is a popularity contest and not code-golf – Mhmd Feb 16 '14 at 17:45
sorry - not meant to offend. I overlooked that. – blabla999 Feb 16 '14 at 17:48

EcmaScript 6:

alert(prompt(_='').split(_).map(x=>String.fromCharCode(x.charCodeAt()+(x>' '?x>'x'|x>'X'&x<'['?-24:2:0))).join(_))
share|improve this answer
EcmaScript, my devolved ol' enemy – Doorhandle Feb 16 '14 at 22:30


32 is space so we print it out as is
88 is X so anything less than 89 moves up 2 characters
90 is Z so anything less than 91 moves down 24 characters (with anything less than 89 already handled so only 89 and 90 effectively)
Repeat same process for lowercase letters, ranging from 97 as a to 122 as z.

void secret(String s) {
    for (char c : s.toCharArray()) {
        System.out.print((char)(c == 32 ? c : c < 89 ? c + 2 : c < 91 ? c - 24 : c < 121 ? c + 2 : c - 24));
share|improve this answer


$chars = [int]('a')[0]..[int]('z')[0] | %{ [char]$_, [char]::ToUpper([char]$_) }

$y = $args[0].ToCharArray() | %{
    $idx = $chars.indexOf($_);
    if ($idx -ge 0) {
        $chars[($idx + 4) % 52]
    } else  {

-join [char[]]$y


PS C:\Temp> .\z.ps1 "Today is a great day"
Vqfca ku c itgcv fca
PS C:\Temp>
share|improve this answer


This solution is rather boring:

echo strtr('Today is a great day','ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz','CDEFGHIJKLMNOPQRSTUVWXYZABcdefghijklmnopqrstuvwxyzab');
share|improve this answer

Python 3

I think i didn't quite understand the question, but anyway:

alphabet = "abcdefghijklmnopqrstuvwxyz"
rot = alphabet[2:] + alphabet[:2]
rot = rot + rot.upper()
alphabet = alphabet + alphabet.upper()

def encode_letter(letter):
    return rot[alphabet.index(letter)]

def encode_word(word):
    return "".join(encode_letter(letter) for letter in word)

def encode_string(string):
    return " ".join(encode_word(word) for word in string.split())

print("Output: " + encode_string(input("Input: ")))
share|improve this answer

Python 2.x

An attempt at a feature rich Python solution.


  • the use of a dict
  • handling the list in a circular way, so that shift=2 can be varied
  • you can also use it to decipher when you know shift (just use minus), it'll also allows you to test your output.
  • ability to add "shifting scopes" -- scopes in which you cycle
  • option to either be strict for undefined characters, or just return the undefined input character.
  • a secret language leaves no trace ;)

Here goes:

# Shifting scopes
lower_case = map(chr, range(97, 123))
upper_case = map(chr, range(65, 91))
space = [" "] # space will always be transformed to space

def secret(instring, shift, scopes, strict=False):
    def buildTranslationDict(scores):
        translation_dict = {}
        for scope in scopes: 
            for index in range(len(scope)): 
                translation_dict[scope[index]] = scope[(index+shift) % len(scope)]
        return translation_dict 
    translation_dict = buildTranslationDict(scopes)
    # Use the translation dictionary to transform input
    output = ""        
    for char in instring:
        if strict:
           output += translation_dict[char]   # will crash if unexpected char
               output += translation_dict[char]
               output += char
    return output    


secret(instring="Today is a great day", shift=2, scopes=[lower_case, upper_case, space])
'Vqfca ku c itgcv fca'

Can you decipher 'Wrpruurz lv qrw edg hlwkhu!' :) ?

share|improve this answer
Just curious, do you consider adding this extra "strict" feature "not to the point"? – PascalvKooten Feb 16 '14 at 23:47
It would save 6 lines of code... – PascalvKooten Feb 17 '14 at 0:08
Are you talking to yourself or am I missing something? Like deleted comments? – Timtech Feb 17 '14 at 0:25
Yup deleted, please do not delete your comment as well... – PascalvKooten Feb 17 '14 at 7:33

Extended BrainFuck

Since this is a popularity contest I've written this with the intention of it being as easy to follow as EBF can be. It's heavily commented and I've intentionally used macros to make the program flow more literal.

Probably the most difficult thing here is the main switch since EBF doesn't have any special means of doing it so it's in reality no simpler than how one would do it in BrainFuck except for the variables and balancing parentheses.

;;;; rot2.ebf : Perform rot2 on ascii text
;;;; Usage: bf < rot2.ebf >
;;;;        echo "Today is a great day" | bf
;;;;        # => Vqfca ku c itgcv fca
;;;; BF interpreter/Compiler requirement: 
;;;; Wrapping cells at any size (allmost all of them do)

;;; Memory map  
:tmp    ; a temporary cell used for the read routine
:input  ; a copy of the input for output purposes
:switch ; a copy of the input for the switch statements
:flag   ; flag to indicate the predicate has been processed or not

;;; Macros
;; Ultracompatible read
;; supports EOF 0, -1 and no change
  [+[-$input-]] ; blanks for all EOFs
  $switch [
    @input &clear

;; for the switch we need
;; to do destructive testing
;; and we need to preserve the
;; original as well. 

;; clears the cell
{clear (-)}

;; prints current cell
{print .}

;;; Main proram
;;; flow starts here
while $tmp not eof
  $switch 10-(22-(
    ;; not linefeed/space
    $switch 57-(-(31-(-(
       ;; default: not wrapping
       $input 2+))))
    $flag (-
       ;; wrapping
       $input 24-)))
  $flag &clear
  $input &print &clear
;;; End
share|improve this answer


var STR = "Today is a great day";
//so i can replace chars at a index in the string
String.prototype.replaceAt=function(i, char) {
    var a = this.split("");
    a[i] = char;
    return a.join("");

function secretIt( str ){
    for( var i = 0; i < str.length; i++ ) {
        var c = str.charCodeAt( i );
        * check for spaces first
        * check if get outside of the letter range for both lower and upper
        * if we dont go then were good
        * if so go back 26 chars
        str = str.replaceAt( i, String.fromCharCode( ( c == 32 ) ? c : ( ( c = c + 2 ) > 91 && c < 97 || c < 123 ) ? c : c - 26 ) ) ;
    return str;

console.log( secretIt( "Qsncp qcapcr ambc" ), ' ' , secretIt( STR ));
share|improve this answer


{x^(raze a!'rotate[2] each a:.Q`a`A)x}
share|improve this answer
Which Q language? or… or something else? – Jerry Jeremiah Dec 23 '15 at 1:11


void sl(String s){
    for (char c: s.toCharArray()){
        char l = Character.toLowerCase(c);
        System.out.print((char)(c + (l < 'y'? l < 'a'? 0: 2: -24)));
share|improve this answer
I would say this is very similar to this answer: – ace Feb 20 '14 at 21:48
...and I would agree with you :P – rodrigopc Feb 21 '14 at 20:04

C#, 163

Yes, this is not code-golf. I went for shortest anyway (or at least, made a first stab at it)

using System.Linq;class P{static void Main(string[]a){System.Console.WriteLine(string.Concat(a[0].Select(c=>(char)(c==32?c:c<89?c+2:c<91?c-24:c<121?c+2:c-24))));}}


using System.Linq;
class P
    static void Main(string[] a)
        System.Console.WriteLine(string.Concat(a[0].Select(c => (char)(c == 32 ? c : c < 89 ? c + 2 : c < 91 ? c - 24 : c < 121 ? c + 2 : c - 24))));

Yes, I did have a peek at ufis' answer.

share|improve this answer

C# 5KB

(381 chars)


using System;
namespace WinHelper {
    class P {
        static void Main(string[] args) {
            char[] f =  "abcdefghijklmnopqrstuvwxyz ".ToCharArray();
            char[] g =  "cdefghijklmnopqrstuvwxyzab ".ToCharArray();

            foreach (char c in Console.ReadLine().ToCharArray().ToLower()) 
                Console.Write(g[Array.FindIndex(f, a => a == c)]);
share|improve this answer
Compiled size (5KB) doesn't matter. For code-golf the number of chars (of sourcecode) usually counts, but since this particular challenge is a popularity contest and not code-golf the chars/size doesn't matter at all. Hover your mouse over the popularity contest badge beneath the challenge (you'll see a tooltip explaining it: "A popularity-contest is a competition where the correct answer with the most upvotes wins, usually the most creative answer"). – RobIII Feb 20 '14 at 15:13
Also, it crashes on the challenge's example input Today is a great day since it doesn't support uppercase letters. – RobIII Feb 21 '14 at 1:24

Bash, 8 characters

...if you happen to have the bsdgames package installed! Reads from standard input.

caesar 2


echo Today is a great day|caesar 2

Output: Vqfca ku c itgcv fca

share|improve this answer


#include <stdio.h>
char c[100];
int main()
char *p=c,x;

share|improve this answer

Your Answer


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.