11
\$\begingroup\$

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

Example:

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.

\$\endgroup\$
7
  • \$\begingroup\$ Shouldn't that be x=z, y=a, z=b? \$\endgroup\$
    – r3mainer
    Feb 16, 2014 at 0:46
  • \$\begingroup\$ you are right "duh" :) \$\endgroup\$
    – Vik P
    Feb 16, 2014 at 0:47
  • 3
    \$\begingroup\$ I was confused until I realized a=c is a -> c. \$\endgroup\$
    – Justin
    Feb 16, 2014 at 4:10
  • 6
    \$\begingroup\$ In other words, ROT2 it \$\endgroup\$ Feb 16, 2014 at 8:39
  • 3
    \$\begingroup\$ Both rot13 and rot2 are both Caesar ciphers with different keys (13 and 2). \$\endgroup\$
    – Sylwester
    Feb 16, 2014 at 15:42

35 Answers 35

20
\$\begingroup\$

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)
\$\endgroup\$
1
  • 2
    \$\begingroup\$ I never thought I'd see a Smalltalk solution! \$\endgroup\$
    – Toothbrush
    Feb 16, 2014 at 22:46
15
\$\begingroup\$

Postscript

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 {
    /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
        putinterval
    } 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.:

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

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

\$\endgroup\$
13
\$\begingroup\$

Ruby, obfuscated edition (with commentary included!)

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

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

# MAGIC:
$s+="#{c}".split("#{$;}").map{|x|x.ord-8**2}.reduce(:"#{43.chr}").chr;end;end

              # 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
ASDFASDFASDF  # I SAID STOP BANGING ON THE KEYBOARD
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?!?!
EEEEEEEEEEEEE # No
VVV           # Stop
HELLOo        # ...it'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 gets.tr'A-Za-z','C-ZABc-zab'.

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

bash

Classic.

tr A-Za-z C-ZABc-zab

Example:

$ tr A-Za-z C-ZABc-zab <<< "Today is a great day"
Vqfca ku c itgcv fca
\$\endgroup\$
2
  • \$\begingroup\$ I think you don't need the quotes. \$\endgroup\$
    – marinus
    Feb 16, 2014 at 11:20
  • \$\begingroup\$ @marinus You're right, I'll change it. \$\endgroup\$
    – daniero
    Feb 16, 2014 at 12:15
6
\$\begingroup\$

DFSORT (IBM Mainframe sorting program)

 OPTION COPY
 INREC BUILD=(1,80,TRAN=ALTSEQ)

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

 OPTION COPY
 INREC BUILD=(1,80,TRAN=ALTSEQ)
 ALTSEQ CODE=(xxyy,...)

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

ALTSEQ CODE=(C1C3,C2C4)

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...

\$\endgroup\$
1
  • \$\begingroup\$ +1. Using DFSORT for ROT2 is really unique. \$\endgroup\$
    – Abhijit
    Feb 17, 2014 at 6:43
4
\$\begingroup\$

C, 75 bytes

main(c){while((c=getchar())>0)putchar(isalpha(c)?(c&224)+((c&31)+2)%26:c);}

Example:

$echo "Today is a great day" |./a.out
Vqfca ku c itgcv fca
\$\endgroup\$
5
  • \$\begingroup\$ assuming EOF is -1 you may use the bitwise not ~(c=getchar()) to save 1 char \$\endgroup\$
    – user12205
    Feb 16, 2014 at 1:08
  • \$\begingroup\$ 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 \$\endgroup\$
    – user12205
    Feb 16, 2014 at 2:08
  • 1
    \$\begingroup\$ This is a popularity contest and not code-golf \$\endgroup\$
    – Mohammad
    Feb 16, 2014 at 9:01
  • \$\begingroup\$ Code golf is antithetical to popularity now? \$\endgroup\$
    – Desty
    Feb 16, 2014 at 17:19
  • \$\begingroup\$ @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. \$\endgroup\$
    – user12205
    Feb 16, 2014 at 22:37
3
\$\begingroup\$

PHP

Not the shortest one though!

Live example: https://eval.in/102173

<?php
$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)));

var_dump($out);

Note:

ord('`') = ord('a') - 1
\$\endgroup\$
3
\$\begingroup\$

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

:ClrHome  
:" abcdefghijklmnopqrstuvwxyz" //all symbols that can be interpreted  
:Ans+Ans+Ans->Str1  
:Menu("crippter","encript",1,"decript",2  
:Lbl 2  
:1->C  
:Lbl 1  
:if not(C)  
:Imput ">",Str2  
:if C  
:Imput "<",Str2  
:length(Str2)->D  
:lenght(Str1)/3->E  
:if not(C)  
:Then  
:randInt(1,E)->B  
:sub(Str1,B,1)->Str3  
:Else  
:inString(Str1,sub(Str2,1,1),1)->B  
":"->Str3  
:For(X,1+C,D  
:inString(Str1,sub(Str2,X,1)->A  
:if not(C  
:A+E-B-X->A  
:if C  
:A+B+X-1->A  
:Str3+sub(Str1,A,1)->Str3  
:End  
:if C  
:sub(Str3,2,D-1)->Str3  
: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>"

\$\endgroup\$
1
  • \$\begingroup\$ This doesn't work, at least on the TI-84 family -- // doesn't define comments (in fact, there is no way to get comments), every If requires a Then, and it's impossible to have a line that doesn't start with a colon (as you have with ":"->Str3). \$\endgroup\$
    – Bbrk24
    Sep 23, 2021 at 1:53
3
\$\begingroup\$

Ruby 40 32

p gets.tr("A-XY-Za-xy-z","C-ZA-Bc-za-b") 

update (as seen from danieros bash solution):

p gets.tr("A-Za-z","C-ZABc-zab")
\$\endgroup\$
3
\$\begingroup\$

I think I'll ROT2 it!

Javascript

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

console.log(r('Qccipcr'));
\$\endgroup\$
1
  • \$\begingroup\$ I thought about something like that at first, but I never thought of [A-z]! \$\endgroup\$
    – Toothbrush
    Feb 16, 2014 at 22:51
3
\$\begingroup\$

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(" ");}}
\$\endgroup\$
2
\$\begingroup\$

Python

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):
    try:
        outstring += c[i]
    except:
        outstring += i

print outstring

Output:

rfc ucyrfcp gq tcpw lgac rmbyw

\$\endgroup\$
4
  • \$\begingroup\$ (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) \$\endgroup\$ Feb 16, 2014 at 4:33
  • \$\begingroup\$ 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 \$\endgroup\$ Feb 16, 2014 at 8:41
  • \$\begingroup\$ oh, and c = dict(zip(a,b)). And the except shouldn't be so generic, use an except KeyError \$\endgroup\$ Feb 16, 2014 at 9:41
  • \$\begingroup\$ str concatenation is super slow. Create a list and join them together would be much better. \$\endgroup\$
    – yegle
    Feb 20, 2014 at 21:27
2
\$\begingroup\$

JavaScript

// setup alphabet and secret rotated alphabet
//
var alpha=' abcdefghijklmnopqrstuvwxyz'
var rotor=' cdefghijklmnopqrstuvwxyzab'
alpha+=alpha.toUpperCase()
rotor+=rotor.toUpperCase()

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
}
\$\endgroup\$
2
\$\begingroup\$

Javascript

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';
            default:
                return String.fromCharCode(c + 2); //If not y, Y, z, or Z, then just two more from the usual char code
        }
    })
}
console.log(str);

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

\$\endgroup\$
2
\$\begingroup\$

Powershell

$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

Output:

PS C:\Temp> .\z.ps1 "Today is a great day"
Vqfca ku c itgcv fca
PS C:\Temp>
\$\endgroup\$
2
\$\begingroup\$

Haskell

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
      fromSecret
  where
    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)
  where
    firstLetter = firstLetterOrd n

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

help :: IO ()
help =
  putStr
  $ 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)

Examples:

$ ./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
\$\endgroup\$
2
\$\begingroup\$

Python 2.x

An attempt at a feature rich Python solution.

Features:

  • 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
        else:
            try:    
               output += translation_dict[char]
            except: 
               output += char
    return output    

Proof:

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!' :) ?

\$\endgroup\$
4
  • \$\begingroup\$ Just curious, do you consider adding this extra "strict" feature "not to the point"? \$\endgroup\$ Feb 16, 2014 at 23:47
  • \$\begingroup\$ It would save 6 lines of code... \$\endgroup\$ Feb 17, 2014 at 0:08
  • 1
    \$\begingroup\$ Are you talking to yourself or am I missing something? Like deleted comments? \$\endgroup\$
    – Timtech
    Feb 17, 2014 at 0:25
  • 3
    \$\begingroup\$ Yup deleted, please do not delete your comment as well... \$\endgroup\$ Feb 17, 2014 at 7:33
1
\$\begingroup\$

C

    #include<stdio.h>

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

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

    else
    {
    switch(p[i])
     {
        case 'y':    p[i] = 'a';
                     break;

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

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


     }
    }
}}

printf("%s", p);

    return 0;
 }
\$\endgroup\$
3
  • \$\begingroup\$ you can save a lot of code by using modulu arithmetic on the chars... \$\endgroup\$
    – blabla999
    Feb 16, 2014 at 17:43
  • \$\begingroup\$ @blabla999 this is a popularity contest and not code-golf \$\endgroup\$
    – Mohammad
    Feb 16, 2014 at 17:45
  • 1
    \$\begingroup\$ sorry - not meant to offend. I overlooked that. \$\endgroup\$
    – blabla999
    Feb 16, 2014 at 17:48
1
\$\begingroup\$

EcmaScript 6:

alert(prompt(_='').split(_).map(x=>String.fromCharCode(x.charCodeAt()+(x>' '?x>'x'|x>'X'&x<'['?-24:2:0))).join(_))
\$\endgroup\$
1
  • \$\begingroup\$ EcmaScript, my devolved ol' enemy \$\endgroup\$
    – Cilan
    Feb 16, 2014 at 22:30
1
\$\begingroup\$

JAVA

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));
    }
}
\$\endgroup\$
1
\$\begingroup\$

PHP

This solution is rather boring:

echo strtr('Today is a great day','ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz','CDEFGHIJKLMNOPQRSTUVWXYZABcdefghijklmnopqrstuvwxyzab');
\$\endgroup\$
1
\$\begingroup\$

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: ")))
\$\endgroup\$
1
\$\begingroup\$

JavaScript (V8)

t=>t.replace(/./g,d=>/[a-z]/i.test(d)?((parseInt(d,36)-8)%26+10).toString(36)[/[A-Z]/.test(d)?"toUpperCase":"valueOf"]():d)

This is code golf, short is popular.

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

Python 3

# To understand recursion, go to the bottom of the program

from string import ascii_letters

translate_table = {
    c: chr(ord(c) + 2) for c in ascii_letters
}


def translate_helper(string):
    if len(string) == 1:
        if string not in {"y", "z"}:
            return translate_table[string]
        else:
            return "a" if string == "y" else "b"
    else:
        return translate_helper(string[:-1]) + translate_helper(string[-1])


def translate(string):
    return " ".join(map(translate_helper, string.split(" ")))


print(translate("Today is a great day"))

# To understand recursion, go to the top of the program
\$\endgroup\$
1
\$\begingroup\$

Javascript, 255 bytes

const sl = text =>
  text
    .split(" ")
    .map(word =>
      word
        .split("")
        .map(c => String.fromCharCode(c.charCodeAt(0) + (c < "y" ? 2 : -24)))
        .join("")
    )
    .join(" ");

console.log(sl("Today is a great day"));
\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Code Golf! There's a lot of byte saves possible here, like removing whitespace and shortening variable names (like changing word to w). I'd recommend checking out our Tips for Golfing in JavaScript for more! \$\endgroup\$ Sep 25, 2021 at 2:59
1
\$\begingroup\$

Vyxal

@rotate:letter|
 kL ←letter c [
   ←letter \Y = [
     \A | ←letter \y = [
       \a | ←letter \Z = [
         \B | ←letter \z = [
           \b | ←letter C 2 + C 
         ]
       ]
     ]
   ] | ←letter
 ]
;

`Today is a great day`f °rotate; M ¤j

Try it Online!

Finally, a chance to use the more obscure features of Vyxal! Behold the beauty of named functions, variables, if-else chains and function references. I also got to make good use of the codemirror functionality built into the online interpreter for once.

Also, I know caird said not to, but I answered anyway, because I never get the chance to properly show off the cooler stuff of my esolang.

\$\endgroup\$
0
\$\begingroup\$

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 ebf.bf < rot2.ebf > rot2.bf
;;;;        echo "Today is a great day" | bf rot2.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
{read_tmp 
  $input+ 
  $tmp(-),
  [+[-$input-]] ; blanks for all EOFs
  $switch [
    @input &clear
    $switch
  ]
}

;; for the switch we need
;; to do destructive testing
;; and we need to preserve the
;; original as well. 
{copy_input 
  $tmp(-$input+$switch+)
}

;; clears the cell
{clear (-)}

;; prints current cell
{print .}

;;; Main proram
;;; flow starts here
&read_tmp
while $tmp not eof
(
  &copy_input
  $flag+
  $switch 10-(22-(
    ;; not linefeed/space
    $switch 57-(-(31-(-(
       ;; default: not wrapping
       &clear
       $flag-
       $input 2+))))
    $flag (-
       ;; wrapping
       $input 24-)))
  $flag &clear
  $input &print &clear
  &read_tmp
)
;;; End
\$\endgroup\$
0
\$\begingroup\$

Javascript

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 ));
\$\endgroup\$
0
\$\begingroup\$

Q

{x^(raze a!'rotate[2] each a:.Q`a`A)x}
\$\endgroup\$
1
0
\$\begingroup\$

Java

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)));
    }
}
\$\endgroup\$
2

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