Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (liketr, which acts like a commonUNIX utility, performing a line-by-line rot-13 encoding of every line of input contained in each file listed on its command line, or (if no filenames are passed thereon) acting as a filter on its "standard input."
(A number of UNIX scripting languages and utilities, such as awk and sed either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g., Perl and Python).
The rot-13 encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of spoiler or potentially offensive material.
Many news reader and mail user agent programs have built-inrot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions.
The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position (wrapping around from z to a as necessary).
Thus the letters abc become nop and so on.
Technicallyrot-13 is a "mono-alphabetic substitution cipher" with a trivial "key".
A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters in the input stream through without alteration.
F rot13(string) V r = ‘ ’ * string.len L(c) string r[L.index] = S c ‘a’..‘z’ Char(code' (c.code - ‘a’.code + 13) % 26 + ‘a’.code) ‘A’..‘Z’ Char(code' (c.code - ‘A’.code + 13) % 26 + ‘A’.code) E c R rprint(rot13(‘foo’))print(rot13(‘sbb’))
sbbfoo
Sytem/360 uses EBCDIC encoding. The power of the CISC architecture, only one hardware instruction (TR) does all the job!
ROT13 CSECT USING ROT13,R15 use calling register XPRNT CC,L'CC TR CC,TABLE translate XPRNT CC,L'CC TR CC,TABLE translate XPRNT CC,L'CC BR R14 return to callerCC DC CL10'{NOWHERE!}'TABLE DC CL64' ' * 0123456789ABCDEF DC CL16' .<(+|' X'4.' DC CL16' !$*);^' X'5.' DC CL16'&& ,%_>?' X'6.' DC CL16'-/ `:#@''="' X'7.' DC CL16' nopqrstuv ' X'8.' DC CL16' wxyzabcde ' X'9.' DC CL16' ~fghijklm [ ' X'A.' DC CL16' ] ' X'B.' DC CL16'{NOPQRSTUV ' X'C.' DC CL16'}WXYZABCDE ' X'D.' DC CL16'\ FGHIJKLM ' X'E.' DC CL16'0123456789 ' X'F.'* 0123456789ABCDEF YREGS END ROT13
{NOWHERE!}{ABJURER!}{NOWHERE!}
Written for the BeebAsm assembler, which uses '&' to indicate a hexadecimal number. Call with the address of a zero terminated string in X and Y.On exit X is hi-order address of the last page of the string, Y is the length of the string modulo 256 and A is zero unless the string is not terminated.
buffer = $fa ; or anywhere in zero page that's goodmaxpage = $95 ; if non-terminated that's badorg $1900.rot13 stx buffer sty buffer+1 ldy #0 beq readit.loop cmp #$7b ; high range bcs next ; >= { cmp #$41 ; low range bcc next ; < A cmp #$4e bcc add13 ; < N cmp #$5b bcc sub13set ; < [ cmp #$61 bcc next ; < a cmp #$6e bcs sub13 ; >= n.add13 adc #13 ; we only get here via bcc; so clc not needed bne storeit.sub13set sec ; because we got here via bcc; so sec is needed.sub13 sbc #13 ; we can get here via bcs; so sec not needed.storeit sta (buffer),y.next iny bne readit ldx buffer+1 cpx maxpage beq done inx stx buffer+1.readit lda (buffer),y ; quit on ascii 0 bne loop.done rts.endsave "rot-13", rot13, end
/* ARM assembly AARCH64 Raspberry PI 3B *//* program rot1364.s *//************************************//* Constantes *//************************************//* for this file see task include a file in language AArch64 assembly*/.include "../includeConstantesARM64.inc" .equ STRINGSIZE, 500//.include "../../ficmacros64.inc"/************************************//* Initialized data *//************************************/.dataszMessString: .asciz "String :\n"szMessEncrip: .asciz "\nEncrypted :\n"szMessDecrip: .asciz "\nDecrypted :\n"szString1: .asciz "{NOWHERE! abcd xyz 1234}"szCarriageReturn: .asciz "\n"/************************************//* UnInitialized data *//************************************/.bss szString2: .skip STRINGSIZEszString3: .skip STRINGSIZE/************************************//* code section *//************************************/.text.global main main: ldr x0,qAdrszMessString // display message bl affichageMess ldr x0,qAdrszString1 // display string bl affichageMess ldr x0,qAdrszString1 ldr x1,qAdrszString2 bl encryptRot13 ldr x0,qAdrszMessEncrip bl affichageMess ldr x0,qAdrszString2 // display string bl affichageMess ldr x0,qAdrszString2 ldr x1,qAdrszString3 bl decryptRot13 ldr x0,qAdrszMessDecrip bl affichageMess ldr x0,qAdrszString3 // display string bl affichageMess ldr x0,qAdrszCarriageReturn bl affichageMess 100: // standard end of the program mov x0, #0 // return code mov x8,EXIT svc 0 // perform system callqAdrszMessString: .quad szMessStringqAdrszMessDecrip: .quad szMessDecripqAdrszMessEncrip: .quad szMessEncripqAdrszString1: .quad szString1qAdrszString2: .quad szString2qAdrszString3: .quad szString3qAdrszCarriageReturn: .quad szCarriageReturn/******************************************************************//* encrypt strings */ /******************************************************************//* x0 contains the address of the string1 *//* x1 contains the address of the encrypted string */encryptRot13: stp x3,lr,[sp,-16]! // save registers stp x4,x5,[sp,-16]! // save registers mov x3,#0 // counter byte string 1 mov x2,#13 // rot characters number1: ldrb w4,[x0,x3] // load byte string 1 cmp w4,#0 // zero final ? bne 2f strb w4,[x1,x3] mov x0,x3 b 100f2: cmp w4,#65 // < A ? bge 3f strb w4,[x1,x3] add x3,x3,#1 b 1b // and loop3: cmp x4,#90 // > Z bgt 4f add x4,x4,x2 // add key cmp x4,#90 // > Z sub x5,x4,26 csel x4,x5,x4,gt strb w4,[x1,x3] add x3,x3,#1 b 1b4: cmp x4,#97 // < a ? bge 5f strb w4,[x1,x3] add x3,x3,#1 b 1b5: cmp x4,#122 //> z ble 6f strb w4,[x1,x3] add x3,x3,#1 b 1b6: add x4,x4,x2 cmp x4,#122 sub x5,x4,26 csel x4,x5,x4,gt strb w4,[x1,x3] add x3,x3,#1 b 1b100: ldp x4,x5,[sp],16 // restaur registers ldp x3,lr,[sp],16 // restaur registers ret /******************************************************************//* decrypt strings */ /******************************************************************//* x0 contains the address of the encrypted string1 *//* x1 contains the address of the decrypted string */decryptRot13: stp x3,lr,[sp,-16]! // save registers stp x4,x5,[sp,-16]! // save registers mov x3,#0 // counter byte string 1 mov x2,#13 // rot characters number1: ldrb w4,[x0,x3] // load byte string 1 cmp w4,#0 // zero final ? bne 2f strb w4,[x1,x3] mov x0,x3 b 100f2: cmp x4,#65 // < A ? bge 3f strb w4,[x1,x3] add x3,x3,#1 b 1b // and loop3: cmp x4,#90 // > Z bgt 4f sub x4,x4,x2 // substract key cmp x4,#65 // < A add x5,x4,26 csel x4,x5,x4,lt strb w4,[x1,x3] add x3,x3,#1 b 1b4: cmp x4,#97 // < a ? bge 5f strb w4,[x1,x3] add x3,x3,#1 b 1b5: cmp x4,#122 // > z ble 6f strb w4,[x1,x3] add x3,x3,#1 b 1b6: sub x4,x4,x2 // substract key cmp x4,#97 // < a add x5,x4,26 csel x4,x5,x4,lt strb w4,[x1,x3] add x3,x3,#1 b 1b100: ldp x4,x5,[sp],16 // restaur registers ldp x3,lr,[sp],16 // restaur registers ret /***************************************************//* ROUTINES INCLUDE *//***************************************************//* for this file see task include a file in language AArch64 assembly*/.include "../includeARM64.inc"
String :{NOWHERE! abcd xyz 1234}Encrypted :{ABJURER! nopq klm 1234}Decrypted :{NOWHERE! abcd xyz 1234}
(include-book"arithmetic-3/top":dir:system)(defunchar-btn(clowhigh)(and(char>=clow)(char<=chigh)))(defunrot-13-cs(cs)(cond((endpcs)nil)((or(char-btn(firstcs)#\a#\m)(char-btn(firstcs)#\A#\M))(cons(code-char(+(char-code(firstcs))13))(rot-13-cs(restcs))))((or(char-btn(firstcs)#\n#\z)(char-btn(firstcs)#\N#\Z))(cons(code-char(-(char-code(firstcs))13))(rot-13-cs(restcs))))(t(cons(firstcs)(rot-13-cs(restcs))))))(defunrot-13(s)(coerce(rot-13-cs(coerces'list))'string))
withAda.Text_IO.Text_Streams;useAda.Text_IO.Text_Streams;withAda.Strings.Maps;useAda.Strings.Maps;withAda.Command_Line;useAda.Command_Line;procedureRot_13isFrom_Sequence:Character_Sequence:="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";Result_Sequence:Character_Sequence:="nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM";Rot_13_Mapping:Character_Mapping:=To_Mapping(From_Sequence,Result_Sequence);In_Char:Character;Stdio:Stream_Access:=Stream(Ada.Text_IO.Standard_Input);Stdout:Stream_Access:=Stream(Ada.Text_Io.Standard_Output);Input:Ada.Text_Io.File_Type;beginifArgument_Count>0thenforIin1..Argument_CountloopbeginAda.Text_Io.Open(File=>Input,Mode=>Ada.Text_Io.In_File,Name=>Argument(I));Stdio:=Stream(Input);whilenotAda.Text_Io.End_Of_File(Input)loopIn_Char:=Character'Input(Stdio);Character'Output(Stdout,Value(Rot_13_Mapping,In_Char));endloop;Ada.Text_IO.Close(Input);exceptionwhenAda.Text_IO.Name_Error=>Ada.Text_Io.Put_Line(File=>Ada.Text_Io.Standard_Error,Item=>"File "&Argument(I)&" is not a file.");whenAda.Text_Io.Status_Error=>Ada.Text_Io.Put_Line(File=>Ada.Text_Io.Standard_Error,Item=>"File "&Argument(I)&" is already opened.");end;endloop;elsewhilenotAda.Text_Io.End_Of_FileloopIn_Char:=Character'Input(Stdio);Character'Output(Stdout,Value(Rot_13_Mapping,In_Char));endloop;endif;endRot_13;
BEGIN CHAR c; on logical file end(stand in, (REF FILE f)BOOL: (stop; SKIP)); on line end(stand in, (REF FILE f)BOOL: (print(new line); FALSE)); DO read(c); IF c >= "A" AND c <= "M" OR c >= "a" AND c <= "m" THEN c := REPR(ABS c + 13) ELIF c >= "N" AND c <= "Z" OR c >= "n" AND c <= "z" THEN c := REPR(ABS c - 13) FI; print(c) ODEND # rot13 #
Sample run on linux:
$ echo Big fjords vex quick waltz nymph! | a68g Rot-13.a68Ovt swbeqf irk dhvpx jnygm alzcu!
r1←⎕UCS∘{+/⍵,13×(⍵≥65)∧(⍵<78),(-(⍵≥78)∧(⍵≤90)),(⍵≥97)∧(⍵<110),(-(⍵≥110)∧(⍵≤122))}∘⎕UCSrot13←{r1¨⍵}
⎕UCS is technically implementation-defined, but the bigger problem with portability of the above is that it uses ∘ for function composition.Here's a version that works in a wider variety of implementations:
r1←{⎕UCS{+/⍵,13×(⍵≥65)∧(⍵<78),(-(⍵≥78)∧(⍵≤90)),(⍵≥97)∧(⍵<110),(-(⍵≥110)∧(⍵≤122))}⎕UCS⍵}rot13←{r1¨⍵}
rot13 'nowhere ABJURER'abjurer NOWHERE
⍝ 2023-03-03k←'AaBbCcDdEeFfGgHhIiJjKkLlMmzZyYxXwWvVuUtTsSrRqQpPoOnN'rot←{⍵∊k:[53-k⍳⍵]⋄⍵}¨
rot 'Usenet rulez !'Hfrarg ehyrm !rot 'Hfrarg ehyrm !'Usenet rulez !
Usingdo shell script
torot13(textString)do shell script"tr a-zA-Z n-za-mN-ZA-M <<<""ed formoftextStringendrot13
Pure AppleScript solution
torot13(textString)settheIDstoidoftextStringrepeatwiththisIDintheIDsif(((thisID<123)and(thisID>96))or((thisID<91)and(thisID>64)))then¬tell(thisIDmod32)tosetthisID'scontentstothisID-it+(it+12)mod26+1endrepeatreturnstringidtheIDsendrot13
Demo code:
rot13("nowhere ABJURER")
abjurer NOWHERE
Or using some generic primitives, and a slightly more functional style of composition:
-- ROT 13 ---------------------------------------------------------------------- rot13 :: String -> Stringonrot13(str)scriptrt13on|λ|(x)if(x≥"a"andx≤"m")or(x≥"A"andx≤"M")thencharacterid((idofx)+13)elseif(x≥"n"andx≤"z")or(x≥"N"andx≤"Z")thencharacterid((idofx)-13)elsexendifend|λ|endscriptintercalate("",map(rt13,charactersofstr))endrot13-- TEST ----------------------------------------------------------------------onrunrot13("nowhere ABJURER")--> "abjurer NOWHERE"endrun-- GENERIC FUNCTIONS ----------------------------------------------------------- map :: (a -> b) -> [a] -> [b]onmap(f,xs)tellmReturn(f)setlngtolengthofxssetlstto{}repeatwithifrom1tolngsetendoflstto|λ|(itemiofxs,i,xs)endrepeatreturnlstendtellendmap-- intercalate :: Text -> [Text] -> Textonintercalate(strText,lstText)set{dlm,mytext item delimiters}to{mytext item delimiters,strText}setstrJoinedtolstTextastextsetmytext item delimiterstodlmreturnstrJoinedendintercalate-- Lift 2nd class handler function into 1st class script wrapper-- mReturn :: Handler -> ScriptonmReturn(f)ifclassoffisscriptthenfelsescriptproperty|λ|:fendscriptendifendmReturn
100HOME:INPUT"ENTER A STRING:";S$:FORL=1TOLEN(S$):I$=MID$(S$,L,1):LC=(ASC(I$)>95)*32:C$=CHR$(ASC(I$)-LC):IFC$>="A"ANDC$<="Z"THENC$=CHR$(ASC(C$)+13):C$=CHR$(ASC(C$)-26*(C$>"Z")):I$=CHR$(ASC(C$)+LC)110A$=A$+I$:NEXT:PRINTA$
/* ARM assembly Raspberry PI *//* program rot13.s *//* for constantes see task include a file in arm assembly *//************************************//* Constantes *//************************************/.include "../constantes.inc".equ STRINGSIZE, 500/************************************//* Initialized data *//************************************/.dataszMessString: .asciz "String :\n"szMessEncrip: .asciz "\nEncrypted :\n"szMessDecrip: .asciz "\nDecrypted :\n"szString1: .asciz "{NOWHERE! abcd xyz 1234}"szCarriageReturn: .asciz "\n"/************************************//* UnInitialized data *//************************************/.bss szString2: .skip STRINGSIZEszString3: .skip STRINGSIZE/************************************//* code section *//************************************/.text.global main main: ldr r0,iAdrszMessString @ display message bl affichageMess ldr r0,iAdrszString1 @ display string bl affichageMess ldr r0,iAdrszString1 ldr r1,iAdrszString2 bl encryptRot13 ldr r0,iAdrszMessEncrip bl affichageMess ldr r0,iAdrszString2 @ display string bl affichageMess ldr r0,iAdrszString2 ldr r1,iAdrszString3 bl decryptRot13 ldr r0,iAdrszMessDecrip bl affichageMess ldr r0,iAdrszString3 @ display string bl affichageMess ldr r0,iAdrszCarriageReturn bl affichageMess 100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc 0 @ perform system calliAdrszMessString: .int szMessStringiAdrszMessDecrip: .int szMessDecripiAdrszMessEncrip: .int szMessEncripiAdrszString1: .int szString1iAdrszString2: .int szString2iAdrszString3: .int szString3iAdrszCarriageReturn: .int szCarriageReturn/******************************************************************//* encrypt strings */ /******************************************************************//* r0 contains the address of the string1 *//* r1 contains the address of the encrypted string */encryptRot13: push {r3,r4,lr} @ save registers mov r3,#0 @ counter byte string 1 mov r2,#13 @ rot characters number1: ldrb r4,[r0,r3] @ load byte string 1 cmp r4,#0 @ zero final ? streqb r4,[r1,r3] moveq r0,r3 beq 100f cmp r4,#65 @ < A ? strltb r4,[r1,r3] addlt r3,#1 blt 1b cmp r4,#90 @ > Z bgt 2f add r4,r2 @ add key cmp r4,#90 @ > Z subgt r4,#26 strb r4,[r1,r3] add r3,#1 b 1b2: cmp r4,#97 @ < a ? strltb r4,[r1,r3] addlt r3,#1 blt 1b cmp r4,#122 @> z strgtb r4,[r1,r3] addgt r3,#1 bgt 1b add r4,r2 cmp r4,#122 subgt r4,#26 strb r4,[r1,r3] add r3,#1 b 1b100: pop {r3,r4,lr} @ restaur registers bx lr @ return/******************************************************************//* decrypt strings */ /******************************************************************//* r0 contains the address of the encrypted string1 *//* r1 contains the address of the decrypted string */decryptRot13: push {r3,r4,lr} @ save registers mov r3,#0 @ counter byte string 1 mov r2,#13 @ rot characters number1: ldrb r4,[r0,r3] @ load byte string 1 cmp r4,#0 @ zero final ? streqb r4,[r1,r3] moveq r0,r3 beq 100f cmp r4,#65 @ < A ? strltb r4,[r1,r3] addlt r3,#1 blt 1b cmp r4,#90 @ > Z bgt 2f sub r4,r2 @ substract key cmp r4,#65 @ < A addlt r4,#26 strb r4,[r1,r3] add r3,#1 b 1b2: cmp r4,#97 @ < a ? strltb r4,[r1,r3] addlt r3,#1 blt 1b cmp r4,#122 @ > z strgtb r4,[r1,r3] addgt r3,#1 bgt 1b sub r4,r2 @ substract key cmp r4,#97 @ < a addlt r4,#26 strb r4,[r1,r3] add r3,#1 b 1b100: pop {r3,r4,lr} @ restaur registers bx lr @ return/***************************************************//* ROUTINES INCLUDE *//***************************************************//* for this file see task include a file in language ARM assembly*/.include "../affichage.inc"
String :{NOWHERE! abcd xyz 1234}Encrypted :{ABJURER! nopq klm 1234}Decrypted :{NOWHERE! abcd xyz 1234}
rot13:function[c][case[in?lowerc]when?->`a`..`m`->returnto:char(to:integer c)+13when?->`n`..`z`->returnto:char(to:integer c)-13else->returnc]loop"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"'ch->printsrot13chprint""
NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm
Simple alphabet remapping method by Raccoon. Similar to a translate() function in many languages.
ROT13(string) ; by Raccoon July-2009{Statica:="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "Staticb:="nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM "s=Loop,Parse,string{c:=substr(b,instr(a,A_LoopField,True),1)if(c!=" ")s.=celses.=A_LoopField}Returns}
Simple ASCII math method by Raccoon. Add or subtract 13 depending on the character's decimal value.
ROT13(string) ; by Raccoon July-2009{s=Loop,Parse,string{c:=asc(A_LoopField)if(c>=97)&&(c<=109)||(c>=65)&&(c<=77)c+=13elseif(c>=110)&&(c<=122)||(c>=78)&&(c<=90)c-=13s.=chr(c)}Returns}
Code modified fromstringmod byHugo:ahk discussion
Str0=Hello,Thisisasampletextwith123orotherdigits!@#$^&*()-_=Str1:=Rot13(Str0)Str2:=Rot13(Str1)MsgBox%Str0"`n"Str1"`n"Str2Rot13(string){LoopParse,string{char:=Asc(A_LoopField) ; o is 'A' code if it is an uppercase letter, and 'a' code if it is a lowercase lettero:=Asc("A")*(Asc("A")<=char&&char<=Asc("Z"))+Asc("a")*(Asc("a")<=char&&char<=Asc("z"))If(o>0){ ; Set between 0 and 25, add rotation factor, modulus alphabet sizechar:=Mod(char-o+13,26) ; Transform back to char, upper or lowerchar:=Chr(char+o)}Else{ ; Non alphabetic, unchangedchar:=A_LoopField}rStr.=char}ReturnrStr}
fromLinearSpoon's Translation ofThe Worlds Shortest C Implementation of Rot13
Rot13(string){Output:=""Loop,Parse,string{a:=~Asc(A_LoopField)Output.=Chr(~a-1//(~(a|32)//13*2-11)*13)}returnOutput}
# usage: awk -f rot13.awkBEGIN{for(i=0;i<256;i++){amap[sprintf("%c",i)]=i}for(l=amap["a"];l<=amap["z"];l++){rot13[l]=sprintf("%c",(((l-amap["a"])+13)%26)+amap["a"])}FS=""}{o=""for(i=1;i<=NF;i++){if(amap[tolower($i)]inrot13){c=rot13[amap[tolower($i)]]if(tolower($i)!=$i)c=toupper(c)o=oc}else{o=o$i}}printo}
Hello, HAL !
Uryyb, UNY !
INPUT "String: ", s$PRINT "Output: ", REPLACE$(s$, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM", 2)
user@host $ ./rot13 String: Oolite quick Thargoid jumps lazy Vipers = blown up + special fxOutput: Bbyvgr dhvpx Gunetbvq whzcf ynml Ivcref = oybja hc + fcrpvny sk
CLSINPUT"Enter a string: ",s$ans$=""FORa=1TOLEN(s$)letter$=MID$(s$,a,1)IFletter$>="A"ANDletter$<="Z"THENchar$=CHR$(ASC(letter$)+13)IFchar$>"Z"THENchar$=CHR$(ASC(char$)-26)ELSEIFletter$>="a"ANDletter$<="z"THENchar$=CHR$(ASC(letter$)+13)IFchar$>"z"THENchar$=CHR$(ASC(char$)-26)ELSEchar$=letter$ENDIFans$=ans$+char$NEXTaPRINTans$
This version does the rotation in-place without the use of a second variable.
INPUT"Enter a string ";Text$FORc%=1TOLEN(Text$)SELECT CASEASC(MID$(Text$,c%,1))CASE65TO90MID$(Text$,c%,1)=CHR$(65+((ASC(MID$(Text$,c%,1))-65+13)MOD26))CASE97TO122MID$(Text$,c%,1)=CHR$(97+((ASC(MID$(Text$,c%,1))-97+13)MOD26))ENDSELECTNEXTc%PRINT"Converted......: ";Text$
Enter a string ? Oolite quick Thargoid jumps lazy Vipers = blown up + special fxConverted......: Bbyvgr dhvpx Gunetbvq whzcf ynml Ivcref = oybja hc + fcrpvny sk
remReturntheROT13transformationofs$,preservingcase\andpassingnon-alphabeticcharacterswithoutchangedeffn.rot13$(s$)normal$="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"rotated$="NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm"outstr$=""fori%=1tolen(s$)c$=mid$(s$,i%,1)k%=match(c$,normal$,1)ifk%<>0thenc$=mid$(rotated$,k%,1)outstr$=outstr$+c$nexti%fn.rot13$=outstr$returnfendplain$="The quick brown fox jumps over the lazy dog."encoded$=fn.rot13$(plain$)print"Plain Text: ";plain$print"Encoded : ";encoded$print"Restored : ";fn.rot13$(encoded$)end
Plain Text: The quick brown fox jumps over the lazy dog.Encoded : Gur dhvpx oebja sbk whzcf bire gur ynml qbt.Restored : The quick brown fox jumps over the lazy dog.
100remROT-13110cls:rem110HOMEforApplesoftBASIC120input"Enter a string: ";a$130gosub160140printb$150end160remFUNCTIONrot13170fori=1tolen(a$)180n=asc(mid$(a$,i,1))190e=255200ifn>64andn<91thene=90:remuppercase210ifn>96andn<123thene=122:remlowercase220ife<255thenn=n+13230ifn>ethenn=n-26240b$=b$+chr$(n)250next260return
100REM ROT-13110CLS:REM110HOMEforApplesoftBASIC120INPUT"Enter a string: ";a$130GOSUB160140PRINTb$150END160REM FUNCTION rot13170FORi=1TOLEN(a$)180n=ASC(MID$(a$,i,1))190e=255200IFn>64ANDn<91THENe=90:REMuppercase210IFn>96ANDn<123THENe=122:REMlowercase220IFe<255THENn=n+13230IFn>eTHENn=n-26240b$=b$+CHR$(n)250NEXT260RETURN
FUNCTIONrot13$(s$)LETans$=""FORa=1tolen(s$)LETletter$=(s$)[a:a+1-1]IFletter$>="A"andletter$<="Z"thenLETchar$=chr$(ord(letter$[1:1])+13)IFchar$>"Z"thenLETchar$=chr$(ord(char$[1:1])-26)ELSEIFletter$>="a"andletter$<="z"thenLETchar$=chr$(ord(letter$[1:1])+13)IFchar$>"z"thenLETchar$=chr$(ord(char$[1:1])-26)ELSELETchar$=letter$ENDIFLETans$=ans$&char$NEXTaLETs$=ans$LETrot13$=s$ENDFUNCTIONINPUTprompt"Enter a string: ":s$PRINT"Before encoding : ";s$PRINT"After encoding : ";rot13$(s$)LETs$=rot13$(s$)PRINT"After decoding : ";rot13$(s$)END
PROGRAM"Rot-13"VERSION"0.0000"DECLAREFUNCTIONEntry()FUNCTIONEntry()dec$=""TYPE$="cleartext "ctext$=""iOffset=13'offset assumed to be 13 - uncomment line 11 to changePRINT"For decrypt enter "+"<d> "+" -- else press enter > ";dec$=INLINE$("")PRINTIFLCASE$(dec$)="d"THENiOffset=26-iOffsetTYPE$="ciphertext "ENDIFPRINT"Enter "+TYPE$;'' + "> ";cad$=UCASE$(INLINE$("> "))FORi=1TOLEN(cad$)iTemp=ASC(MID$(cad$,i,1))IFiTemp>64ANDiTemp<91THENiTemp=((iTemp-65)+iOffset)MOD26PRINTCHR$(iTemp+65);ENDIFNEXTiENDFUNCTIONENDPROGRAM
#rot13Cipherv2.0#basic2561.1.4.0#2101031238dec$=""type$="cleartext "ctext$=""sp=0iOffset=13#offsetassumedtobe13-uncommentline11tochangeinput"For decrypt enter "+"<d> "+" -- else press enter > ",dec$#input"Enter offset > ",iOffsetifdec$="d"ORdec$="D"theniOffset=26-iOffsettype$="ciphertext "endifinput"Enter "+type$+"> ",str$str$=upper(str$)fori=1tolength(str$)iTemp=asc(mid(str$,i,1))ifiTemp>64ANDiTemp<91theniTemp=((iTemp-65)+iOffset)%26printchr(iTemp+65);sp=sp+1ifsp=5thenprint(' ');sp=0endifendifnexti
This is a rewrite of the original version. Output:We are discovered. Flee at once.JRNER QVFPB IRERQ SYRRN GBAPR
@echo off & setlocal enabledelayedexpansion:: ROT13 obfuscator Michael Sanders - 2017:::: example: rot13.cmd Rire abgvpr cflpuvpf arire jva gur ybggrel?:setup set str=%* set buf=%str% set len=0:getlength if not defined buf goto :start set buf=%buf:~1% set /a len+=1 goto :getlength:start if %len% leq 0 (echo rot13: zero length string & exit /b 1) set abc=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz set nop=NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm set r13= set num=0 set /a len-=1:rot13 for /l %%x in (!num!,1,%len%) do ( set log=0 for /l %%y in (0,1,51) do ( if "!str:~%%x,1!"=="!abc:~%%y,1!" ( call set r13=!r13!!nop:~%%y,1! set /a num=%%x+1 set /a log+=1 if !num! lss %len% goto :rot13 ) ) if !log!==0 call set r13=!r13!!str:~%%x,1! ):done echo !r13! endlocal & exit /b 0
REPEATINPUTA$PRINTFNrot13(A$)UNTILFALSEENDDEFFNrot13(A$)LOCALA%,B$,C$IFA$=""THEN=""FORA%=1TOLENA$C$=MID$(A$,A%,1)IFC$<"A"OR(C$>"Z"ANDC$<"a")ORC$>"z"THENB$=B$+C$ELSEIF(ASC(C$)AND&DF)<ASC("N")THENB$=B$+CHR$(ASC(C$)+13)ELSEB$=B$+CHR$(ASC(C$)-13)ENDIFENDIFNEXTA%=B$
get "libhdr"let rot13(x) = 'A' <= x <= 'Z' -> (x - 'A' + 13) rem 26 + 'A', 'a' <= x <= 'z' -> (x - 'a' + 13) rem 26 + 'a', x let start() be$( let ch = rdch() if ch = endstreamch then break wrch(rot13(ch))$) repeat
~:"z"`#v_:"m"`#v_:"`"`|>:"Z"`#v_:"M"`#v_:"@"`|>:0`#v_@v-6-7<>,<<+6+7<<v
chars←⥊"AaNn"+⌜↕13Rot13←{𝕨⊣⌾((𝕩=52)⊸/)⊏⟜chars52|26+𝕩}⟜(chars⊸⊐)
Test:
Rot13"Abcdefghijklm:Nopqrstuvwxyz_123 aBCDEFGHIJKLM-nOPQRSTUVWXYZ."
"Nopqrstuvwxyz:Abcdefghijklm_123 nOPQRSTUVWXYZ-aBCDEFGHIJKLM."
blsq ) "HELLO WORLD"{{'A'Zr\\/Fi}m[13?+26.%'A'Zr\\/si}ww"URYYB JBEYQ"blsq ) "URYYB JBEYQ"{{'A'Zr\\/Fi}m[13?+26.%'A'Zr\\/si}ww"HELLO WORLD"
The following code can handle all character sets, even if the letters are not in a contiguous range (in ASCII they are, in EBCDIC they aren't).
#include<ctype.h>#include<limits.h>#include<stdio.h>#include<stdlib.h>staticcharrot13_table[UCHAR_MAX+1];staticvoidinit_rot13_table(void){staticconstunsignedcharupper[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ";staticconstunsignedcharlower[]="abcdefghijklmnopqrstuvwxyz";for(intch='\0';ch<=UCHAR_MAX;ch++){rot13_table[ch]=ch;}for(constunsignedchar*p=upper;p[13]!='\0';p++){rot13_table[p[0]]=p[13];rot13_table[p[13]]=p[0];}for(constunsignedchar*p=lower;p[13]!='\0';p++){rot13_table[p[0]]=p[13];rot13_table[p[13]]=p[0];}}staticvoidrot13_file(FILE*fp){intch;while((ch=fgetc(fp))!=EOF){fputc(rot13_table[ch],stdout);}}intmain(intargc,char*argv[]){init_rot13_table();if(argc>1){for(inti=1;i<argc;i++){FILE*fp=fopen(argv[i],"r");if(fp==NULL){perror(argv[i]);returnEXIT_FAILURE;}rot13_file(fp);fclose(fp);}}else{rot13_file(stdin);}returnEXIT_SUCCESS;}
usingSystem;usingSystem;usingSystem.IO;usingSystem.Linq;usingSystem.Text;classProgram{privatestaticcharshift(charc){returnc.ToString().ToLower().First()switch{>='a'and<='m'=>(char)(c+13),>='n'and<='z'=>(char)(c-13),var_=>c};}staticstringRot13(strings)=>newstring(s.Select(c=>shift(c)).ToArray());staticvoidMain(string[]args){foreach(varfileinargs.Where(file=>File.Exists(file))){Console.WriteLine(Rot13(File.ReadAllText(file)));}if(!args.Any()){Console.WriteLine(Rot13(Console.In.ReadToEnd()));}}}
#include<iostream>#include<istream>#include<ostream>#include<fstream>#include<cstdlib>#include<string>// the rot13 functionstd::stringrot13(std::strings){staticstd::stringconstlcalph="abcdefghijklmnopqrstuvwxyz",ucalph="ABCDEFGHIJKLMNOPQRSTUVWXYZ";std::stringresult;std::string::size_typepos;result.reserve(s.length());for(std::string::iteratorit=s.begin();it!=s.end();++it){if((pos=lcalph.find(*it))!=std::string::npos)result.push_back(lcalph[(pos+13)%26]);elseif((pos=ucalph.find(*it))!=std::string::npos)result.push_back(ucalph[(pos+13)%26]);elseresult.push_back(*it);}returnresult;}// function to output the rot13 of a file on std::cout// returns false if an error occurred processing the file, true otherwise// on entry, the argument is must be open for readingintrot13_stream(std::istream&is){std::stringline;while(std::getline(is,line)){if(!(std::cout<<rot13(line)<<"\n"))returnfalse;}returnis.eof();}// the main programintmain(intargc,char*argv[]){if(argc==1)// no arguments givenreturnrot13_stream(std::cin)?EXIT_SUCCESS:EXIT_FAILURE;std::ifstreamfile;for(inti=1;i<argc;++i){file.open(argv[i],std::ios::in);if(!file){std::cerr<<argv[0]<<": could not open for reading: "<<argv[i]<<"\n";returnEXIT_FAILURE;}if(!rot13_stream(file)){if(file.eof())// no error occurred for file, so the error must have been in outputstd::cerr<<argv[0]<<": error writing to stdout\n";elsestd::cerr<<argv[0]<<": error reading from "<<argv[i]<<"\n";returnEXIT_FAILURE;}file.clear();file.close();if(!file)std::cerr<<argv[0]<<": warning: closing failed for "<<argv[i]<<"\n";}returnEXIT_SUCCESS;}
Here is an other approach which can rotate by any number:
#include<iostream>#include<string>#include<boost/iostreams/concepts.hpp> // output_filter#include<boost/iostreams/operations.hpp> // put#include<boost/iostreams/filtering_stream.hpp>#include<fstream>namespaceio=boost::iostreams;classrot_output_filter:publicio::output_filter{public:explicitrot_output_filter(intr=13):rotby(r),negrot(alphlen-r){};template<typenameSink>boolput(Sink&dest,intc){charuc=toupper(c);if(('A'<=uc)&&(uc<=('Z'-rotby)))c=c+rotby;elseif((('Z'-rotby)<=uc)&&(uc<='Z'))c=c-negrot;returnboost::iostreams::put(dest,c);};private:staticconstintalphlen=26;constintrotby;constintnegrot;};intmain(intargc,char*argv[]){io::filtering_ostreamout;out.push(rot_output_filter(13));out.push(std::cout);if(argc==1)out<<std::cin.rdbuf();elsefor(inti=1;i<argc;++i){std::ifstreamin(argv[i]);out<<in.rdbuf();}}
#include<string>#include<iostream>#include<fstream>charrot13(constcharc){if(c>='a'&&c<='z')return(c-'a'+13)%26+'a';elseif(c>='A'&&c<='Z')return(c-'A'+13)%26+'A';returnc;}std::string&rot13(std::string&s){for(auto&c:s)//range based for is the only used C++11 featurec=rot13(c);returns;}voidrot13(std::istream&in,std::ostream&out){std::strings;while(std::getline(in,s))out<<rot13(s)<<'\n';}intmain(intargc,char*argv[]){if(argc==1)rot13(std::cin,std::cout);for(intarg=1;arg<argc;++arg){std::ifstreamf(argv[arg]);if(!f)returnEXIT_FAILURE;rot13(f,std::cout);}}
All invocations produce "Gur Dhvpx Oebja Sbk Whzcrq Bire Gur Ynml Qbt!"
(nsrosettacode.rot-13)(let[a(int\a)m(int\m)A(int\A)M(int\M)n(int\n)z(int\z)N(int\N)Z(int\Z)](defnrot-13[^Characterc](char(let[i(intc)](cond->i(or(<=aim)(<=AiM))(+13)(or(<=niz)(<=NiZ))(-13))))))(apply str(maprot-13"The Quick Brown Fox Jumped Over The Lazy Dog!")); An alternative implementation using a map:(let[A(into#{}"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")Am(->>(cycleA)(drop26)(take52)(zipmapA))](defnrot13[^Stringin](apply str(map#(Am%%)in))))(rot13"The Quick Brown Fox Jumped Over The Lazy Dog!")
rot13 = proc (c: char) returns (char) base: int letter: bool := false if c>='A' & c<='Z' then base := char$c2i('A') letter := true elseif c>='a' & c<='z' then base := char$c2i('a') letter := true end if ~letter then return(c) end return(char$i2c((char$c2i(c)-base+13)//26+base))end rot13start_up = proc () po: stream := stream$primary_output() pi: stream := stream$primary_input() while true do stream$putc(po,rot13(stream$getc(pi))) except when end_of_file: break end endend start_up
Strict COBOL-85 implementation.
FORMATIDENTIFICATIONDIVISION.PROGRAM-ID.rot-13.DATADIVISION.LINKAGESECTION.77in-strPIC X(100).77out-strPIC X(100).PROCEDUREDIVISIONUSINGBYREFERENCEin-str,out-str.MOVEin-strTOout-strINSPECTout-strCONVERTING"abcdefghijklmnopqrstuvwxyz"TO"nopqrstuvwxyzabcdefghijklm"INSPECTout-strCONVERTING"ABCDEFGHIJKLMNOPQRSTUVWXYZ"TO"NOPQRSTUVWXYZABCDEFGHIJKLM"EXITPROGRAM.ENDPROGRAMrot-13.
A more modern version, with a user-defined function and compile-time constants.
IDENTIFICATIONDIVISION.FUNCTION-ID.rot-13.DATADIVISION.LOCAL-STORAGESECTION.01STR-LENGTHCONSTANTAS100.01normal-lowerCONSTANTAS"abcdefghijklmnopqrstuvwxyz".01rot13-lowerCONSTANTAS"nopqrstuvwxyzabcdefghijklm".01normal-upperCONSTANTAS"ABCDEFGHIJKLMNOPQRSTUVWXYZ".01rot13-upperCONSTANTAS"NOPQRSTUVWXYZABCDEFGHIJKLM".LINKAGESECTION.77in-strPICTURE ISX(STR-LENGTH).77out-strPICTURE ISX(STR-LENGTH).PROCEDUREDIVISIONUSINGin-str,RETURNINGout-str.MOVEin-strTOout-strINSPECTout-strCONVERTINGnormal-lowerTOrot13-lowerINSPECTout-strCONVERTINGnormal-upperTOrot13-upperGOBACK.ENDFUNCTIONrot-13.
Very generic implementation. Please note that in Commodore BASIC, SHIFT-typed letters (to generate either graphic symbols in upper-case mode, or capital letters in lower-case mode) donot translate to PETSCII characters 97 through 122, but instead to characters 193 through 218.
1remrot-13cipher2remrosettacode10printchr$(147);chr$(14);25gosub100030printchr$(147);"Enter a message to translate."35print:print"Press CTRL-Z when finished.":print40mg$="":gosub200045printchr$(147);"Processing...":gosub300050printchr$(147);"The translated message is:"55print:printcm$100print:print"Do another one? ";110getk$:ifk$<>"y"andk$<>"n"then110120printk$:ifk$="y"thengoto10130end1000remgenerateencodingtable1010ec$="mnopqrstuvwxyzabcdefghijklMNOPQRSTUVWXYZABCDEFGHIJKL"1099return2000remgetuserinputroutine2005printchr$(18);" ";chr$(146);chr$(157);2010getk$:ifk$=""then20102012ifk$=chr$(13)thenprint" ";chr$(157);2015printk$;2020ifk$=chr$(20)thenmg$=left$(mg$,len(mg$)-1):goto20402025iflen(mg$)=255ork$=chr$(26)thenreturn2030mg$=mg$+k$2040goto20053000remtranslatemessage3005cm$=""3010fori=1tolen(mg$)3015c=asc(mid$(mg$,i,1))3020ifc<65or(c>90andc<193)orc>218thencm$=cm$+chr$(c):goto30303025ifc>=65andc<=90thenc=c-643030ifc>=193andc<=218thenc=(c-192)+263035cm$=cm$+mid$(ec$,c,1)3040nexti3050return
Enter a message to translate. Press CTRL-Z when finished.You know it is going to be a bad daywhen the letters in your alphabet soupspell D-I-S-A-S-T-E-R.Processing...The translated message is: Lbh xabj vg vf tbvat gb or n onq qnljura gur yrggref va lbhe nycunorg fbhcfcryy Q-V-F-N-F-G-R-E. Do another one? nready.█
The standard gives implementations great leeway with respect to character encodings, so we can't rely on the convenient properties of ASCII.
(defconstant+alphabet+'(#\A#\B#\C#\D#\E#\F#\G#\H#\I#\J#\K#\L#\M#\N#\O#\P#\Q#\R#\S#\T#\U#\V#\W#\X#\Y#\Z))(defunrot13(s)(map'string(lambda(c&aux(n(position(char-upcasec)+alphabet+)))(ifn(funcall(if(lower-case-pc)#'char-downcase#'identity)(nth(mod(+13n)26)+alphabet+))c))s))
Though the standard intentionally doesn't specify encoding, every popular implementation today uses ASCII.
(defunrot13(string)(map'string(lambda(char&aux(code(char-codechar)))(if(alpha-char-pchar)(if(>(-code(char-code(if(upper-case-pchar)#\A#\a)))12)(code-char(-code13))(code-char(+code13)))char))string))(rot13"Moron"); -> "Zbeba"
1. Equality
a = "abcdefghijklm" . "zyxwvutsrqpon"rot(a) = a i length(a) - i - 1
2. Application
(defconstant+a+"AaBbCcDdEeFfGgHhIiJjKkLlMmzZyYxXwWvVuUtTsSrRqQpPoOnN")(defunrot(txt)(map'string#'(lambda(x)(if(findx+a+)(char+a+(-51(positionx+a+)))x))txt))
3. Execution
(rot "Usenet rulez !")Hfrarg ehyrm !(rot "Hfrarg ehyrm !")Usenet rulez !
That's all Folks !
cyril nocton : <cyril.nocton@gmail.com>
alias rot13 [push alpha ["A B C D E F G H I J K L M N O P Q R S T U V W X Y Z""a b c d e f g h i j k l m n o p q r s t u v w x y z"] [ push chars [] [loop i (strlen $arg1) [looplist n $alpha [if (! (listlen $chars)) [alias chars (? (> (listindex $n (substr $arg1 $i 1)) -1) $n [])]]alias arg1 (concatword (substr $arg1 0 $i) (? (listlen $chars) (at $chars (mod (+ (listindex $chars (substr $arg1 $i 1)) 13 ) (listlen $chars))) (substr $arg1 $i 1)) (substr $arg1 (+ $i 1) (strlen $arg1)))alias chars []]] ]result $arg1]
Usage:
>>> rot13 "Hello World"> Uryyb Jbeyq>>> rot13 "Gur Dhvpx Oebja Sbk Whzcf Bire Gur Ynml Qbt!"> The Quick Brown Fox Jumps Over The Lazy Dog!
importstd.stdio;importstd.ascii:letters,U=uppercase,L=lowercase;importstd.string:makeTrans,translate;immutabler13=makeTrans(letters,//U[13 .. $] ~ U[0 .. 13] ~U[13..U.length]~U[0..13]~L[13..L.length]~L[0..13]);voidmain(){writeln("This is the 1st test!".translate(r13,null));}
The Quick Brown Fox Jumps Over The Lazy Dog!
importstd.stdio,std.string,std.traits;pureSrot13(S)(inSs)if(isSomeString!S){returnrot(s,13);}pureSrot(S)(inSs,inintkey)if(isSomeString!S){autor=s.dup;foreach(i,refc;r){if('a'<=c&&c<='z')c=((c-'a'+key)%26+'a');elseif('A'<=c&&c<='Z')c=((c-'A'+key)%26+'A');}returncast(S)r;}voidmain(){"Gur Dhvpx Oebja Sbk Whzcf Bire Gur Ynml Qbt!".rot13().writeln();}
Stringrot13char(intcharCode){if((charCode>='A'.codeUnitAt(0)&&charCode<='M'.codeUnitAt(0))||(charCode>='a'.codeUnitAt(0)&&charCode<='m'.codeUnitAt(0))){returnString.fromCharCode(charCode+13);}elseif((charCode>='N'.codeUnitAt(0)&&charCode<='Z'.codeUnitAt(0))||(charCode>='n'.codeUnitAt(0)&&charCode<='z'.codeUnitAt(0))){returnString.fromCharCode(charCode-13);}else{returnString.fromCharCode(charCode);}}Stringrot13(Stringstr){returnString.fromCharCodes(str.runes.map((rune){returnrot13char(rune).codeUnitAt(0);}));}voidmain(){print(rot13("The quick brown fox jumps over the lazy dog"));}
Gur dhvpx oebja sbk whzcf bire gur ynml qbt
programRot13;{$APPTYPE CONSOLE}usesSystem.SysUtils;functionRot13char(c:AnsiChar):AnsiChar;beginResult:=c;ifcin['a'..'m','A'..'M']thenResult:=AnsiChar(ord(c)+13)elseifcin['n'..'z','N'..'Z']thenResult:=AnsiChar(ord(c)-13);end;functionRot13Fn(s:ansistring):ansistring;vari:Integer;beginSetLength(result,length(s));fori:=1tolength(s)doResult[i]:=Rot13char(s[i]);end;beginwriteln(Rot13Fn('nowhere ABJURER'));readln;end.
func Char.Rot13() { return Char(this.Order() + 13) when this is >= 'a' and <= 'm' or >= 'A' and <= 'M' return Char(this.Order() - 13) when this is >= 'n' and <= 'z' or >= 'N' and <= 'Z' return this} func String.Rot13() { var cs = [] for c in this { cs.Add(c.Rot13()) } String.Concat(values: cs)} "ABJURER nowhere".Rot13()
"NOWHERE abjurer"
rot-13:)for ch in chars swap:ord chif <= 65 dup:if >= 90 dup:+ 13 - swap 65+ 65 % swap 26if <= 97 dup:if >= 122 dup:+ 13 - swap 97+ 97 % swap 26chrconcat(!print rot-13 "Snape kills Frodo with Rosebud."
Fancr xvyyf Sebqb jvgu Ebfrohq.
pragma.enable("accumulator")var rot13Map := [].asMap()for a in ['a', 'A'] { for i in 0..!26 { rot13Map with= (a + i, E.toString(a + (i + 13) % 26)) }}def rot13(s :String) { return accum "" for c in s { _ + rot13Map.fetch(c, fn{ c }) }}
func$ rot13 str$ . for c$ in strchars str$ c = strcode c$ if c >= 65 and c <= 90 c = (c + 13 - 65) mod 26 + 65 elif c >= 97 and c <= 122 c = (c + 13 - 97) mod 26 + 97 . enc$ &= strchar c . return enc$.enc$ = rot13 "Rosetta Code"print enc$print rot13 enc$
H,pg/([[:alpha:]])/s// \1 /gg/[ ]a[ ]/s//%n%/gg/[ ]b[ ]/s//%o%/gg/[ ]c[ ]/s//%p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whzcf bire gur ynml erq qbt.?Warning: buffer modified
ELENA 6.x :
import system'routines;import extensions;import extensions'text; singleton rotConvertor{ char convert(char ch) { if (($97 <= ch && ch <= $109) || ($65 <= ch && ch <= $77)) { ^ (ch.toInt() + 13).toChar() }; if (($110 <= ch && ch <= $122) || ($78 <= ch && ch <= $90)) { ^ (ch.toInt() - 13).toChar() }; ^ ch } string convert(string s) = s.selectBy::(ch => rotConvertor.convert(ch)).summarize(new StringWriter());} public program(){ if (program_arguments.Length > 1) { console.printLine(rotConvertor.convert(program_arguments[1])) }}
rot13 "Hello World"Hryyb Wbeyq
A simple conditional version.
defmoduleRCdodefrot13(clist)dof=fn(c)when(?A<=candc<=?M)or(?a<=candc<=?m)->c+13(c)when(?N<=candc<=?Z)or(?n<=candc<=?z)->c-13(c)->cendEnum.map(clist,f)endendIO.inspectencode=RC.rot13('Rosetta Code')IO.inspectRC.rot13(encode)
'Ebfrggn Pbqr''Rosetta Code'
A functional version.
defmoduleRot13do@moduledoc"""ROT13 encoding program. Takes user input and outputs encoded text."""@specsign(integer|float)::-1|1defsign(int)doifint>=0do1else-1endend@specrotate(charlist)::charlistdefrotate(string_chars)dostring_chars|>Enum.map(fnchar->char_up=<<char::utf8>>|>String.upcase()|>String.to_charlist()|>Enum.at(0)if?A<=char_upandchar_up<=?Zdo<<char+(-13*trunc(sign(char_up-77.5)))::utf8>>else<<char::utf8>>endend)end@specstart(any,any)::{:ok,pid}defstart(_type,_args)doIO.puts("Enter string to encode:")IO.puts(["Encoded string:\n",IO.read(:line)|>String.trim()|>String.to_charlist()|>rotate()])Task.start(fn->:timer.sleep(1000)end)endend
Enter string to encode:NOWHERE abjurer Rosetta Code 123Encoded string:ABJURER nowhere Ebfrggn Pbqr 123
Emacs comes with built-in rot-13 support for translating strings,buffers and regions:
(rot13-string"abc");=> "nop"(with-temp-buffer(insert"abc")(rot13-region(point-min)(point-max))(buffer-string));=> "nop"
A more specialized version which only works on strings:
(defunrot-13(string)(let*((len(lengthstring))(output(make-stringlen?\s)))(dotimes(ilen)(let((char(arefstringi)))(cond((or(and(>=char?n)(<=char?z))(and(>=char?N)(<=char?Z)))(asetoutputi(-char13)))((or(and(>=char?a)(<=char?m))(and(>=char?A)(<=char?M)))(asetoutputi(+char13)))(t(asetoutputichar)))))output))
rot13(Str)->F=fun(C)when(C>=$AandalsoC=<$M);(C>=$aandalsoC=<$m)->C+13;(C)when(C>=$NandalsoC=<$Z);(C>=$nandalsoC=<$z)->C-13;(C)->Cend,lists:map(F,Str).
PROGRAM ROT13BEGININPUT("Enter a string ",TEXT$)FOR C%=1 TO LEN(TEXT$) DO A%=ASC(MID$(TEXT$,C%,1)) CASE A% OF 65..90-> MID$(TEXT$,C%,1)=CHR$(65+(A%-65+13) MOD 26) END -> 97..122-> MID$(TEXT$,C%,1)=CHR$(97+(A%-97+13) MOD 26) END -> END CASEEND FORPRINT("Converted: ";TEXT$)END PROGRAM
Enter a string ? pippoConverted: cvccb
include std/types.einclude std/text.eatom FALSE = 0atom TRUE = not FALSEfunction Rot13( object oStuff )integer iOffsetinteger bIsUpperobject oResultsequence sAlphabet = "abcdefghijklmnopqrstuvwxyz"if sequence(oStuff) thenoResult = repeat( 0, length( oStuff ) )for i = 1 to length( oStuff ) dooResult[ i ] = Rot13( oStuff[ i ] )end forelsebIsUpper = FALSEif t_upper( oStuff ) thenbIsUpper = TRUEoStuff = lower( oStuff )end ifiOffset = find( oStuff, sAlphabet )if iOffset != 0 theniOffset += 13iOffset = remainder( iOffset, 26 )if iOffset = 0 then iOffset = 1 end ifoResult = sAlphabet[iOffset]if bIsUpper thenoResult = upper(oResult)end ifelseoResult = oStuff --sprintf( "%s", oStuff )end ifend ifreturn oResultend functionputs( 1, Rot13( "abjurer NOWHERE." ) & "\n" )
Illustrates turning a string into an array of chars then composition of type casting with a conversion function. We create a composite that converts its input to an integer, calls the convertion function andthen casts to a char type. The result is an array of modified chars that we can use to create a new string.
letrot13(s:string)=letrotc=matchcwith|cwhenc>64&&c<91->((c-65+13)%26)+65|cwhenc>96&&c<123->((c-97+13)%26)+97|_->cs|>Array.of_seq|>Array.map(int>>rot>>char)|>(funseq->newstring(seq))
#! /usr/bin/env factorUSING:kernelioasciimathcombinatorssequences;IN:rot13:rot-base(chch--ch)[-13+26mod]keep+;:rot13-ch(ch--ch){{[dupletter?][CHAR:arot-base]}{[dupLETTER?][CHAR:Arot-base]}[]}cond;:rot13(str--str)[rot13-ch]map;:main(--)[readlndup][rot13printflush]whiledrop;MAIN:main
[^$1+][$32|$$'z>'a@>|$[\%]?~[13\'m>[_]?+]?,]#%
class Rot13{ static Str rot13 (Str input) { Str result := "" input.each |Int c| { if ((c.lower >= 'a') && (c.lower <= 'm')) result += (c+13).toChar else if ((c.lower >= 'n') && (c.lower <= 'z')) result += (c-13).toChar else result += c.toChar } return result } public static Void main (Str[] args) { if (args.size == 1) { // process each line of given file Str filename := args[0] File(filename.toUri).eachLine |Str line| { echo (rot13(line)) } } else { echo ("Test:") Str text := "abcstuABCSTU123!+-" echo ("Text $text becomes ${rot13(text)}") } }}
Implements a circular queue, finds the required character and then rotates the queue forward 13 places. Would do as a solution to Caesar Cipher with a different rotation number. Please note that FBSL is not case sensitive, thus the use of lstrcmp.
#APPTYPECONSOLEREM Create a CircularQueue objectREM CQ.Store itemREM CQ.Find itemsREM CQ.Forward nItemsREM CQ.RecallREM SO CQ init WITH "A"... "Z"REM CQ.Find "B"REM QC.Forward 13REM QC.RecallCLASSCircularQueueitems[]headtailhereSUBINITIALIZE(dArray)head=0tail=0here=0FORDIMi=LBOUND(dArray)TOUBOUND(dArray)items[tail]=dArray[i]tail=tail+1NEXTENDSUBSUBTERMINATE()REMENDSUBMETHODPut(sASSTRING)items[tail]=stail=tail+1ENDMETHODMETHODFind(sASSTRING)FORDIMi=headTOtail-1IFitems[i]=sTHENhere=iRETURNTRUEENDIFNEXTRETURNFALSEENDMETHODMETHODMove(nASINTEGER)DIMboundASINTEGER=UBOUND(items)+1here=(here+n)MODboundENDMETHODMETHODRecall()RETURNitems[here]ENDMETHODPROPERTYSize()RETURNCOUNT(items)ENDPROPERTYENDCLASSDIMCQASNEWCircularQueue({"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"})DIMcASSTRINGDIMisUppercaseASINTEGERDIMsASSTRING="nowhere ABJURER"FORDIMi=1TOLEN(s)c=MID(s,i,1)isUppercase=lstrcmp(LCASE(c),c)IFCQ.Find(UCASE(c))THENCQ.Move(13)PRINTIIF(isUppercase,UCASE(CQ.Recall()),LCASE(CQ.Recall()));ELSEPRINTc;ENDIFNEXTPAUSE
(fnrot13[s](let[a:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzb:NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm](s:gsub:%a#(b:sub(a:find$)))))
A simple version, using nested conditionals.
:r13( c -- o )dup32or\ tolowerdup[char]a[char]z1+withinif[char]m>if-13else13then+elsedropthen;
A table driven version which should be more efficient. The mechanism is flexible enough to express any sort of transform.
:,chars( end start -- )doic,loop;:xlatecreatedoes>( c -- c' )+c@;xlaterot13charA0,charscharZ1+charN,charscharNcharA,charscharacharZ1+,charscharz1+charn,charscharnchara,chars256charz1+,chars:rot13-string( addr len -- )over+swapdoic@rot13ic!loop;:.rot13"( string -- )[char]"parse2duprot13-stringtype;.rot13"abjurerNOWHERE"\ nowhere ABJURER
programtest_rot_13implicit noneinteger,parameter::len_max=256integer,parameter::unit=10character(len_max)::filecharacter(len_max)::fmtcharacter(len_max)::lineinteger::arginteger::arg_maxinteger::iostatwrite(fmt,'(a, i0, a)')'(a',len_max,')'arg_max=iargc()if(arg_max>0)then! Encode all files listed on the command line.doarg=1,arg_maxcallgetarg(arg,file)open(unit,file=file,iostat=iostat)if(iostat/=0)cycle do read(unit,fmt=fmt,iostat=iostat)lineif(iostat/=0)exit write(*,'(a)')trim(rot_13(line))end do close(unit)end do else! Encode standard input.do read(*,fmt=fmt,iostat=iostat)lineif(iostat/=0)exit write(*,'(a)')trim(rot_13(line))end do end ifcontains functionrot_13(input)result(output)implicit nonecharacter(len_max),intent(in)::inputcharacter(len_max)::outputinteger::ioutput=inputdoi=1,len_trim(output)select case(output(i:i))case('A':'M','a':'m')output(i:i)=char(ichar(output(i:i))+13)case('N':'Z','n':'z')output(i:i)=char(ichar(output(i:i))-13)end select end do end functionrot_13end programtest_rot_13
Note:iargc
andgetarg
are common extensions that are implemented by e.g. the Intel Fortran Compiler, G95 and gfortran.
Sample usage:
> cat foo.txtfoo> cat bar.txtbar> ./rot_13 foo.txt bar.txtsbbone> ./rot_13 < foo.txtsbb> cat foo.txt bar.txt | ./rot_13sbbone
' FB 1.05.0 Win64' uses in place encoding/decodingSubrot13(ByRefsAsString)Ifs=""ThenExitSubDimcodeAsIntegerForiAsInteger=0ToLen(s)-1SelectCaseAsConsts[i]Case65To90'' A to Zcode=s[i]+13Ifcode>90Thencode-=26s[i]=codeCase97To122'' a to zcode=s[i]+13Ifcode>122Thencode-=26s[i]=codeEndSelectNextEndSubDimsAsString="nowhere ABJURER"Print"Before encoding : ";srot13(s)Print"After encoding : ";srot13(s)Print"After decoding : ";sPrintPrint"Press any key to quit"Sleep
Before encoding : nowhere ABJURERAfter encoding : abjurer NOWHEREAfter decoding : nowhere ABJURER
import io.{lines, stdin}def rot13( s ) = buf = StringBuilder() for c <- s if isalpha( c ) n = ((ord(c) and 0x1F) - 1 + 13)%26 + 1 buf.append( chr(n or (if isupper(c) then 64 else 96)) ) else buf.append( c ) buf.toString()def rot13lines( ls ) = for l <- ls println( rot13(l) )if _name_ == '-main-' if args.isEmpty() rot13lines( stdin() ) else for f <- args rot13lines( lines(f) )
rot13:=function(s)localupper,lower,c,n,t;upper:="ABCDEFGHIJKLMNOPQRSTUVWXYZ";lower:="abcdefghijklmnopqrstuvwxyz";t:=[];forcinsdon:=Position(upper,c);ifn<>failthenAdd(t,upper[((n+12)mod26)+1]);elsen:=Position(lower,c);ifn<>failthenAdd(t,lower[((n+12)mod26)+1]);elseAdd(t,c);fi;fi;od;returnt;end;a:="England expects that every man will do his duty";# "England expects that every man will do his duty"b:=rot13(a);# "Ratynaq rkcrpgf gung rirel zna jvyy qb uvf qhgl"c:=rot13(b);# "England expects that every man will do his duty"
/[a-mA-M]/=@int-char{@add{@char-int{$1};13}}/[n-zN-Z]/=@int-char{@sub{@char-int{$1};13}}
#define rot13var in, out, i, working;in = argument0;out = "";for (i = 1; i <= string_length(in); i += 1) { working = ord(string_char_at(in, i)); if ((working > 64) && (working < 91)) { working += 13; if (working > 90) { working -= 26; } } else if ((working > 96) && (working < 123)) { working += 13; if (working > 122) working -= 26; } out += chr(working); }return out;
The above code is called like this:
show_message(rot13("My dog has fleas!"));
Output (in a message box):
Zl qbt unf syrnf!
packagemainimport("fmt""strings")funcrot13char(crune)rune{ifc>='a'&&c<='m'||c>='A'&&c<='M'{returnc+13}elseifc>='n'&&c<='z'||c>='N'&&c<='Z'{returnc-13}returnc}funcrot13(sstring)string{returnstrings.Map(rot13char,s)}funcmain(){fmt.Println(rot13("nowhere ABJURER"))}
Output:
abjurer NOWHERE
{\{=}+\%1?)}:in;{91,65>''+}:A;{123,97>''+}:a;{ .A in { A?13+26%A= } {.a in { a?13+26%a= }{}if }if}:r13;{r13}%
Hello world!
:Uryyb jbeyq!
#!/usr/bin/env golosh----This module encrypts strings by rotating each character by 13.----moduleRot13augmentjava.lang.Character{functionrot13=|this|->match{whenthis>='a'andthis<='z'thencharValue((this-'a'+13)%26+'a')whenthis>='A'andthis<='Z'thencharValue((this-'A'+13)%26+'A')otherwisethis}}augmentjava.lang.String{functionrot13=|this|->vector[this:charAt(i):rot13()foreachiin[0..this:length()]]:join("")}functionmain=|args|{require('A':rot13()=='N',"A is not N")require("n":rot13()=="a","n is not a")require("nowhere ABJURER":rot13()=="abjurer NOWHERE","nowhere is not abjurer")foreachstringinargs{print(string:rot13())print("")}println("")}
Solution:
defrot13={Strings->(sasList).collect{ch->switch(ch){case('a'..'m')+('A'..'M'):return(((chaschar)+13)aschar)case('n'..'z')+('N'..'Z'):return(((chaschar)-13)aschar)default:returnch}}.inject(""){string,ch->string+=ch}}
Test program:
printlnrot13("Noyr jnf V, 'rer V fnj Ryon.")
Output:
Able was I, 'ere I saw Elba.
10INPUT"Enter a string: ",A$20GOSUB5030PRINTB$40END50FORI=1TOLEN(A$)60N=ASC(MID$(A$,I,1))70E=25580IFN>64ANDN<91THENE=90' uppercase90IFN>96ANDN<123THENE=122' lowercase100IFE<255THENN=N+13110IFN>ETHENN=N-26120B$=B$+CHR$(N)130NEXT140RETURN
Straightforward implementation by checking multiple cases:
importData.Char(chr,isAlpha,ord,toLower)importData.Bool(bool)rot13::Char->Charrot13c|isAlphac=chr$bool(-)(+)('m'>=toLowerc)(ordc)13|otherwise=c-- Simple testmain::IO()main=print$rot13<$>"Abjurer nowhere"
Or in point-free applicative terms:
importData.Char(chr,isAlpha,ord,toLower)importData.Bool(bool)rot13::Char->Charrot13=letrot=flip((bool(-)(+).('m'>=).toLower)<*>ord)in(bool<*>chr.rot13)<*>isAlpha-- Simple testmain::IO()main=print$rot13<$>"Abjurer nowhere"
"Nowhere abjurer"
To wrap rot13 as a utility program, here's a quick implementation of a general framework:
importSystem.EnvironmentimportSystem.IOimportSystem.DirectoryimportControl.MonadhInteract::(String->String)->Handle->Handle->IO()hInteractfhInhOut=hGetContentshIn>>=hPutStrhOut.fprocessByTemp::(Handle->Handle->IO())->String->IO()processByTempfname=dohIn<-openFilenameReadModelettmp=name++"$"hOut<-openFiletmpWriteModefhInhOuthClosehInhClosehOutremoveFilenamerenameFiletmpnameprocess::(Handle->Handle->IO())->[String]->IO()processf[]=fstdinstdoutprocessfns=mapM_(processByTempf)ns
Then the wrapped program is simply
main=donames<-getArgsprocess(hInteract(maprot13))names
Note that the framework will read the file lazily, which also provides buffering.
CHARACTER c, txt='abc? XYZ!', cod*100 DO i = 1, LEN_TRIM(txt) c = txt(i) n = ICHAR(txt(i)) IF( (c >= 'a') * (c <= 'm') + (c >= 'A') * (c <= 'M') ) THEN c = CHAR( ICHAR(c) + 13 ) ELSEIF( (c >= 'n') * (c <= 'z') + (c >= 'N') * (c <= 'Z') ) THEN c = CHAR( ICHAR(c) - 13 ) ENDIF cod(i) = c ENDDO WRITE(ClipBoard, Name) txt, cod ! txt=abc? XYZ!; cod=nop? KLM!;END
publicstaticfunctionrot13(input:String):String{varbuf=newStringBuf();for(charIntinnewhaxe.iterators.StringIterator(input)){if(charInt>=0x41&&charInt<=0x4d||charInt>=0x61&&charInt<=0x6d)charInt+=13;elseif(charInt>=0x4e&&charInt<=0x5a||charInt>=0x6e&&charInt<=0x7a)charInt-=13;buf.addChar(charInt);}returnbuf.toString();}
#!/usr/bin/envhy(requirehyrule[defmain])(setvlowers(lfor*x*(range26)(chr(+*x*(ord"a")))));generatelatinlower26chars(setvuppers(list(mapstr.upperlowers)));andtheuppercase(setvlowers(list(mapordlowers)));converttounicodecodepoints(setvuppers(list(maporduppers)))(setvtranslations;adictionarywithfrom->to(dict(zip;codepointmapping(+lowersuppers)(+(cutlowers13None)(cutlowers013)(cutuppers13None)(cutuppers013)))))(defnrot13[string](return(.translatestringtranslations)))(defmain[](importfileinput)(for[*line*(fileinput.input)](print(rot13*line*):end"")))
proceduremain(arglist)file:=open(arglist[1],"r")|&inputeverywrite(rot13(|read(file)))endprocedurerot13(s)#: returns rot13(string)statica,ninitial{a:=&lcase||&ucase(&lcase||&lcase)?n:=(move(13),move(*&lcase))(&ucase||&ucase)?n||:=(move(13),move(*&ucase))}returnmap(s,a,n)end
This example uses a number of Icon features.
(function ROT-13-char ch (let x (char-code ch) x- (or (< 109 x 123) (< 77 x 91))) (if (or (< 96 x 123) (< 64 x 91)) (char-code ((x- - +) x 13)) ch))(function ROT-13 text (.. str (map ROT-13-char text)))(ROT-13 "The Quick Brown Fox Jumps Over The Lazy Dog!");returns "Gur Dhvpx Oebja Sbk Whzcf Bire Gur Ynml Qbt!"
100 PROGRAM "Rot13.bas"110 DO120 LINE INPUT PROMPT "Line: ":LINE$130 PRINT ROT13$(LINE$)140 LOOP UNTIL LINE$=""150 DEF ROT13$(TEXT$)160 LET RESULT$=""170 FOR I=1 TO LEN(TEXT$)180 LET CH$=TEXT$(I)190 SELECT CASE CH$200 CASE "A" TO "M","a" TO "m"210 LET CH$=CHR$(ORD(CH$)+13)220 CASE "N" TO "Z","n" TO "z"230 LET CH$=CHR$(ORD(CH$)-13)240 CASE ELSE250 END SELECT260 LET RESULT$=RESULT$&CH$270 NEXT280 LET ROT13$=RESULT$290 END DEF
rot13=:{&((6597+/~i.213)|.@[}i.256)&.(a.&i.)
For example:
rot13 'abc! ABC!'nop! NOP!
Compare with the solution to theChange String Case task.
fn rot_13(anon string: String) throws -> String { mut builder = StringBuilder::create() for code_point in string.code_points() { builder.append(match code_point { 'a'..'n' => code_point + 13 'n'..('z' + 1) => code_point - 13 'A'..'N' => code_point + 13 'N'..('Z' + 1) => code_point - 13 else => code_point }) } return builder.to_string()}fn main() { println("{}", rot_13("The quick brown fox jumps over the lazy dog."))}
importjava.io.*;publicclassRot13{publicstaticvoidmain(String[]args)throwsIOException{if(args.length>=1){for(Stringfile:args){try(InputStreamin=newBufferedInputStream(newFileInputStream(file))){rot13(in,System.out);}}}else{rot13(System.in,System.out);}}privatestaticvoidrot13(InputStreamin,OutputStreamout)throwsIOException{intch;while((ch=in.read())!=-1){out.write(rot13((char)ch));}}privatestaticcharrot13(charch){if(ch>='A'&&ch<='Z'){return(char)(((ch-'A')+13)%26+'A');}if(ch>='a'&&ch<='z'){return(char)(((ch-'a')+13)%26+'a');}returnch;}}
functionrot13(c){returnc.replace(/([a-m])|([n-z])/ig,function($0,$1,$2){returnString.fromCharCode($1?$1.charCodeAt(0)+13:$2?$2.charCodeAt(0)-13:0)||$0;});}rot13("ABJURER nowhere")// NOWHERE abjurer
TDD with Jasmine using Underscore.js
functionrot13(value){if(!value)return"";functionsingleChar(c){if(c.toUpperCase()<"A"||c.toUpperCase()>"Z")returnc;if(c.toUpperCase()<="M")returnString.fromCharCode(c.charCodeAt(0)+13);returnString.fromCharCode(c.charCodeAt(0)-13);}return_.map(value.split(""),singleChar).join("");}describe("Rot-13",function(){it("Given nothing will return nothing",function(){expect(rot13()).toBe("");});it("Given empty string will return empty string",function(){expect(rot13("")).toBe("");});it("Given A will return N",function(){expect(rot13("A")).toBe("N");});it("Given B will return O",function(){expect(rot13("B")).toBe("O");});it("Given N will return A",function(){expect(rot13("N")).toBe("A");});it("Given Z will return M",function(){expect(rot13("Z")).toBe("M");});it("Given ZA will return MN",function(){expect(rot13("ZA")).toBe("MN");});it("Given HELLO will return URYYB",function(){expect(rot13("HELLO")).toBe("URYYB");});it("Given hello will return uryyb",function(){expect(rot13("hello")).toBe("uryyb");});it("Given hello1 will return uryyb1",function(){expect(rot13("hello1")).toBe("uryyb1");});});
#!/usr/bin/env jq -M -R -r -f# or perhaps:#!/usr/local/bin/jq -M -R -r -f# If your operating system does not allow more than one option# to be specified on the command line,# then consider using a version of jq that allows# command-line options to be squished together (-MRrf),# or see the following subsection.defrot13:explode|map(if65<=.and.<=90then((.-52)%26)+65elif97<=.and.<=122then(.-84)%26+97else.end)|implode;rot13
#!/bin/bashjq-M-R-r'def rot13: explode | map( if 65 <= . and . <= 90 then ((. - 52) % 26) + 65 elif 97 <= . and . <= 122 then (. - 84) % 26 + 97 else . end) | implode;rot13'
Example:
$ echo abc123ABC | ./rot13nop123NOP
rot13 function borrowed from Javascript entry, and modified to take into account typed parameters to functions in Jsish.
Can be used as a require module or a command line utility, and includes unit testing.
#!/usr/local/bin/jsish/* ROT-13 in Jsish */functionrot13(msg:string){returnmsg.replace(/([a-m])|([n-z])/ig,function(m,p1,p2,ofs,str){returnString.fromCharCode(p1?p1.charCodeAt(0)+13:p2?p2.charCodeAt(0)-13:0)||m;});}provide('rot13',Util.verConvert("1.0"));/* rot13 command line utility */if(isMain()){/* Unit testing */if(Interp.conf('unitTest')>0){;rot13('ABJURER nowhere 123!');;rot13(rot13('Same old same old'));return;}/* rot-13 of data lines from given filenames or stdin, to stdout */functionprocessFile(fname:string){varstr;if(fname=="stdin")fname="./stdin";if(fname=="-")fname="stdin";varfin=newChannel(fname,'r');while(str=fin.gets())puts(rot13(str));fin.close();}if(console.args.length==0)console.args.push('-');for(varfnofconsole.args){try{processFile(fn);}catch(err){puts(err,"processing",fn);}}}/*=!EXPECTSTART!=rot13('ABJURER nowhere 123!') ==> NOWHERE abjurer 123!rot13(rot13('Same old same old')) ==> Same old same old=!EXPECTEND!=*/
prompt$ jsish -e 'require("rot13"); puts(rot13("abcxyz"));'nopklmprompt$ jsish -u rot13.jsi[PASS] rot13.jsiprompt$ jsish rot13.jsithis is a stdin filter testguvf vf n fgqva svygre grfgprompt$ ./rot13.jsi rot13.jsi | head -4#!/hfe/ybpny/ova/wfvfu/* EBG-13 va Wfvfu */shapgvba ebg13(zft:fgevat) {prompt$ ./rot13.jsi rot13.jsi | head -4 | ./rot13.jsi#!/usr/local/bin/jsish/* ROT-13 in Jsish */function rot13(msg:string) {
# Julia 1.0functionrot13(c::Char)shft=islowercase(c)?'a':'A'isletter(c)?c=shft+(c-shft+13)%26:cendrot13(str::AbstractString)=map(rot13,str)
julia> rot13("abcdefghijklmnopqrtuvwxyz 123 ABCDEFGHIJKLMNOPQRTUVWXYZ")"nopqrstuvwxyzabcdeghijklm 123 NOPQRSTUVWXYZABCDEGHIJKLM"
replace("nowhere ABJURER",r"[A-Za-z]"=>s->map(c->c+(uppercase(c)<'N'?13:-13),s))
abjurer NOWHERE
rot13:{a:+6597+\:213#!26;_ci@[!256;a;:;|a]_icx}rot13"Testing! 1 2 3""Grfgvat! 1 2 3"
importjava.io.*funString.rot13()=map{when{it.isUpperCase()->{valx=it+13;if(x>'Z')x-26elsex}it.isLowerCase()->{valx=it+13;if(x>'z')x-26elsex}else->it}}.toCharArray()funInputStreamReader.println()=try{BufferedReader(this).forEachLine{println(it.rot13())}}catch(e:IOException){e.printStackTrace()}funmain(args:Array<String>){if(args.any())args.forEach{FileReader(it).println()}elseInputStreamReader(System.`in`).println()}
#!/bin/ksh# rot-13 function## Variables:#integerROT_NUM=13# Generalize to any ROTstring1="A2p"# Default "test"string=${1:-${string1}}# Allow command line inputtypeset-alcalph=(abcdefghijklmnopqrstuvwxyz)typeset-aucalph=(ABCDEFGHIJKLMNOPQRSTUVWXYZ)## Functions:### Function _rotN(char) - return the "rotated" N letter to char# Needs: $ROT_NUM defined#function_rotN{typeset_char;_char="$1"typeset_casechk_alpha_oldIFS_buff_indx[[${_char}!=@(\w)||${_char}==@(\d)]]&&echo"${_char}"&&return# Non-alphatypeset-l_casechk="${_char}"[[${_casechk}=="${_char}"]]&&nameref_aplha=lcalph||nameref_aplha=ucalph_oldIFS="$IFS";IFS='';_buff="${_aplha[*]}";IFS="${oldIFS}"_indx=${_buff%${_char}*}echo${_aplha[$(((${#_indx}+ROT_NUM)%(ROT_NUM*2)))]}typeset+n_aplhareturn}####### main #######for((i=0;i<${#string};i++));dobuff+=$(_rotN"${string:${i}:1}")doneprint"${string}"print"${buff}"
A real 12 test
N erny 12 grfg
This image is aVI Snippet, an executable image ofLabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.
The rot13 function works on any text containing this set
abcdefghijklomnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXZ.
Note that spaces can be used but not the "_" character used to handle them.
{defrot13{defrot13.alphabet{A.splitabcdefghijklomnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXZ_.}}{defrot13.delta{lambda{:i:a}{A.get{%{+{A.in?{A.get:i:a}{rot13.alphabet}}32}64}{rot13.alphabet}}}}{defrot13.r{lambda{:a:b:n:i}{if{>:i:n}then:belse{rot13.r:a{A.set!:i{rot13.delta:i:a}:b}:n{+:i1}}}}}{lambda{:txt}{let{{:t{S.replace\sby_in:txt}}}{S.replace_byspacein{A.join{rot13.r{A.split:t}{A.new}{-{W.length:t}1}0}}}}}}->rot131)encoding:{rot13abcdefghijklomnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXZ.}->56789ABCDEFGKIJKLMNOPQRSTUV3WXZ.abcde3fghijklomnopqrstuvwxyz01242)decoding:{rot1356789ABCDEFGKIJKLMNOPQRSTUV3WXZ.abcde3fghijklomnopqrstuvwxyz0124}->abcdefghijklomnopqrstuvwxyz0123456789ABCDEFGKIJKLMNOPQRSTUVWXZ.
// Extend the string typedefinestring->rot13=>{local(rot13=bytes,i,a,b)withcharin.eachCharacterletint=#char->integerdo{// We only modify these ranges, set range if we should modify#int>=65and#int<91?local(a=65,b=91)|#int>=97and#int<123?local(a=97,b=123)|local(a=0,b=0)if(#a&&#b)=>{#i=(#int+13)%#b// loop back if past ceiling (#b)#i+=#a*(1-#i/#a)// offset if below floor (#a)#rot13->import8bits(#i)// import the new characterelse#rot13->append(#char)// just append the character}}return#rot13->asstring}
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'->rot13'Where do you find a dog with no legs?Evtug jurer lbh yrsg uvz.'->rot13
NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklmJurer qb lbh svaq n qbt jvgu ab yrtf? Right where you left him.
definerot13(p::string)=>{local(rot13=bytes,a=bytes('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'),b=bytes('NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'),i)withcharin#p->eachCharacterletc=bytes(#char)do{#i=#a->find(#b)#i?#rot13->import8bits(#b->get(#i))|#rot13->append(#c)}return#rot13->asString}rot13('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')
NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm
Liberty BASIC string comparisons are not ascii-based.Verbose version:
input "Type some text to be encoded, then ENTER. ";tx$tex$ = Rot13$(tx$)print tex$'checkprint Rot13$(tex$)waitFunction Rot13$(t$) if t$="" then Rot13$="" exit function end if for i = 1 to len(t$) c$=mid$(t$,i,1) ch$=c$ if (asc(c$)>=asc("A")) and (asc(c$)<=asc("Z")) then ch$=chr$(asc(c$)+13) if (asc(ch$)>asc("Z")) then ch$=chr$(asc(ch$)-26) end if if (asc(c$)>=asc("a")) and (asc(c$)<=asc("z")) then ch$=chr$(asc(c$)+13) if (asc(ch$)>asc("z")) then ch$=chr$(asc(ch$)-26) end if rot$=rot$+ch$ next Rot13$=rot$ end function
Concise:
Function Rot13$(t$) for i = 1 to len(t$) ch$=mid$(t$,i,1) if (asc(ch$)>=asc("A")) and (asc(ch$)<=asc("Z")) then ch$=chr$(asc("A")+ (asc(ch$)-asc("A")+13) mod 26) end if if (asc(ch$)>=asc("a")) and (asc(ch$)<=asc("z")) then ch$=chr$(asc("a")+ (asc(ch$)-asc("a")+13) mod 26) end if Rot13$=Rot13$+ch$ next end function
A fairly straightforward version that uses a lookup table, based on Inferno's cat(1).
implementRot13;include"sys.m";sys:Sys;include"draw.m";Rot13:module{init:fn(ctxt:refDraw->Context,argv:listofstring);};stdout:refSys->FD;tab:arrayofint;init(nil:refDraw->Context,args:listofstring){sys=loadSysSys->PATH;stdout=sys->fildes(1);inittab();args=tlargs;if(args==nil)args="-"::nil;for(;args!=nil;args=tlargs){file:=hdargs;if(file!="-"){fd:=sys->open(file,Sys->OREAD);if(fd==nil){sys->fprint(sys->fildes(2),"rot13: cannot open %s: %r\n",file);raise"fail:bad open";}rot13cat(fd,file);}elserot13cat(sys->fildes(0),"<stdin>");}}inittab(){tab=array[256]ofint;for(i:=0;i<256;i++)tab[i]=i;for(i='a';i<='z';i++)tab[i]=(((i-'a')+13)%26)+'a';for(i='A';i<='Z';i++)tab[i]=(((i-'A')+13)%26)+'A';}rot13(s:string):string{for(i:=0;i<lens;i++){if(s[i]<256)s[i]=tab[s[i]];}returns;}rot13cat(fd:refSys->FD,file:string){buf:=array[Sys->ATOMICIO]ofbyte;while((n:=sys->read(fd,buf,lenbuf))>0){obuf:=arrayofbyte(rot13(stringbuf));if(sys->write(stdout,obuf,n)<n){sys->fprint(sys->fildes(2),"rot13: write error: %r\n");raise"fail:write error";}}if(n<0){sys->fprint(sys->fildes(2),"rot13: error reading %s: %r\n",file);raise"fail:read error";}}
function rot13 S repeat with i = 1 to length(S) get chartonum(char i of S) if it < 65 or it > 122 or (it > 90 and it < 97) then next repeat put char it - 64 of "NOPQRSTUVWXYZABCDEFGHIJKLM nopqrstuvwxyzabcdefghijklm" into char i of S end repeat return Send rot13
10INPUT"Enter a string: ",a$20GOSUB5030PRINTb$40END50FORi=1TOLEN(a$)60n=ASC(MID$(a$,i,1))70e=25580IFn>64ANDn<91THENe=90' uppercase90IFn>96ANDn<123THENe=122' lowercase100IFe<255THENn=n+13110IFn>eTHENn=n-26120b$=b$+CHR$(n)130NEXT140RETURN
to rot13 :c make "a difference ascii lowercase :c ascii "a if or :a < 0 :a > 25 [output :c] make "delta ifelse :a < 13 [13] [-13] output char sum :delta ascii :cendprint map "rot13 "|abjurer NOWHERE|nowhere ABJURER
functionrot13(s)locala="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"localb="NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm"return(s:gsub("%a",function(c)returnb:sub(a:find(c))end))end
functionrot13(s)return(s:gsub("%a",function(c)c=c:byte()returnstring.char(c+(c%32<14and13or-13))end))end
Minimum change: ELSEIF to ELSE.IF
letter$ is reserved word, but here we change the use for the current module
Strings are UTF16LE encoded, but ASC() and CHR$() works for ANSI codes for characters (0 to 255) for specific LOCALE (language id). See the line bellow, set locale to 1033, and automatic change the codepage and charset. Charset can explicitly change for use for no unicode fonts (161 for Greek/English letters).
locale 1033 : Print Locale=1033, codepage=1252, charset=0
We can use a CLIPBOARD ans$ for export to clipboard
CLSINPUT "Enter a string: ", s$ans$ = ""FOR a = 1 TO LEN(s$) letter$ = MID$(s$, a, 1) IF letter$ >= "A" AND letter$ <= "Z" THEN char$ = CHR$(ASC(letter$) + 13) IF char$ > "Z" THEN char$ = CHR$(ASC(char$) - 26) ELSE.IF letter$ >= "a" AND letter$ <= "z" THEN char$ = CHR$(ASC(letter$) + 13) IF char$ > "z" THEN char$ = CHR$(ASC(char$) - 26) ELSE char$ = letter$ END IF ans$ = ans$ + char$NEXT aPRINT ans$
b'BA@?>=<;:9876543210/.-,+*)('&%$#"!Q=+^:('&Y$#m!1So.QOO=v('98$65a`_^]\[ZYXWVUTSRQ#I2MLKJIHGFEDCBA@#!7~|4{y1xv.us+rp(om%lj"ig}fd"cx``uz]rwvYnslkTonPfOjiKgJeG]\EC_X]@[Z<R;VU7S6QP2N1LK-I,GF(D'BA#?>7~;:9y16w43s10)p-,l*#(i&%e#d!~``{tyxZpuXsrTTongOkdMhg`Hd]ba`_^W@[ZYXW9UNSRQPOHMLKJ-++FE''<A$?>=<;:387xw43s10/(-&m*)('&}${d!~}|^zyxwvutmVqpiRQlkjiKafedc\E`_^@\[ZYX;V9NMRQ42NGLK.IH*F?DCBA$#>7~;{{8xx5uu2rr/oo,ll)ii&f|e"!aw`{z\r[vXnmVTpongPkNihgJ_dcFa`B^]\UZ=RWV8TSLQ4ON0LE.IHA)E>'BA:?!7~5|38y6/v321q).-&m*)i'&%|{d!~}_{zs\wvutsUqTonPlOjiKgJedFbE`_A]@[Z<X;VU7S6QP22GL/JIB+FEDC%;@?>7~;:987w5v32r0)p-,+k)('~g$#"b~w|uz]xwvutsrqTinQlOjLhgfeH]bE`CB]\>ZSXWVUTSRQPON1LE.I,+*((&&$$""~~||zzxxv4u210/(-n+l)ji~g|eccaa_{zy[qZoXVVTponPfOdiLJJ_HFba`BXAV?==;;9977pQPONMLKJIHGFEDCBA@?>=<;:9876543210/.-,+*)('&%$#"!~}|{zyxwvutsrqponmlkjihgfedcF!`_^]\[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:9876543210/.-JI*)FE&%$#"!~}|{zyxwvutsrqponmlkjihgJ%dcF!`_^]\[ZYXWVUTSRQPO2kLKJIHGF)bCBA@?>=<;:9876543210/.-JI*)FE3%$#"!~}|{zyxwvutsrqponmlkjihgJ%dcF!`_B{\[>wXWVUTSRQPO2kLKJIHGF)bCBA@?>=<;:9876543210/.-JI*)FE&%$#"!~}|{zyxwvutsrqponmlkjihgJ%dcF!`_B{\[ZYX;VUTS6Q4O200EJIH*@)>'%A@?!7~5|zzx65u3,s*qoommk)(h&}f{dbb``^^\xwYutWVkToRmlkjMLgfHdcF[DBB@\?==RWV8TM6K4220LK-IB+@E(&&;$""~~||zzxxv4u21r/.o,mlk"i&g$#"!b}`{^\\qvYWWlUSSQQOkjiKaJ_HFFD`_A]V?T=;;997SRQ3I2G0.JIH*@)>'%A@">=~}4{8y6wv3trr).omm$)j'&g$#d!ba`u^y\wZYtWrqTonmOOdihK`IHG\a`_AW@U><XWV8N7LQ422G0.JI+G@)>C&$$9"~~||z87w5.u,sqqoommkki'h%$e"yb}`_t][wvXtmVkpSQQfOMihgI_H]FD`_A]V?T=;;99775QPO1G0E.,HG)E>'<A$""7~||z8y654u,s0qp',m*)ii&}$e"cb``^z][[putVrkTiRPPNjMKK`edFb[DYB@\?==RWVU7M6K42200..,,*F)DCB%@9>!~;|zz165u32s*qoommkki'&f${dy~a__t][[YutVrkTinQOOdMKKIIGGEaD_^A\?ZYR;:U8SR533NMLEJ-,G*((=B%##8=<|:3z1xvvttr0/o-&m$)jhh}fd"!~`v_t][wvXtmVkpSQQfOMMKKIIGGEaD_^A\?ZYXQV9T7R5PO11LKJIB+F)D'%%:#!!};:z81x/vttrrppnnlljjhhf$e"!~a|{zyr[vYXmrqpRnQfkjiKaJ_HFFDDBB@@>><<::88664P3NMLE.I,+@)'CBA#9"7<}{{2ywwuussqqoommkkiig%f#"!xa`{^yx[YYnsVUpSQQfOMMKgfHd]F[`CAAV?=YX:VO8M6442200..,,**(D'BA$?"7<}:{z16w43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Q:O866442200..,,**(D'BA$?"=6}|9zxx/4u21rpp-,%*kji~ge#"!aw`u^\\ZvutVlUjSQQOkjiKaJ_HFFDDBB@@>Z=XW:U8SRKP32M0KJ-++FED=&%$9"7<}{{276v4-t+rppn,mkk"'&f${dyb`|{]yr[pYWWUUSSQQOOMMKgJedGbE`_^W@?Z=XW:88SRQPIN10/D-B+)E(&&;@?!=6}4{y7xvv-21q/(o&mkki'hff{"!a}v_t][[YYWWUUSSQmPNNchKfeHcFa`_^W\?Z=X;VUTSR44INM0E.I,G*((=B%##8!};:9y1x/vttr0/.n&m$kiiggeeccaa__]y\wvunWVqTonQOOdMLgJHH]baC_XAV?==;;997S644INM/KD-B+))''%%##!!};|98y6w.uts*/pnn%l#(i&%f#d!x}`_z]xwZXXsrkTSnQOOdMKgfHd]F[`CAAV?=YX:VO8MR533H1//--++))''%%##!=~;:{8y65.ut1r/.omm*)(!&gfez!b``uz][[putVrkTiRPPNNLLJfIGG\a`B^W@U><<:VU7SL5JO200E.,,**((&B%@?"=~;:927x5v3t10pp-,+*#j'h%fddy~a__ty\wvuXsrqpiRmPkNLLafeGcbEZCX]\[=S<Q:8TSR4J3H1/KJ,HA*?(&&$$""~~||zzxxv4u210)po,m*)jhh}$edcxav_]][[YutVrkTiRPPNNLLJJHHFFD`C^]@[>SX;V9T7RQ33NG0K.I,**?(=&$@?>~6}4{y76v4-t+0qoo&mkkiiggeeccaa__]y\wvuXslUTShmPkjMKKfe^cFE`_A]V?T=;;9UT6RK4I20LKJ,B+@)''%%##!!}}{{y7x54u2s0/(-nml#('&f|ezcaa_{zy[qZoXVVTTRRPPNNLLJJHdGbaD_B]\[T=X;V9TS55PONMFK.I,G*((=BA#?>!6;|zz16w432s0/.-&+l)j'h%$#"!aav{z]r[vYXmVTponPfOdMKKIeHFF[`_A]V?T=;;9UT6RK4I200..,,**(D'BA@9"!~5|38y65vtt+rq.-,l$k"igge#"b~w`uz][[pYWWUUSSQQOOMMKKIeHcbE`CXA\?Z=XW99TMR5P3N1//DI,**?DC%A:#8!}}{{yyw54t2+r)pn,+*j"i~%fddyb``^^\\ZZXtWrqpSnglOjMLaJ_dcbDZCX]@>>S<:VUT6L5J311//--++))'CBA#9"7<}{{2yw543s+r).omm$ki'&%e{dyb`|_zyx[vunWrUpSnmOOjihafIdGbECCXAV?==;;9U866KPO1MF/D-++)ED&B;$9"~~||zzxxv4u210q.-,%*kj'h%$ecc~}|{t]\wvXtsVkpSnmPkNihgf_HcFaD_^]\[==RWV9N7R5P311FK.,,AF)DCB;$#"7<}{{2y0wuussq/.n,%l#(igg|eccaa_{z\xqZotWUUjSQQOOMMKgJedGbEZ_B]@[>YX::UN7R54I20LKJ,B+@)''%A@?!7~5|zzxxvvttrrppn,m*)(i&}fedy~a|{^\\wvotWVqpRnmPeNLLJfeGc\EZ_B@@U><<::8T755JON0LE.C,*F)''<A@">7~5|zzxxvvt2s0/p-n+*#(i&gf{dbb``^zy[wpYnsVTTiRPPNNLhgIe^G\aDBBW@>><<::8T7RQP3NMLE.-,A*?D'BA$?"=<;:38y6w4u210/.nn%*)j!h%f#dbbw|{]yr[puXVVkTRRPPNNLLJJHdcbDZCX]@>>S<::88664P3NMLE.-,AF)DC&$$9"!<;{92y05vtt+rppnnlljjh&%$dzcx}`^^s\ZZXXVVTTRnQlkNiLaJeHG\a`_A]@UZ=XWV9TMR54O2ML/--HG@)(C&$$9>=};:{2ywwuus10p.'n%ljjhhffddbb``^z]xwZuXsrkToRmPkjLLgfe^cFaDCXAV?=YX:VO8MR533H1//--+GF(D=&;$""~~||zzxxv4u210q.-,%*k(i&g$#cc~}|{t]x[vuWsrUjSQQOkNLLafeGc\EZCAA??==;W:88MRQ3OH1F/--++))'C&$$9>!<;:{8765.u2sr)p'nlljjhhffddb~}_{t]r[YYWWUUSoRmlkdMhKJ_dcbDZCX]@>>S<::8866442200..,,**(D'BA@9"=~}4{27x54tt+0q.onlljjhhf$#c!xav_]][[YYWWUUSoRmlkNchKJeHcbECC^W@?Z=;;PUT6RK4I200..,,**((&&$$""~~|:{87x5v3,s0q.o,+kk('~%f#d!b``uz][[pYnsVTTinQlkjMhg`eHGF[`C^]@>>YXWP98SR4PO2G0..,,*FE'C<%:#!!}}{{yywwuus1r/.o,m*)(!h%f#d!~``{zyxqvYtWVkTinQOOdihJf_H]FD`CAAV[Z<XQ:O8664PO1MF/D-++))''%%##!!};|987x5432+0q.o,mkk"'&f$#dybw|_zyxqZuXWlqTonmfOjMhKfeGG\E`C^A??T=R;997S644INM/KD-B+)ED&B;$9"~~||zzxxvvttr0q.-,m$kji~%f#"caa|uz]\wZXXmrqSonQfOMihJf_H]FDDBB@\[=YR;PU866K4220LK-IB+@E(&&;$""~~||z8y65v3t1*/p-n+l)(hh%${d!bav{^\\qZXtWUUjonPleNcLJJHdcbDZCXA??==;;9977553O2MLK.IHA*)D'BA$""=<;49zyx/v-trrppnnl*)i'~g|eccaa__]][[YuXsrUpSnmlejMLgJedGEE`_^]V?>YX:VU8MRQ3OH1FK.,,A*(D'%%:?>~<5|3zx6wuu,10p.'n%ljjhhffd"caav{z\xqZoXVVTTRRPlOMMbgJedGbE`_^]V?Z=X;VUTSR44INM0E.I,+@E(&&;@?>~6}4{y765u-t+rppnnllj('g%|ezcaa__]][[YuXsrqjSRmPkjMKK`eHGbECCXAV?==;W:88MRQ3OH1F/-I,**?DC%A:#8!};:9y1x/vttrrppnnllj(i&%f#dy~a`{zy[wZoXmVTTRRPlkMibK`eHFF[DBB@\[=YR;PU866K42NM/KD-BG*((=&$$""~~|:{87x5v3,sr/p-,mkk('~%fedybw`^zy[wpYnsVTTiRPPNNLLJfeGc\EZCAA??==;;9U8SR5P3NMFK.I,+@E(CB$$?>=6}:{zxxv432r*q(ommkki'&%e{dy~a__t][[YYWWUUSoRmlkNihg`IdGbE`_AA\[ZYRW:U87LQ422G0.JIH*@)>'%%##!!}}{{yywwuus1r/.-n+*)(!&gf#d!~a|{z\\qvuXmVUpSQQfOMihgI_H]bECCXA??=YX:VO8M6442200..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XWVO8764PON0F/DI,**?(&&$@?>~6}4{yywwu321q)p',mkk"iggeecca}`{z]x[vutslUToRmlOjihJJ_dcF[DCBW@U><<:V977LQP2NG0E.,,**(DC%A:#8!}}{{yywwu3t10q.'n+l)j'&ff{"c~a|_]]rwvXtmVkpSQQfOMMKKIedcE[DYB@@>><<::88664P3NML/DI,+F)DC&$$?8!~}4{276v4-t+rppnnl*)i'~g|#dbbw`^^\\ZZXXVVTTRnQlkNiLg`IdGbE`_AA\[TY<W:U866KP311FK.IHG*ED=B%@#"7<}{{2765u-t+rp.omm$)(h&}f{dbb`|_]]rwvXtmVkTRnmOkdMbgJHH]FDDBB@@>><<:V9TSR5PONG0/J-HG*((CBA@9>!~;|zz1xvvt21q/(o&mkkiiggeeccaa__]y\wvYtWrqpohmPkNihgIeH]ba`BXAV?==;;9UT6RK4I200..,,**((&&$@#>=<5|9zy0w.u,1r/.-n%lk(i&%fdd!x}`_^sxwvXnWlUSoRPPejiKg`I^GEa`_AW@U><<::8866442200.J-HG*E(C<A$#>!<;|zz76/vu2sqq(-,l*)j!&%e#zcxa__]][[YYWWUUSSQQOOMiLgfIdGbaZC^A\?==R;PU8SRQ4ONMFK.-H+FE(&&A@?>7~}:{yy054t21r).omm$)j'&g$e"!~}v_z]\qZoXmrqpRhQfOMihJf_H]bECCXA??==;;9977553311/K.IHG@)(C&A@#!!6;|{z16wuu,1rpp',+k)"i~geeccaa_{^\\qvuWslUjSQQOkjLhaJ_dGEEZCAA??==;W:UT7R5JO2M0/DI,GF((C<%@#>=};:{2ywwuus10p.'n%*kii~geec!~`|u^s\ZZXXVVTTRnQlkjMhaJIH]bE`_B@@[ZSX;:U866KPO1ML/D-++))''%%##!=<|:3z16wuu,sqqoommk)j'&g$e"!x}`{^y\wvXXsrqjSnQlOMMbgJHH]FDDB^A??TYX:VO8M6442200..,,**((&B%@?>!<;:3z7x5v32rr/.-,%*k(i&geez!b``u^s\ZvuWslUjSQmlNjcLafIGG\EC_^@\U>SX;99N7553311//--++)E(CBA$?>=<5:{8yx/432r0q(-n+*)"i&gf{"!~`v_ty\ZZoXVVTTRRPPNNLLJJHHFFD`C^]\U>=X;VU866K43N1//D-+GF(D=&;@#!!6}{98x6/v-trrppnnlljjhhffd"c~}`{^s\wZuXsrTTohmPkNiLJJ_H]FD`_A]V?T=;;9UT6RK4IN1//D-++))''%%##!!};|987x5.3t1rq(-nll#j!&g$#"c~}v_^]rwZutWUUponglONMKKIeHFF[`_A]V?T=;WV8TM6K42N1//DIH*F?(=&$$""~~||zzx6w43t1r/.-&+l)ji~%f#"bb}|{zs\wZuXVVkpoQmlOdihJf_H]FDDBB@@>><<::8866442N1LKJ-HGFE>'&A$?>!<;:zz165v-ts0/o-,m$)jhh}$#c!xav_]][[YYWsrTpiRglOMMbKIIGGEECCAA?[>YX;VO876K4IN1LK.,,AF)(C&$$9>=};:{27x54u2s*/p-nm$k"'h%$dd!xa|_z][[putVrqTinQlkjMhaJIH]bE`_B@@[ZSX;:9N7553ONM/E.C,*FE'C<%:#!!}}{{yywwuus1r/.o,m*)"'hgf{"c~}`^^yxwpYXsVTTiRglOMMbgJedGbE`_^W@[>=RW:UT66QPONGL/J-,**((&BA#?8!6}{{yywwuussqqo-n+*)j'&%${"cb}`{z]xwvXXmrqTiRQPejiKg`I^cFDDYB@@>ZY;WP9NS644I20LK-IB+@E(&&;$">=};4{27xvv-trrppnnlljjh&g$#d!xa`_ty\wvYWWlUTonPleNchKII^GEECCA]\>ZS<Q:8866442200..,H+FE(C&;$#>=<|:{2765u-t+rppnnlljjh&%e#zcx}`^^s\ZvuWslUjoRPPeNLLJJHHFbE`_B]@[TY<;:OT7RQ422MLE.-H+))>CB$@9"7~|:{yy054t2+r)pn,+k)"i~geeccaa_{zy[qZotWUUjSQQOOMMKgJedGbE`_XA@[>YX;99TSRKP32M0..CH+))>'<%#?>=}5|3zx65u3,s*/pnn%ljjhhffddbb``^^\x[vuXsVqpohmPkNMbgJedFFa`_^W@[>YX:VU8MR533HM0KJI,GFED=&A$?"=<;:9yy054u,s0qp'n%lj(igg|#"b~w`u^\xwYunWlUSonPleNchKII^GEa`B^W@UZ=;;P977553311//-I,GFE>'&A$?>!}}49zy6wuu,10p.-n%*kii~%f#"c~av{^]\qvYtsVTTohQPkNLLafeGc\EZCAA?[><<QVU7SL5J31ML.JC,A*((&&$$""~~||z8y65v3t1*qp-n+*kii&%|#dcbw|_]]r[YuXVVkpoQmfOdMKKIIGGEa`B^W@U><<::88664P3NM0K.IHAF)('<A$""7~5:{87x5v321*qpo&+l)(i&g$#"!x}`{^y\wvutsUUjonQfOjMhKII^cbD`YBW@>Z=;;PUT6RK4I200..,,**((&&$$""~<}:981xw4uss*q(-n+*k(i~gfez!b}|_]]xqvYXsrTpiRglOMMbKIIGcFDDY^]?[T=R;9UT6RK4I200..,,**((&&$@#>=~;|927x5v3t10pp-,%l)j'hff{"!~`v_t][[YYWsrTpiRgPNNLLJfeGc\EZ_B@@U><<::886R5PON1LKD-,+@E(CB%##>=<5:{z765u-t+rp.omm$)(h&}f{db~}|^t]r[YYWWUUSSQQOOMMKgJedGbE`_^W\?Z=<Q:OT7RQ33NMLKD-H+F)''<A@?!7~5|zzxxv43s1*q(ommkkiiggeecca}`{zy\wvutmVUTiRglkjLbK`IGGEECCAA??==;;99775Q4ON1LE.-,AF)DC&$$9>!~;:z87x/4uss*/p-,m*k"'h%f#d!~``{t]x[vYWWlUSonmOeNcLJJHHFFDDBB@@>><<:V9TSR5PI2M0/DI,**?(=B%@?>!<;49z7xw.3t10/p-,+$k(ih}$e"!~a|{zyrwZYXmVkTinQOOdiLgfId]FEDY^]\>T=RW:88M6442200..,,**((&&$$">!<;|92y6w4uss*q(-n+*)j!h%fez!b}|^^yrwZuXsVTTinmOkdMbKIIGcFDDY^]?[T=R;9UT6RK4I200..,,**((&&$@#>=<}:38yxw.u,sqqoom+ljj!&%e#zcxa_{zy[qZoXVVTTRRPPNNLhKfeHcFa`YBA\?ZY<::UTSLQ43N1//DI,**?(&&$$""~<;{92y0wuus10p.'n%*kii~geeccaa_{^yx[vYtsrkpSnQlOjiKKfedc\E`C^]?[Z=RWV8TM6KP311F/--++))''%%##!!}}{{y7x543t10/.'n+l)j'&%$#ccx}|_t]x[vYWWlUSonPleNcLJJHdcEaZCX]@>>S<:VU7SL5JO200E.,,**((&&$$">!<;:3zy6w43trr).on+ljj!&geez!~`|u^sx[YYnWUUSSQQOOMMKKIIGGEEC_B]\?Z=RW:9T755JONM/E.C,**(DCB$:#8!};:z81x/vttr0/o-&m$)jhh}fddbb``^^\x[vuXsVqjSRmPNNchKfeHFFa`Y^A@?TYX:VO8MR533H1/KJ,HA*?D'%%:#!!}}{{yywwuussqqo-nll#(i&%f#d!~w|_z]\qZXtWUUjonmOeNcLJfedF\EZCAA??=YX:VO8M6442200..,H+FED'BA@9"!<}:9zxx5432+0qp-nll#jh&%e#zcx}`^^s\ZZXtsrTjShQOkjiKaJ_HFba`BXAV?==;;99775Q4ON1L/JIHG@E('BA@">!6}{987w/v-trrppn,mkk"'&f${dyb``^^\\ZZXXVrUpoRmfONihJfeH]bECCX]\>ZS<Q:886R533HML.JC,A*((&&$$""~~||zzx6wuu,1r/.o,m$kj'h%$ecc~w|_^y\ZZotsUqjShmPNNcLJJHHFFDDBB@\[=YR;PU866K42200..,H+FE(C&A:?"=~}498x65v-t+rppnnllj('&f|ezca}|{]s\qvYWWlUSSQQOOMMKgJedcFa`YB]@?TY<WV88SRQJO2M0/--+GFE'=&;$""~~||zzxxvvttr0q.-,m*)(!&gf#d!~a__zyxwpYXsVTTiRPlkMibK`eHFF[DB^]?[T=R;9977553311//--+G*ED'B%@?>=6}|9z76w432rr).-n%lk(igg|ec!~`|u^s\ZZXtsUqjShQOOMMKgfeG]F[`CAAV?==;;997S6QP3NG0K.I,GF((=B%@#>=};:{2ywwuus10p.'n%*kii~geeccaa__]][[YuXsrqTinQPkjLhgJ_H]FDDB^]\>T=R;9977553311//--+G*ED'B%@9"!~5:{yy0w.3t10q.o,+$)j'h%f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-nll#(ih%fddybw|{z\r[pYWsrqSiRgPNjiKg`I^GEECCA]\[=S<QV977L53311//-IHG)?(=B%##8!};|98y6w.3t1r/p-,ll)"i&g$eccx}|^zy\qZXXVVTpoQmfOdMKKIIGGEECCAA?[>YXW:UN76Q4ON1//JIBG*)(=&;$">!}}498x6/v-trrppn,+k)"i~geeccaa__]][wZutWrUpohmPONcLaJHHFbECCX]\[=S<Q:886644220L/--BGFE'=&;$">!}}4987w/v-tr0qoo&+*)i!h}fd"c~}`{^yxwpYXsVqpSQQlkjibgJIdGEEZCAA??==;WV8TM6KP311F/-IHG)?(=B%##8!};:9y1x/4uss*qoommkki'h%$e"c~}|{ty\wZYnWlUSSQQOkjLhaJ_HFFDDBB@@>><<:V9TSRK4O21F/DI,GF((=&A$?"~~5:9y70w.ussq/.-m%l#jh&%e#zcx}`^^s\ZZXXVVTTRRPPNjMhgfI^GFEZ_B]\?==XQV9875QPO1G0E.,,**(D'%%:?>~<5|3zxxvvttrrppn,m*)j'h%|#dc~a|{^\\wvoXWrUSShQOOMMKgfHd]F[DBB@@>><<::886R5PO2M0KJC,+*?DC%A:#8=~||3zxxvvttrrp.-m+$k"'hff{db~}_{t]rwZXXmVTTRRPPNjMhgJeHcbaZ_BA@UZ=XW:88SRQPI21LKJ,B+@)''%A@">7~5:{yy0wuus10p.'n%*kii~ge#"!aw`u^\\ZZXXVVTpSnmPkNihgf_HGbE`_B]\[==RWV9N76QP2NM0E.,H+))>CB$@9"7~||z8yww.32r0)p'nl*kii~%$d"ybw`^^\\ZZXXVVTpSQQfkNihKf_HcFEZ_B]\>>SX;V9T755JO2MLK.CH+F)DC%A@#8!6;|zz165u3,s*qoommk)jhh}$#c!xav_]][[YutVrkTinQOOdMKKIIGGEaD_^]@[T=<W:UT755POHM0/J-++@ED&BA$9"~~|:{yy054t2+r)pnnlljjhhffddbb`|_]]rwZutWrUpohmPkNMbKIIGcbaCYBW@>Z=;;PUT6RK4I200..,,**((&&$@#>=<}:981xw4u21rpp-,+*#(ih%$d"!bw|_]]rwvXtmVkTRRPPNNLLJJHHFFDDBB@\?ZY<W:UTSRKP32M0KJ-HGF((=BA$9"!<;{98y0wu32r0)p'nlljjh&%e#zcxa__]][[YYWWUqTonQleNiLK`eHcbDDYB]@?TY<::O86R533HML.JC,A*((&&$@?>~6}49zxx/vttrrppnnllj(i&%$ezc~a`uz]xwYYtmrUpSnmOkdMbgJHH]FDDB^]\>T=RW:88M6442N1//DIH*F?(=&$$""~~||zzx6w432s0).on+l)(igg$#zcb}`^^sxwYutWlqTRRglkMibK`IGGEECCAA??==;;99775Q422GL/JI,G*ED=&%@#>=~||98705vut+0qoo&mk)jhh}$#c!xav_]yxwYoXmVTTRRPPNNLLJJHHFbE`_B]@[ZYRW:U8S6QP22MLKJC,G*)>'<%##!!}}{{yywwuussqqo-nll#(i&%$e"!~}v_^]r[pYWsVTTinmOkdMbKIedFb[DYB@@>><<::8866442N1LK.IB+*E(CB%##8=~}:{yy054t21r)pnnl*kii~%$d"ybw`^zy[wpYnWUUSSQQOOMMKKIeHcbE`CX]@?>SX;VU866QJ321/KJ,HA*?(&&$$""~~||zzxxvvt2s0/p-n+$k(ih}$e"!aa|{ty\wZYWWUUSSQmlNjcLafIGG\ECCA]\>ZS<QV977L53311//-I,GFE(CB;@#"=~;:{yy654-tsr)p',+k)"i~geecca}|^zs\qvYWWlUSSQQOOMMKKIIGcFa`C^A\[ZS<W:9NS6QP22MLKJCH+F)(&&$$""~~||z876v.u,1rpp'nlljjhhf$e"!~a|{zyrwZYtWrqTonmOOdihK`IHcbD`_BW@>><X;99NSR4PI2G0..,H+))>CB$@9"7~||zzxxvvttr0q.-n+$kj'h%$eccxa`_ty\ZZoXVVTponPfOdMKKIedcE[DY^A??T=;;997755331M0KJ-H+@)(C&A@#!!<5:{zy0wu32r0)p',mkk"iggeeccaa__]][[YYWsVqpSnQlejMhKfIdcEE`_XA\?ZY;WV9N75Q422GLK-IB+@)''%%##!=<|:3z16wuu,sqqoommkki'hff{"c~}|_zyr[ZuXsrUSSnmlejMLgJHH]baC_^AV?==;W:88MRQ3OH1F/--++))''%%##!!};|zz16w43t1r/.-&+l)ji~g|#"!aw`uz][[pYWWUUSonPleNchKII^GEECCA]\>ZS<QV977L53311//-I,GFE(CBA@9"!<}:9z765uu,10q(onm$k"ig%fddy~}_{t]r[YYWsVTTinmOkdMbKIedFb[DYB@@>><<::886R5PO2MF/J-,AFE'CB%:#8=~;:9z16wv32r0/p'nllj(igg|#"b~w`u^\x[YYnsrTpiRgPNNLLJJHHFFDDB^A\[>Y<WP9T76KP3NM//JIBG*E('<A$""7<;:z2y0wuussq/.-m%l#jh&%$dzcxa_{zy[qZoXVVTTRRPPNjMhgfIdc\aDC^]?[Z=R;99775Q422GLK-IB+@)'CB$@9"7<}{{2ywwuussqqoom+l)(i&g$#"yb}`{^yxZZutsrkpSnQlOMMbgJHH]baC_XAV?=YXW9O8M64PON0F/DI,**?(&&$$""~~||zzxxv4u210q.-,+$)ji&g$#d!~}__tyx[pYXWlUjonPleNchKII^GEECCA]@>>SXW9UN7L53ON0LE.C,**((&&$$""~<}:9z70wv3trr).-m+*k"igge#dbbw|{]yr[pYWWUqpRngPeNLLJJHHFFDDB^A\[>Y<Q:98M644220LK-IB+@)'CBA#9"7~|:9y70w.3trr)pn,+k)"i~%fddyb``^^\\ZvYtsVqTohmPOjMKK`I^GEa`B^W@U><<::8TS5QJ3HM0..C,**((&&$$""~<}:9z7x54-ts0q.-nll)('~%fedy~a|{^y\wvunsVqToRmlNNihgf_HcFaDBBW\?==RW:UTS6QPONG0/J-HG*EDC%%:?>!6}|9zxx/4uss*/.n,%l#jhhf$eccx}|^zs\qZXtsUqjShQOOMMKKIIGGEEC_B]\?ZS<W:U8SR44IN1L/J-++@)>'%%#?>=}5|3zx65u3,s*/pnn%ljjhhffddbb``^z]xwvYnsVUTinQlkNLLg`IHGEECCA]\>ZS<Q:8TSR4J3HM0..C,**((&&$$""~<}:9z7x5.ut1r/.omm*)"'hgf{db~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h%${d!b}`^^s\qvYWWlqTonmPkjcLKJ_H]F[`C^]@>>YXWPU8764P311FKJ,HA*?(&BA@"8!6}{{yywwuussqqoom+l)(i&g$#"y~a|_^sx[vuWWrqpohQlOjiKg`I^GEECCA]@>>SXW9UN7L53311//--++))'C&A@?"=<;:3z7xw.321q/p',m*)(!h%fez!~}_u^sx[YYnWUUSSQQOOMMKKIIGGEEC_B]\[T=X;:O8MR5PO11FK.I,G*((=B%@?>!6;|{8y65vtt1*qp-nll#('g%$ez!b``uz]xwZuXslUpSRgPeNchKfeGGbaZ_B]@[ZY;Q:OT755J311//--+G*((=BA#?8!6}{{y76v4-t+0qoo&mkkiigge#d!~}`{zsx[ZYnWlUSoRPPejiKg`I^GEEC_^@\U>S<::8866442200.J-HG*E(CBA:#>!~5|z8yww.32r0)p'nl*)(h~g|eccaa_{z\xqZotWUUjSQQOOMMKKIeHcbaD_^]\UZ=<W:UT7RQP22GLK.C,+F)''<A$""7~||z87w5.u,1rpp'nl*)(h~g|#dbbw`^^\\ZZXXVVTTRnQlkNibKJedcEaDY^]\>T=R;9UTS5K4I200.JI+G@)>C&$$9"~~||zzxxvvttr0q.-n+l#j'hg|ez!b}|^^yrwZuXsVTTinmOkdMbKIIGGEECCAA??==;;997S644IN1LKJ-HAF)D'&;@#!!6}49z765v32+rqp',m*)jhh%$#z!ba`^^\\ZvuWslUjoRPPeNLhKII^cbD`YBW@>><<::88664P3NM0K.IHG@E(C&%:?"=<||9876/v3t1rpp',+k)(i~%$d"ybw`^^\\ZZXXVVTTRRPPNNLhKfedGba`_XA\?Z=XWVUT66KPO2G0K.IH*FE(=&$@#!!6;:z81x/vttrrp.omm$)(h&}f{dbb``^^\\ZZXtWrqpiRmPkNihJJ_dGbEDYBW\[=YR;P977553311//--++))''%A$?>=~5:{z7x54uss0)po,mkk"'&f$#dy~a__ty\wvYtWrkToRQfkNihJJed]bE`C^A??TYX:VU8MR5PON1LKDI,G*)>C&A@""=<;4{8yxvvt2sqq(-,l*#j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##8=<}4{8y65u32s*qoom+*j(!h}$eccxa__]][[YYWWUUSSQmPNNchKfed]FE`CAAV[><<QV9TS6Q4I21L/JI,**E>C&%@#!!6;|zz16w43t1r/(-nm*kii~%fddy~a|{^y\wvoXWrUpoRPPkjibgJIdGEEZ_B@@UZ=XW:U8SRQJO2M0K.,,A*((&B%##8=<|:3z1xvvttrrppnnlljjh&g$#"c~}|{t]x[vYtsrqpRRglkNcLgJI^G\EC_B@@UZY;WP9N75Q422GLK-IB+@)'CB$@9"7~||zzxxvvttrrp.o,+*#j'h%f#"bbw|_z]\qvuWslUjoRPPeNLhgfH^G\ECCAA??==;;9977553O2MLK.CH+*)>C&A@#>!<5|{8y65vtt10).on+ljj!&geez!b}|_z]xwpuXsVUjonPleNchKII^GEEC_B@@UZYX:P9N7553ON0LE.CH+))>'%%##!!}}{{y7x543t10/(on+l)(igg$#"!x}`_z][[puXVVkpSnmPkNihgf_dGbE`C^]\[Z<<QVU8M6Q43H1FKJ,HA*?D'%%:#!!};|zz165u3,s*qo-,l*#j!hffddbb``^^\\ZvYtsrkToRQfkNLLafedF\EZCA]@>>SXW9UN7L53311//--++))''%%#?"=<;|3zy6w43trr/(-nm*kii~%fddy~a|{^y\wpuXsVUjSQmlNjcLafIGG\ECCA]\[=S<QV977L53311//--++))'C&A@?"=<5|9z7x54tt10/(-n+l)jhh}$#"bxav_]][[YYWWUUSSQQOOMMKgJedcFa`_X]@?Z=;;PU866KP3NM0K.IHGF?(C&%:#8=~||387w5.u,sqqo-,l*#j!hffddbb``^^\\ZZXtWrqpiRQlOjiLJJ_dGFaDBBW\?==RW:UT7R5JO2M0K.,,A*?DC%A:#8=~||3zxxvvttr0/o-&m$)jhh}fddbb``^^\\ZvYtsrUpiRQPejMhgJHHcb[`CB]\[=S<Q:8866442NML.D-B+))''%%##!!};|98y6w43,1r/po&+*)i!h}fd"!~`v_t][wvXtmVkTRnmOkdMbKIedFb[DY^A??T=;;997755331M0KJI,GFE>'&%:?"=<}{{8765.3ts0/o-&m$kiiggeec!~}_u^s\ZZXXVVTTRRPlOjiLgJedcb[`C^A\?ZYXWV88MRQ4I2M0/D-B+))'CB$@9"7<}{{2yw54t2+r)pnnlljjhhffddb~a|{zs\[vYWWlqTRRglOjiLgJ_HGbE`_B@@[TY<;V977LQ422GL/JI,G*E>C&%@#!!6;|zz16w43t1r/.'nm*k('hff#"!x}`_z][[puXVVkpSnmPkNihg`eHGbECCX]@>>SX;VU8S6QPONG0K.-BG*((=&;@#!!6;:9y1x/vttrrp.-m+$k"iggeeccaa__]][wZutslUToRmlOMMbgJIdGEEZ_B@@UZ=XW:U8MR54O200EJ-++@E(CB%@#>7~;|9z76vv32+0q.on%l#jh&geez!~`|u^s\ZZXtsUqjShmPNNcLJfeGc\EZ_B@@U><<::8866442N1LKJ-HG@E('B%##8=~||38y65v3t10/(on+l)(igg$#"!x}`_z][[puXVVkpSnmPkNihgf_dGbEDYBW\?==RWV8TM6K42NML.D-B+))''%%##!!}}{{yyw5v321*qp-nll#(igg|ez!b}|_zs\[ZoXmVTponPfOdiLJJ_HFFD`CAAV[Z<XQ:O866442200..,,*F)DC&A$9"!<}:9zxx5.3ts0qoo&+ljj!&g$#d!b}v{^y\[putVrqTiRPPNNLLJfeGc\EZ_B@@U><<::8866442N1LKJ-HG@)D'&;@#!!6}49z765v321*/pon%l#j!hffd"caav{z\xqZoXVrqpRhQfOMihJf_H]bECCXA?[Z<XQ:OT755J311//--++))(aBA@?>=<;:9876543210/.-,+*)54&%ed/.a=_^zy87YXts21}|nm,+j)hg&%qpbam_kj\[>=ed:U87_^PO2MLXJI,+SRDP&AML>=}|Gz87wvA@21qp;n,+kj54&%e#/.>=_^zy[7YXts21}|nz,+wvhg&%q#baDCkj\[>=edVU87_^4\21YXJI,+F)DC&%ML>JI|GF87wvAts1qp;:,+kj5h&%ed/.>=_^zy87YXts2q}|nm,+wvht&%qpbaDCkj\[>=edVU8S_^PO21YXJV,+SRDC&%M#>=}|GF8DC5A@21qp;nm+kj54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<|GFy7CBAt21qp;:9+76(4&%e0/ba`|^zy87v5tVr1}|.zykjiug&%qponm_^j\[gYX;:UT7_^P32MYKJI,+F)(CBA$L>=I;:z8D6vA@2>q<.n,l*6i'32e0/.>=_{zy8wYXtsU10|.-y+wvhg&e$#baDC^A\h>=<dVU87_54321YX.IH+*)DC&%MLK~I|G9Ex6Bu@srqp;:,8kj('&%ed"b>}_^zy87YXWVr1}|nmy+*vuts%qpbaDl^]i[>=XdcU8SR^PO2MY/WI,T*EQ'BAM?>=}|Gzy7wvu@21q<;n9+kj54&fe#cb>=_^z98wYXW3r~0o{m,k*vhg&rqp"n`lB]i?Zfed:baSR54O[MLKW-HT*EDPON$?K~<|G9yx6Bu3?1=/.-9l*6i43f10c!~`<;:9[Z6uW3r1}o{-lx*iut&%d#"nm_^A\hgf<Wc9TSR^4O21YKJV,GSRDC&A$?K~}H{9Ex6vA@s1qp.:9+*j54&%e0/.>}_^zy87Y5t32~0o{-lkjih'fr$coaDCkj\[>fe;:ba`6Q]3NMYK.I,+SRDP&AM?K~<H{F8x6Bu3?r0/.-9+kj5h3f$#"!~`<{]\8Z6uW3r~po{mlx*iu'feqpo!`lB]i?ZfXWc9T`65P\[1YX.V,GS)('BN$?KJ}H:9Ex6B43?>0<o-9l*j5'g%ed".~=<^zy87YXtVr~}|nmykw)htsr$co!`CkA\[>=XdcUa`_^PO21Y/W-,+SR(P&AM#>~<H{9EDwv4@21q<.:9+kj54&%ed".>=_^z9[w6X4s21p/nzykjvhgs%$ponDlB]i?ZYeWVU87R54\NM0XJIUGF)DCO%ML"=IHGFE7wvAt?rqp.:,+k654gf$T/RQ
There is a built-in command for this in Maple.
> StringTools:-Encode( "The Quick Brown Fox Jumped Over The Lazy Dog!", encoding = rot13 ); "Gur Dhvpx Oebja Sbk Whzcrq Bire Gur Ynml Qbt!"
Rot13[s_]:=StringReplace[s,#->RotateLeft[#,13]&@*CharacterRange@@#&[{"a","z"},{"A","Z"}]//Thread]Rot13["Hello World!"]Rot13[%]
Uryyb Jbeyq!Hello World!
functionr=rot13(s)ifischar(s)r=s;% preallocation and copy of non-lettersfori=1:size(s,1)forj=1:size(s,2)ifisletter(s(i,j))ifs(i,j)>=97% lower casebase=97;else% upper casebase=65;endr(i,j)=char(mod(s(i,j)-base+13,26)+base);endendendelseerror('Argument must be a CHAR')endend
Call it like this:
>>rot13('Hello World!')ans=UryybJbeyq!
It is possible to vectorize this code, the example below is not fully vectorized in order to make the order of operations clear. It is possible to reduce this solution to two lines by integrating the "selectedLetters" calculations directly into the line following them.
functiontext=rot13(text)ifischar(text)selectedLetters=((text>='A')&(text<='Z'));%Select upper case letterstext(selectedLetters)=char(mod(text(selectedLetters)-'A'+13,26)+'A');selectedLetters=((text>='a')&(text<='z'));%Select lower case letterstext(selectedLetters)=char(mod(text(selectedLetters)-'a'+13,26)+'a');elseerror('Argument must be a string.')endend
Sample Output:
>>plainText=char((64:123))plainText=@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{>>rot13(plainText)ans=@NOPQRSTUVWXYZABCDEFGHIJKLM[\]^_`nopqrstuvwxyzabcdefghijklm{
rot13(a):=simplode(map(ascii,map(lambda([n],if(n>=65andn<=77)or(n>=97andn<=109)thenn+13elseif(n>=78andn<=90)or(n>=110andn<=122)thenn-13elsen),map(cint,sexplode(a)))))$lowercase:"abcdefghijklmnopqrstuvwxyz"$uppercase:"ABCDEFGHIJKLMNOPQRSTUVWXYZ"$rot13(lowercase);"nopqrstuvwxyzabcdefghijklm"rot13(uppercase);"NOPQRSTUVWXYZABCDEFGHIJKLM"rot13("The quick brown fox jumps over the lazy dog");"Gur dhvpx oebja sbk whzcf bire gur ynml qbt"rot13(%);"The quick brown fox jumps over the lazy dog"
:- module rot13.:- interface.:- import_module io.:- pred main(io::di, io::uo) is det.:- implementation.:- import_module string, set, list, char, int.:- type transition == {character, character}.:- type transitions == set(transition).:- type rot_kind ---> encrypt ; decrypt.:- pred build_transition(int::in, rot_kind::in, int::in, int::in, character::in, transitions::in, transitions::out) is det.build_transition(Offset, Kd, Lb, Ub, Ch, St, Rs) :- ( Kd = encrypt, Diff = to_int(Ch) + Offset ; Kd = decrypt, Diff = to_int(Ch) - Offset ), (if (Diff >= (Ub + 0x01)) then Ct = {Ch, det_from_int(Lb + (Diff - Ub) - 0x01) `with_type` char} else if (Diff =< (Lb - 0x01)) then Ct = {Ch, det_from_int(Ub - (Lb - Diff) + 0x01) `with_type` char} else Ct = {Ch, det_from_int(Diff) `with_type` char}), union(St, make_singleton_set(Ct), Rs).:- pred generate_alpha_transition(int::in, rot_kind::in, transitions::out) is det.generate_alpha_transition(N, Kd, Ts) :- Offset = N mod 0x1A, to_char_list("abcdefghijklmnopqrstuvwxyz", Lower), to_char_list("ABCDEFGHIJKLMNOPQRSTUVWXYZ", Upper), foldl(build_transition(Offset, Kd, 0x61, 0x7A), Lower, init, Ts0), foldl(build_transition(Offset, Kd, 0x41, 0x5A), Upper, Ts0, Ts).:- pred rot(transitions::in, string::in, string::out) is det.rot(Ts, Base, Result) :- to_char_list(Base, Fragment), map((pred(Ch::in, Rs::out) is det :- promise_equivalent_solutions [Rs] (if member({Ch, Nx}, Ts) then Rs = Nx else Rs = Ch) ), Fragment, Result0), from_char_list(Result0, Result).:- pred invoke_line(transitions::in, string::in, text_input_stream::in, io::di, io::uo) is det.invoke_line(Ts, File, Stream, !IO) :- read_line_as_string(Stream, Line, !IO), ( Line = ok(Base), rot(Ts, Base, Rot), write_string(Rot, !IO), invoke_line(Ts, File, Stream, !IO) ; Line = error(_), format("Can't read correctly the file %s.\n", [s(File)], !IO) ; Line = eof ).:- pred handle_files(transitions::in, list(string)::in, io::di, io::uo) is det.handle_files(_, [], !IO).handle_files(Ts, [Head|Tail], !IO) :- open_input(Head, Result, !IO), ( Result = ok(Stream), invoke_line(Ts, Head, Stream, !IO), close_input(Stream, !IO) ; Result = error(_), format("Can't open the file %s.\n", [s(Head)], !IO) ), handle_files(Ts, Tail, !IO).main(!IO) :- generate_alpha_transition(0x0D, encrypt, Table), command_line_arguments(Args, !IO), ( Args = [_|_], handle_files(Table, Args, !IO) ; Args = [], invoke_line(Table, "<stdin>", stdin_stream, !IO) ).:- end_module rot13.
Sub Rot13 EncodedString = "" For i = 1 To Text.GetLength(String) Code = Text.GetCharacterCode(Text.GetSubText(String, i, 1)) If Code >= 65 And Code <= 90 Then EncodedCode = Code + 13 If EncodedCode > 90 Then EncodedCode = 64 + EncodedCode - 90 EndIf ElseIf Code >= 97 And Code <= 122 Then EncodedCode = Code + 13 If EncodedCode > 122 Then EncodedCode = 96 + EncodedCode - 122 EndIf Else EncodedCode = Code EndIf EncodedString = EncodedString + Text.GetCharacter(EncodedCode) EndForEndSubString = "Rosetta Code"Rot13()TextWindow.WriteLine(EncodedString)
Ebfrggn PbqrPress any key to continue...
( "(?i)[A-M]|([N-Z])" (-> '== (-13) (13) if nip swap ord + chr) replace-apply) ^rot13
rot13=function(s)chars=s.valuesforiinchars.indexesc=chars[i]ifc>="a"andc<="z"thenchars[i]=char(97+(code(c)-97+13)%26)ifc>="A"andc<="Z"thenchars[i]=char(65+(code(c)-65+13)%26)endforreturnchars.join("")endfunctionprintrot13("Hello world!")printrot13("Uryyb jbeyq!")
Uryyb jbeyq!Hello world!
def rot13 (value:string) result = "" d = ' '.toCharArray[0] value.toCharArray.each do |c| testChar = Character.toLowerCase(c) if testChar <= 'm'.toCharArray[0] && testChar >= 'a'.toCharArray[0] then d = char(c + 13) end if testChar <= 'z'.toCharArray[0] && testChar >= 'n'.toCharArray[0] then d = char(c - 13) end result += d end resultendputs rot13("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
fun rot13char c = if c >= #"a" andalso c <= #"m" orelse c >= #"A" andalso c <= #"M" then chr (ord c + 13) else if c >= #"n" andalso c <= #"z" orelse c >= #"N" andalso c <= #"Z" then chr (ord c - 13) else cval rot13 = String.map rot13char
Helper function:
fun rot13stdin () = case (TextIO.inputLine TextIO.stdIn) of NONE => () | SOME(s) => (print (rot13 s); rot13stdin ());
Reads text file from stdin to list of lines, encodes and prints lines of encoding to stdout.
fun readfile () = readfile [] | x = let val ln = readln () in if eof ln then rev x else readfile ` ln :: x endlocalval lower_z = ord #"z";val upper_z = ord #"Z";val lower_a = ord #"a";val upper_a = ord #"A";fun which (c_upper c) = (upper_a, upper_z)|_ = (lower_a, lower_z);fun scale (c, az) where (c > #1 az) = scale( (#0 az + (c - #1 az - 1)), az)|(c, az) = cinfun rot13([], t) = implode ` rev t|(x :: xs, t) where (c_alphabetic x) = rot13 (xs, (chr ` scale (ord x + 13, which x)) :: t)|(x :: xs, t) = rot13 (xs, x :: t)|s = rot13 (explode s, [])end;map (println o rot13) ` readfile ();
// main registerspIS$255% text pointercGREG% charccGREG% uppercase copy of cuGREG% all purposeLOCData_SegmentGREG@TestBYTE"dit is een bericht voor de keizer",#a,0LOC#100MainLDAp,TestTRAP0,Fputs,StdOut% show text to encryptLDAp,Test% points to text to encryptJMP4F// do in place text encryption% REPEAT2HADDcc,c,0% copy charSUBcc,cc,' '% make uppercaseCMPu,cc,'A'BNu,3F% IF c < 'A' OR c > 'Z' THEN next charCMPu,cc,'Z'BPu,3FCMPu,cc,'N'% ELSEBNu,1F% IF c < 'N' THEN encrypt 'up'SUBc,c,26% ELSE char ready for encrypt 'down'1HINCLc,13% encrypt charSTBUc,p% replace char with encrypted char3HINCLp,1% move to next char4HLDBUc,p% get next charPBNZc,2B% UNTIL EOT// print resultLDAp,TestTRAP0,Fputs,StdOut% show encrypted textTRAP0,Halt,0
Example:
~/MIX/MMIX/Progs> mmix rot13simpldit is een bericht voor de keizerqvg vf rra orevpug ibbe qr xrvmre
MODULE Rot13;FROM STextIO IMPORT ReadString, WriteString, WriteLn;FROM Strings IMPORT Length;TYPE MyString = ARRAY [0..80] OF CHAR;VAR S, T : MyString;PROCEDURE Rot13(S : ARRAY OF CHAR; VAR T : ARRAY OF CHAR);VAR I, J : CARDINAL;BEGIN FOR I := 0 TO Length(S) - 1 DO J := ORD(S[I]); IF ((J >= 65) AND (J <= 90)) THEN J := (J - 52) % 26 + 65; IF ((J >= 97) AND (J <= 122)) THEN J := (J - 84) % 26 + 97; T[I] := CHR(J); END;END Rot13;BEGIN WHILE NOT Eof DO ReadString(S); SkipLine; WriteLn; Rot13(S, T); WriteString(T); WriteLn; END;END Rot13.
This implementation reads fromstdin and writes tostdout.
MODULE Rot13 EXPORTS Main;IMPORT Stdio, Rd, Wr;VAR c: CHAR;<*FATAL ANY*>BEGIN WHILE NOT Rd.EOF(Stdio.stdin) DO c := Rd.GetChar(Stdio.stdin); IF c >= 'A' AND c <= 'M' OR c >= 'a' AND c <= 'm' THEN c := VAL(ORD((ORD(c) + 13)), CHAR); ELSIF c >= 'N' AND c <= 'Z' OR c >= 'n' AND c <= 'z' THEN c := VAL(ORD((ORD(c) - 13)), CHAR); END; Wr.PutChar(Stdio.stdout, c); END;END Rot13.
Output:
martin@thinkpad:~$ ./progFoo bar bazSbb one onmmartin@thinkpad:~$ echo "Bar baz foo" | ./progOne onm sbbmartin@thinkpad:~$ echo "Foo bar baz" > foo.txt martin@thinkpad:~$ echo "quux zeepf" >> foo.txt martin@thinkpad:~$ cat foo.txt | ./progSbb one onmdhhk mrrcs
Rot13(in)New low,rot,upSet up="ABCDEFGHIJKLMNOPQRSTUVWXYZ"Set low="abcdefghijklmnopqrstuvwxyz"Set rot=$Extract(up,14,26)_$Extract(up,1,13)Set rot=rot_$Extract(low,14,26)_$Extract(low,1,13)Quit $Translate(in,up_low,rot)Write $$Rot13("Hello World!") ; Uryyb Jbeyq!Write $$Rot13("ABCDEFGHIJKLMNOPQRSTUVWXYZ") ; NOPQRSTUVWXYZABCDEFGHIJKLM
def rot13(plaintext)uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"lowercase = "abcdefghijklmnopqrstuvwxyz"cypher = ""for char in plaintextif uppercase .contains. charcypher += uppercase[uppercase[char] - 13]else if lowercase .contains. charcypher += lowercase[lowercase[char] - 13]elsecypher += charendendreturn cypherend
% import "rot13.nq"% println rot13("This is a test.")Guvf vf n grfg.% println rot13("Nanoquery 2.3")Anabdhrel 2.3
rotate13 function based on ALGOL-68 entry.
/* ROT-13 in Neko*//* Assume ASCII encoding */var rotate13 = function(c) { if (c >= 65 && c <= 77) || (c >= 97 && c <= 109) c += 13 else if (c >= 78 && c <= 90) || (c >= 110 && c <= 122) c -= 13 return c}var rot13 = function(s) { var r = $scopy(s) var len = $ssize(r) var pos = 0 while pos < len { $sset(r, pos, rotate13($sget(r, pos))) pos += 1 } return r}var msg = $loader.args[0]if msg == null { var testing = "[abcdefghijklmnopqrstuvwxyz 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ]" $print(testing, "\n", replaced = rot13(testing), "\n") $print(rot13(replaced), "\n") $print("\n") msg = "The secret message said \"Open Sesame!\""}$print(msg, "\n", replaced = rot13(msg), "\n")$print(rot13(replaced), "\n")
prompt$ nekoc rot-13.nekoprompt$ neko rot-13[abcdefghijklmnopqrstuvwxyz 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ][nopqrstuvwxyzabcdefghijklm 0123456789 NOPQRSTUVWXYZABCDEFGHIJKLM][abcdefghijklmnopqrstuvwxyz 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ]The secret message said "Open Sesame!"Gur frperg zrffntr fnvq "Bcra Frfnzr!"The secret message said "Open Sesame!"prompt$ neko rot-13 'nowhere ABJURER'nowhere ABJURERabjurer NOWHEREnowhere ABJURER
This sample leverages the code demonstrated in theCaesar cipher – NetRexx task.
/* NetRexx */options replace format comments java crossref savelog symbols nobinaryparse arg fileNamesrdr = BufferedReaderdo if fileNames.length > 0 then do loop n_ = 1 for fileNames.words fileName = fileNames.word(n_) rdr = BufferedReader(FileReader(File(fileName))) encipher(rdr) end n_ end else do rdr = BufferedReader(InputStreamReader(System.in)) encipher(rdr) endcatch ex = IOException ex.printStackTraceendreturnmethod encipher(rdr = BufferedReader) public static signals IOException loop label l_ forever line = rdr.readLine if line = null then leave l_ say rot13(line) end l_ returnmethod rot13(input) public static signals IllegalArgumentException return caesar(input, 13, isFalse)method caesar(input = Rexx, idx = int, caps = boolean) public static signals IllegalArgumentException if idx < 1 | idx > 25 then signal IllegalArgumentException() -- 12345678901234567890123456 itab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' shift = itab.length - idx parse itab tl +(shift) tr otab = tr || tl if caps then input = input.upper cipher = input.translate(itab || itab.lower, otab || otab.lower) return ciphermethod caesar_encipher(input = Rexx, idx = int, caps = boolean) public static signals IllegalArgumentException return caesar(input, idx, caps)method caesar_decipher(input = Rexx, idx = int, caps = boolean) public static signals IllegalArgumentException return caesar(input, int(26) - idx, isFalse)method caesar_encipher(input = Rexx, idx = int) public static signals IllegalArgumentException return caesar(input, idx, isFalse)method caesar_decipher(input = Rexx, idx = int) public static signals IllegalArgumentException return caesar(input, int(26) - idx, isFalse)method caesar_encipher(input = Rexx, idx = int, opt = Rexx) public static signals IllegalArgumentException return caesar(input, idx, opt)method caesar_decipher(input = Rexx, idx = int, opt = Rexx) public static signals IllegalArgumentException return caesar(input, int(26) - idx, opt)method caesar(input = Rexx, idx = int, opt = Rexx) public static signals IllegalArgumentException if opt.upper.abbrev('U') >= 1 then caps = isTrue else caps = isFalse return caesar(input, idx, caps)method caesar(input = Rexx, idx = int) public static signals IllegalArgumentException return caesar(input, idx, isFalse)method isTrue public static returns boolean return (1 == 1)method isFalse public static returns boolean return \isTrue
Output(using the source file as input):
/* ArgErkk */bcgvbaf ercynpr sbezng pbzzragf wnin pebffers fnirybt flzobyf abovanelcnefr net svyrAnzrfeqe = OhssrerqErnqreqb vs svyrAnzrf.yratgu > 0 gura qb ybbc a_ = 1 sbe svyrAnzrf.jbeqf svyrAnzr = svyrAnzrf.jbeq(a_) eqe = OhssrerqErnqre(SvyrErnqre(Svyr(svyrAnzr))) rapvcure(eqe) raq a_ raq ryfr qb eqe = OhssrerqErnqre(VachgFgernzErnqre(Flfgrz.va)) rapvcure(eqe) raqpngpu rk = VBRkprcgvba rk.cevagFgnpxGenprraqergheazrgubq rapvcure(eqe = OhssrerqErnqre) choyvp fgngvp fvtanyf VBRkprcgvba ybbc ynory y_ sberire yvar = eqe.ernqYvar vs yvar = ahyy gura yrnir y_ fnl ebg13(yvar) raq y_ ergheazrgubq ebg13(vachg) choyvp fgngvp fvtanyf VyyrtnyNethzragRkprcgvba erghea pnrfne(vachg, 13, vfSnyfr)zrgubq pnrfne(vachg = Erkk, vqk = vag, pncf = obbyrna) choyvp fgngvp fvtanyf VyyrtnyNethzragRkprcgvba vs vqk < 1 | vqk > 25 gura fvtany VyyrtnyNethzragRkprcgvba() -- 12345678901234567890123456 vgno = 'NOPQRSTUVWXYZABCDEFGHIJKLM' fuvsg = vgno.yratgu - vqk cnefr vgno gy +(fuvsg) ge bgno = ge || gy vs pncf gura vachg = vachg.hccre pvcure = vachg.genafyngr(vgno || vgno.ybjre, bgno || bgno.ybjre) erghea pvcurezrgubq pnrfne_rapvcure(vachg = Erkk, vqk = vag, pncf = obbyrna) choyvp fgngvp fvtanyf VyyrtnyNethzragRkprcgvba erghea pnrfne(vachg, vqk, pncf)zrgubq pnrfne_qrpvcure(vachg = Erkk, vqk = vag, pncf = obbyrna) choyvp fgngvp fvtanyf VyyrtnyNethzragRkprcgvba erghea pnrfne(vachg, vag(26) - vqk, vfSnyfr)zrgubq pnrfne_rapvcure(vachg = Erkk, vqk = vag) choyvp fgngvp fvtanyf VyyrtnyNethzragRkprcgvba erghea pnrfne(vachg, vqk, vfSnyfr)zrgubq pnrfne_qrpvcure(vachg = Erkk, vqk = vag) choyvp fgngvp fvtanyf VyyrtnyNethzragRkprcgvba erghea pnrfne(vachg, vag(26) - vqk, vfSnyfr)zrgubq pnrfne_rapvcure(vachg = Erkk, vqk = vag, bcg = Erkk) choyvp fgngvp fvtanyf VyyrtnyNethzragRkprcgvba erghea pnrfne(vachg, vqk, bcg)zrgubq pnrfne_qrpvcure(vachg = Erkk, vqk = vag, bcg = Erkk) choyvp fgngvp fvtanyf VyyrtnyNethzragRkprcgvba erghea pnrfne(vachg, vag(26) - vqk, bcg)zrgubq pnrfne(vachg = Erkk, vqk = vag, bcg = Erkk) choyvp fgngvp fvtanyf VyyrtnyNethzragRkprcgvba vs bcg.hccre.nooeri('H') >= 1 gura pncf = vfGehr ryfr pncf = vfSnyfr erghea pnrfne(vachg, vqk, pncf)zrgubq pnrfne(vachg = Erkk, vqk = vag) choyvp fgngvp fvtanyf VyyrtnyNethzragRkprcgvba erghea pnrfne(vachg, vqk, vfSnyfr)zrgubq vfGehr choyvp fgngvp ergheaf obbyrna erghea (1 == 1)zrgubq vfSnyfr choyvp fgngvp ergheaf obbyrna erghea \vfGehr
(define (rot13 str) (join (map (fn(c) (cond ((<= "A" (upper-case c) "M") (char (+ (char c) 13))) ((<= "N" (upper-case c) "Z") (char (- (char c) 13))) (true c))) (explode str))))
import strutilsproc rot13(c: char): char = case toLowerAscii(c) of 'a'..'m': chr(ord(c) + 13) of 'n'..'z': chr(ord(c) - 13) else: cfor line in stdin.lines: for c in line: stdout.write rot13(c) stdout.write "\n"
let map = ( seq char A Z | zip (seq char a z) | flatten | into record | [$in $in] | headers | first | roll left -c -b 26)def rot13 [] { split chars | each {|c| $map | get -i -s $c | default $c } | str join}
bundle Default { class Rot13 { function : Main(args : String[]) ~ Nil { Rot13("nowhere ABJURER")->PrintLine(); } function : native : Rot13(text : String) ~ String { rot := ""; each(i : text) { c := text->Get(i); if(c >= 'a' & c <= 'm' | c >= 'A' & c <= 'M') { rot->Append(c + 13); } else if(c >= 'n' & c <= 'z' | c >= 'N' & c <= 'Z') { rot->Append(c - 13); } else { rot->Append(c); }; }; return rot; } }}
Straightforward implementation for characters by using character range patterns:
let rot13 c = match c with | 'A'..'M' | 'a'..'m' -> char_of_int (int_of_char c + 13) | 'N'..'Z' | 'n'..'z' -> char_of_int (int_of_char c - 13) | _ -> c
We provide a function for converting whole strings:
let rot13_str s = let len = String.length s in let result = String.create len in for i = 0 to len - 1 do result.[i] <- rot13 s.[i] done; result(* or in OCaml 4.00+: let rot13_str = String.map rot13*)
And here is a utility program that converts the content read onsdtin
and write it tostdout
:
let () = try while true do String.iter (fun c -> print_char (rot13 c)) (read_line()); print_newline() done with End_of_file -> ()
: encryptRot13(c) c dup isLetter ifFalse: [ return ] isUpper ifTrue: [ 'A' ] else: [ 'a' ] c 13 + over - 26 mod + ;: rot13 map(#encryptRot13) charsAsString ;
>"Oolite quick Thargoid jumps lazy Vipers = blown up + special fx" rot13 printlnBbyvgr dhvpx Gunetbvq whzcf ynml Ivcref = oybja hc + fcrpvny sk
(import (scheme char))(define (rot13 str) (runes->string (map (lambda (ch) (+ ch (cond ((char-ci<=? #\a ch #\m) 13) ((char-ci<=? #\n ch #\z) -13) (else 0)))) (string->runes str))))(define str "`What a curious feeling!' said Alice; `I must be shutting up like a telescope.'")(print (rot13 str))(print (rot13 (rot13 str)))
`Jung n phevbhf srryvat!' fnvq Nyvpr; `V zhfg or fuhggvat hc yvxr n gryrfpbcr.'`What a curious feeling!' said Alice; `I must be shutting up like a telescope.'
; rot-13.xomglobal stream gs-phrasedefine stream function apply-rot-13 (value stream phrase) as local integer b local stream ciphered open ciphered as buffer repeat scan phrase match letter => char set b to char binary 0 increment b by 13 decrement b by 26 when char matches uc and b > 90 decrement b by 26 when char matches lc and b > 122 put ciphered "b" % b match any => char put ciphered char again close ciphered return cipheredprocess output apply-rot-13(gs-phrase)
> omnimark -sb rot-13.xom -d gs-phrase "abc"nop> omnimark -sb rot-13.xom -d gs-phrase "nop"abc> omnimark -sb rot-13.xom -d gs-phrase "Rot-13 is easy to crack!"Ebg-13 vf rnfl gb penpx!> omnimark -sb rot-13.xom -d gs-phrase "Ebg-13 vf rnfl gb penpx!"Rot-13 is easy to crack!
declare fun {RotChar C} if C >= &A andthen C =< &Z then &A + (C - &A + 13) mod 26 elseif C >= &a andthen C =< &z then &a + (C - &a + 13) mod 26 else C end end fun {Rot13 S} {Map S RotChar} endin {System.showInfo {Rot13 "NOWHERE Abjurer 42"}} {System.showInfo {Rot13 {Rot13 "NOWHERE Abjurer 42"}}}
rot13(s)={ s=Vecsmall(s); for(i=1,#s, if(s[i]>109&s[i]<123,s[i]-=13,if(s[i]<110&s[i]>96,s[i]+=13,if(s[i]>77&s[i]<91,s[i]-=13,if(s[i]<78&s[i]>64,s[i]+=13)))) ); Strchr(s)};
program rot13;var line: string; function rot13(someText: string): string; var i: integer; ch: char; result: string; begin result := ''; for i := 1 to Length(someText) do begin ch := someText[i]; case ch of 'A' .. 'M', 'a' .. 'm': ch := chr(ord(ch)+13); 'N' .. 'Z', 'n' .. 'z': ch := chr(ord(ch)-13); end; result := result + ch; end; rot13 := result; end;begin while not eof(input) do begin readln(line); writeln(rot13(line)); end;end.
function Rot13(s: string): string;begin var sb := new StringBuilder; foreach var c in s do begin var c1 := c; if c in 'a'..'z' then c1 := Chr((c.Code - 'a'.Code + 13) mod 26 + 'a'.Code) else if c in 'A'..'Z' then c1 := Chr((c.Code - 'A'.Code + 13) mod 26 + 'A'.Code); sb.Append(c1) end; Result := sb.ToString;end;begin Println(rot13('foo')); Println(rot13('sbb'))end.
sbbfoo
sub rot13 { shift =~ tr/A-Za-z/N-ZA-Mn-za-m/r;} print rot13($_) while (<>);
Input:
NOWHERE Abjurer
Output:
ABJURER Nowhere
One-liner version:
perl -pe 'tr/A-Za-z/N-ZA-Mn-za-m/'
functionrot13(strings)integerchfori=1tolength(s)doch=upper(s[i])ifch>='A'andch<='Z'thens[i]+=iff(ch<='M',+13,-13)endifendforreturnsendfunction?rot13("abjurer NOWHERE.")
"nowhere ABJURER."
PHP has a built-in function for this:
echo str_rot13('foo'), "\n";
will output
sbb
Here is an implementation:
<?phpfunction rot13($s) { return strtr($s, 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm');}echo rot13('foo'), "\n";?>
Output:
sbb
go => S = "Big fjords vex quick waltz nymph!", println(S), println(rot13(S)), println(rot13(rot13(S))), nl. % Rot 13 using a maprot13(S) = S2 => lower(Lower), upper(Upper), M = create_map(Lower, Upper), % If a char is not in a..zA..z then show it as it is. S2 := [M.get(C,C) : C in S].create_map(Lower, Upper) = M => M = new_map(), Len = Lower.length, LDiv := Lower.length div 2, foreach(I in 1..Len) II = (LDiv+I) mod Len, if II == 0 then II := Len end, M.put(Upper[I],Upper[II]), M.put(Lower[I],Lower[II]) end.lower("abcdefghijklmnopqrstuvwxyz").upper("ABCDEFGHIJKLMNOPQRSTUVWXYZ").
Big fjords vex quick waltz nymph!Ovt swbeqf irk dhvpx jnygm alzcu!Big fjords vex quick waltz nymph!
(de rot13-Ch (C) (if (or (member C '`(apply circ (chop "ABCDEFGHIJKLMNOPQRSTUVWXYZ"))) (member C '`(apply circ (chop "abcdefghijklmnopqrstuvwxyz"))) ) (get @ 14) C ) )
or:
(de rot13-Ch (C) (cond ((>= "M" (uppc C) "A") (char (+ (char C) 13)) ) ((>= "Z" (uppc C) "N") (char (- (char C) 13)) ) (T C) ) )
Then call it as:
(de rot13-stdIn () (while (line) (prinl (mapcar rot13-Ch @)) ) )
import Crypto;int main(){ string r = rot13("Hello, World"); write(r + "\n");}
rotate: procedure (in) options (main); /* 2 March 2011 */ declare in character (100) varying; declare line character (500) varying; declare input file; open file (input) title ('/' || in || ',type(text),recsize(500)' ); on endfile (input) stop; do forever; get file (input) edit (line) (L); line = translate ( line, 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'); put edit (line) (a); put skip; end;end;
Data file:
"The time has come,"the walrus said,"to speak of many things;of ships and shoes and sealing wax;of cabbages and kings."
Output:
"Gur gvzr unf pbzr,"gur jnyehf fnvq,"gb fcrnx bs znal guvatf;bs fuvcf naq fubrf naq frnyvat jnk;bs pnoontrf naq xvatf."
Since PL/I-80 includes the translate() function, the code given for the full language would work without change (and, for an unruly character set, would definitely be the way to go). But here is another approach that is fine for ASCII.
rot13_test: procedure options(main); dcl (plain, encoded) char(127) varying; plain = 'The quick brown fox jumps over the lazy dog.'; put skip list ('Plain text:', plain); encoded = rot13(plain); put skip list ('Encoded :', encoded); put skip list ('Restored :', rot13(encoded)); stop;rot13: procedure (s) returns (char(127) varying); dcl s char(127) varying, ch char(1), i fixed bin(15); do i = 1 to length(s); ch = substr(s,i,1); if (ch >= 'a' & ch <= 'm') | (ch >= 'A' & ch <= 'M') then ch = ascii(rank(ch) + 13); else if (ch >= 'n' & ch <= 'z') | (ch >= 'N' & ch <= 'Z') then ch = ascii(rank(ch) - 13); substr(s,i,1) = ch; end; return (s); end rot13;end rot13_test;
Plain text: The quick brown fox jumps over the lazy dog.Encoded : Gur dhvpx oebja sbk whzxc bire gur ynml qbt.Restored : The quick brown fox jumps over the lazy dog.
-- Works for VARCHAR2 (up to 32k chars)CREATE OR REPLACE FUNCTION fn_rot13_native(p_text VARCHAR2) RETURN VARCHAR2 IS c_source CONSTANT VARCHAR2(52) := 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; c_target CONSTANT VARCHAR2(52) := 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm';BEGIN RETURN TRANSLATE(p_text, c_source, c_target);END;/-- For CLOBs (translate only works with VARCHAR2, so do it in chunks)CREATE OR REPLACE FUNCTION fn_rot13_clob(p_text CLOB) RETURN CLOB IS c_source CONSTANT VARCHAR2(52) := 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; c_target CONSTANT VARCHAR2(52) := 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'; c_chunk_size CONSTANT PLS_INTEGER := 4000; v_result CLOB := NULL;BEGIN FOR i IN 0..TRUNC(LENGTH(p_text) / c_chunk_size) LOOP v_result := v_result || TRANSLATE(dbms_lob.substr(p_text, c_chunk_size, i * c_chunk_size + 1), c_source, c_target); END LOOP; RETURN v_result;END;/-- The full algorithm (Slower. And MUCH slower if using CLOB!)CREATE OR REPLACE FUNCTION fn_rot13_algorithm(p_text VARCHAR2) RETURN CLOB IS c_upper_a CONSTANT PLS_INTEGER := ASCII('A'); c_lower_a CONSTANT PLS_INTEGER := ASCII('a'); v_rot VARCHAR2(32000); v_char VARCHAR2(1);BEGIN FOR i IN 1..LENGTH(p_text) LOOP v_char := SUBSTR(p_text, i, 1); IF v_char BETWEEN 'A' AND 'Z' THEN v_rot := v_rot || CHR(MOD(ASCII(v_char) - c_upper_a + 13, 26) + c_upper_a); ELSIF v_char BETWEEN 'a' AND 'z' THEN v_rot := v_rot || CHR(MOD(ASCII(v_char) - c_lower_a + 13, 26) + c_lower_a); ELSE v_rot := v_rot || v_char; END IF; END LOOP; RETURN v_rot;END;/
SELECT fn_rot13_native('Hello ROT-13') FROM DUAL;SELECT fn_rot13_clob('Hello ROT-13') FROM DUAL;SELECT fn_rot13_algorithm('Hello ROT-13') FROM DUAL;-- All return:-- Uryyb EBG-13
In Pop11 characters are just integers, so we can use integercomparisons and arithmetic (assuming ASCII based encoding).
define rot13(s); lvars j, c; for j from 1 to length(s) do s(j) -> c; if `A` <= c and c <= `M` or `a` <= c and c <= `m` then c + 13 -> s(j); elseif `N` <= c and c <= `Z` or `n` <= c and c <= `z` then c - 13 -> s(j); endif; endfor; s;enddefine;rot13('NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm') =>
/r13 {4 dict begin /rotc { { {{{64 gt} {91 lt}} all?} {65 - 13 + 26 mod 65 +} is? {{{95 gt} {123 lt}} all?} {97 - 13 + 26 mod 97 +} is? } cond }. {rotc} map cvstrend}.
#COMPILE EXE#COMPILER PBWIN 9.05#DIM ALLFUNCTION ROT13(BYVAL a AS STRING) AS STRING LOCAL p AS BYTE PTR LOCAL n AS BYTE, e AS BYTE LOCAL res AS STRING res = a p = STRPTR(res) n = @p DO WHILE n SELECT CASE n CASE 65 TO 90 e = 90 n += 13 CASE 97 TO 122 e = 122 n += 13 CASE ELSE e = 255 END SELECT IF n > e THEN n -= 26 END IF @p = n INCR p n = @p LOOPFUNCTION = resEND FUNCTION'testing:FUNCTION PBMAIN () AS LONG#DEBUG PRINT ROT13("abc")#DEBUG PRINT ROT13("nop")END FUNCTION
$e = "This is a test Guvf vf n grfg"[char[]](0..64+78..90+65..77+91..96+110..122+97..109+123..255)[[char[]]$e] -join ""
A more POSH way..
function Invoke-Rot13 { param( [char[]]$message ) begin { $outString = New-Object System.Collections.ArrayList $alpha = 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' $alphaL = $alpha + $alpha $alphaU = $alphaL.toUpper() $int = 13 } process{ $message | ForEach-Object { # test if char is special if ($_ -match '[^\p{L}\p{Nd}]') { $outString += $_ } # test if char is digit elseif ($_ -match '\d') { $outString += $_ } # test if char is upperCase elseif ($_ -ceq $_.ToString().ToUpper()) { $charIndex = $alphaU.IndexOf($_.tostring()) $outString += $alphaU[$charIndex+$int] } # test if char is lowerCase elseif ($_ -ceq $_.ToString().ToLower()) { $charIndex = $alphaL.IndexOf($_.tostring()) $outString += $alphaL[$charIndex+$int] } else { $outString += $_ } } # end foreach } # end process end { # output string and join all chars $outString -join "" }} # end function
OutPut
PS> $message = '{!This is /A\ Test123}'PS> $messageE = Invoke-Rot13 -message $messagePS> $messageEPS> Invoke-Rot13 -message $messageE{!Guvf vf /N\ Grfg123}{!This is /A\ Test123}
Works with Quintus Prolog.
:- use_module(library(ctypes)).runtime_entry(start) :-prompt(_, ''),rot13.rot13 :-get0(Ch),( is_endfile(Ch) ->true; rot13_char(Ch, Rot), put(Rot), rot13).rot13_char(Ch, Rot) :-( is_alpha(Ch) ->to_upper(Ch, Up),Letter is Up - 0'A,Rot is Ch + ((Letter + 13) mod 26) - Letter; Rot = Ch).
Works with SWI-Prolog.
rot13(Str, SR) :-maplist(rot, Str, Str1),string_to_list(SR, Str1).rot(C, C1) :-( member(C, "abcdefghijklmABCDEFGHIJKLM") -> C1 is C+13; (member(C, "nopqrstuvwxyzNOPQRSTUVWXYZ") -> C1 is C-13; C1 = C)).
Output :
?- rot13("The Quick Brown Fox Jumped Over The Lazy Dog!", SR).SR = "Gur Dhvpx Oebja Sbk Whzcrq Bire Gur Ynml Qbt!".
Declare.s Rot13(text_to_code.s)If OpenConsole() Define txt$ Print("Enter a string to encode: "): txt$=Input() PrintN("Coded : "+Rot13(txt$)) PrintN("Decoded: "+Rot13(Rot13(txt$))) Print("Press ENTER to quit."): Input() CloseConsole()EndIfProcedure.s Rot13(s.s) Protected.i i Protected.s t, u For i=1 To Len(s) t=Mid(s,i,1) Select Asc(t) Case Asc("a") To Asc("m"), Asc("A") To Asc("M") t=chr(Asc(t)+13) Case Asc("n") To Asc("z"), Asc("N") To Asc("Z") t=chr(Asc(t)-13) EndSelect u+t Next ProcedureReturn uEndProcedure
Python 2.x (but not 3.x) has built-in rot13 encoding and decoding:
>>> u'foo'.encode('rot13')'sbb'>>> 'sbb'.decode('rot13')u'foo'
In both Python 2.x and 3.x one can use the standard library modulecodecs
for rot13 encoding and decoding:
>>> import codecs>>> codecs.encode("The quick brown fox jumps over the lazy dog", "rot13")'Gur dhvpx oebja sbk whzcf bire gur ynml qbt'>>> codecs.decode(_, "rot13")'The quick brown fox jumps over the lazy dog'
An alternative that doesn't rely on the built-in "rot13" codec:
#!/usr/bin/env pythonimport stringTRANSLATION_TABLE = str.maketrans( string.ascii_uppercase + string.ascii_lowercase, string.ascii_uppercase[13:] + string.ascii_uppercase[:13] + string.ascii_lowercase[13:] + string.ascii_lowercase[:13])def rot13(s): """Return the rot-13 encoding of s.""" return s.translate(TRANSLATION_TABLE)if __name__ == "__main__": """rot-13 encode the input files, or stdin if no files are provided.""" import fileinput for line in fileinput.input(): print(rot13(line), end="")
Thestr.translate() andstr.maketrans() functions make the function's definition almost trivial. Thefileinput module makes the wrapper functionality trivial to implement. This can be adapted for Python2.x by replacingstr.maketrans withstring.maketrans and using Python2 style print statement in place of the Python3 print function.
and
This one uses a dictionary comprehension to define the key forlowercase then another to updates with with uppercase mappings.It uses generator expression in a lambda as the encoding functionand the dictionary.get() (with default value) to preserve any non-lettercharacters during encoding. This lambda line can be used to generatean encoding function forany substitution cipher defined in the name"key."
#!/usr/bin/env pythonfrom __future__ import print_functionimport stringlets = string.ascii_lowercasekey = {x:y for (x,y) in zip(lets[13:]+lets[:14], lets)}key.update({x.upper():key[x].upper() for x in key.keys()})encode = lambda x: ''.join((key.get(c,c) for c in x))if __name__ == '__main__': """Peform line-by-line rot-13 encoding on any files listed on our command line or act as a standard UNIX filter (if no arguments specified). """ import fileinput for line in fileinput.input(): print(encode(line), end="")
CBTJD: 2020/03/14
By using the matching length inlist$ and outlist$ variables, any arbitrary replacement code can easily be implemented.
INPUT "Enter a string: ", a$PRINT rot13$(a$)FUNCTION rot13$ (stg$) inlist$ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" outlist$ = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm" FOR n = 1 TO LEN(stg$) letter$ = MID$(stg$, n, 1) letpos = INSTR(inlist$, letter$) IF letpos = 0 THEN rotated$ = letter$ ELSE rotated$ = MID$(outlist$, letpos, 1) END IF rot13$ = rot13$ + rotated$ NEXTEND FUNCTION
[ $ "" swap witheach [ dup char A char M 1+ within over char a char m 1+ within or iff [ 13 + ] else [ dup char N char Z 1+ within over char n char z 1+ within or if [ 13 - ] ] join ] ] is rot-13 ( $ --> $ )
Testing in Quackery shell.
/O> $ "five quacking zephyrs jolt my wax bed." carriage join... $ "VAMP FOX HELD QUARTZ DUCK JUST BY WING." join... dup echo$ cr cr... rot-13 dup echo$ cr cr... rot-13 echo$ cr... five quacking zephyrs jolt my wax bed.VAMP FOX HELD QUARTZ DUCK JUST BY WING.svir dhnpxvat mrculef wbyg zl jnk orq.INZC SBK URYQ DHNEGM QHPX WHFG OL JVAT.five quacking zephyrs jolt my wax bed.VAMP FOX HELD QUARTZ DUCK JUST BY WING.Stack empty.
rot13 <- function(x){ old <- paste(letters, LETTERS, collapse="", sep="") new <- paste(substr(old, 27, 52), substr(old, 1, 26), sep="") chartr(old, new, x)}x <- "The Quick Brown Fox Jumps Over The Lazy Dog!.,:;'#~[]{}"rot13(x) # "Gur Dhvpx Oebja Sbk Whzcf Bire Gur Ynml Qbt!.,:;'#~[]{}"x2 <- paste(letters, LETTERS, collapse="", sep="")rot13(x2) # "nNoOpPqQrRsStTuUvVwWxXyYzZaAbBcCdDeEfFgGhHiIjJkKlLmM"
For a slightly more general function, see theexample on the chartr help page.
#!/usr/bin/env racket#lang racket/base(define (run i o) (for ([ch (in-producer regexp-match #f #rx#"[a-zA-Z]" i 0 #f o)]) (define b (bytes-ref (car ch) 0)) (define a (if (< b 96) 65 97)) (write-byte (+ (modulo (+ 13 (- b a)) 26) a))))(require racket/cmdline)(command-line #:help-labels "(\"-\" specifies standard input)" #:args files (for ([f (if (null? files) '("-") files)]) (if (equal? f "-") (run (current-input-port) (current-output-port)) (call-with-input-file f (λ(i) (run i (current-output-port)))))))
(formerly Perl 6)
my @abc = 'a'..'z';my $abc = [@abc».uc, @abc];put .trans: $abc => $abc».rotate(13) for lines
Rosetta Code
Ebfrggn Pbqr
As a one-liner:
$ raku -pe '.=trans: {$_ => $_».rotate(13)}({[$_».uc, @$_]}("a".."z"))'
function ROT13 (InputTxt as string) as string dim i as integer, ascVal as byte Result = "" for i = 1 to len(InputTxt) ascVal = asc(InputTxt[i]) select case ascVal case 65 to 77, 97 to 109 Result = Result + chr$(ascVal + 13) case 78 to 90, 110 to 122 Result = Result + chr$(ascVal - 13) case else Result = Result + chr$(ascVal) end select nextend functionInput "Text to encode: "; a$Print ROT13(a$)Input "Press a key to end..."; a$
define rot13 use $str $str each chr dup m/[A-Ma-m]/ if ord 13 + chr else dup m/[N-Zn-z]/ if ord 13 - chr $str length list "" join"12!ABJURER nowhere" dup print "\nas rot13 is\n" print rot13 print "\n" print
12!ABJURER nowhereas rot13 is12!NOWHERE abjurer
REBOL [ Title: "Rot-13" URL: http://rosettacode.org/wiki/Rot-13]; Test data has upper and lower case characters as well as characters; that should not be transformed, like numbers, spaces and symbols.text: "This is a 28-character test!"print "Using cipher table:"; I build a set of correspondence lists here. 'x' is the letters from; A-Z, in both upper and lowercase form. Note that REBOL can iterate; directly over the alphabetic character sequence in the for loop. 'y'; is the cipher form, 'x' rotated by 26 characters (remember, I have; the lower and uppercase forms together). 'r' holds the final result,; built as I iterate across the 'text' string. I search for the; current character in the plaintext list ('x'), if I find it, I get; the corresponding character from the ciphertext list; ('y'). Otherwise, I pass the character through untransformed, then; return the final string.rot-13: func ["Encrypt or decrypt rot-13 with tables."text [string!] "Text to en/decrypt."/local x y r i c] [x: copy "" for i #"a" #"z" 1 [append x rejoin [i uppercase i]]y: rejoin [copy skip x 26 copy/part x 26]r: copy ""repeat i text [append r either c: find/case x i [y/(index? c)][i]]r]; Note that I am setting the 'text' variable to the result of rot-13; so I can reuse it again on the next call. The rot-13 algorithm is; reversible, so I can just run it again without modification to decrypt.print [" Encrypted:" text: rot-13 text]print [" Decrypted:" text: rot-13 text] print "Using parse:"clamp: func ["Contain a value within two enclosing values. Wraps if necessary."x v y][x: to-integer x v: to-integer v y: to-integer ycase [v < x [y - v] v > y [v - y + x - 1] true v]]; I'm using REBOL's 'parse' word here. I set up character sets for; upper and lower-case letters, then let parse walk across the; text. It looks for matches to upper-case letters, then lower-case,; then skips to the next one if it can't find either. If a matching; character is found, it's mathematically incremented by 13 and; clamped to the appropriate character range. parse changes the; character in place in the string, hence this is a destructive; operation.rot-13: func ["Encrypt or decrypt rot-13 with parse."text [string!] "Text to en/decrypt. Note: Destructive!"] [u: charset [#"A" - #"Z"]l: charset [#"a" - #"z"]parse text [some [i: ; Current position.u (i/1: to-char clamp #"A" i/1 + 13 #"Z") | ; Upper case.l (i/1: to-char clamp #"a" i/1 + 13 #"z") | ; Lower case.skip]] ; Ignore others.text]; As you see, I don't need to re-assign 'text' anymore.print [" Encrypted:" rot-13 text]print [" Decrypted:" rot-13 text]
Output:
Using cipher table: Encrypted: Guvf vf n 28-punenpgre grfg! Decrypted: This is a 28-character test!Using parse: Encrypted: Guvf vf n 28-punenpgre grfg! Decrypted: This is a 28-character test!
{{ : rotate ( cb-c ) tuck - 13 + 26 mod + ; : rotate? ( c-c ) dup 'a 'z within [ 'a rotate ] ifTrue dup 'A 'Z within [ 'A rotate ] ifTrue ;---reveal--- : rot13 ( s-s ) dup [ [ @ rotate? ] sip ! ] ^types'STRING each@ ;}}"abcdef123GHIJKL" rot13 dup puts cr rot13 puts"abjurer NOWHERE" rot13 puts
This REXX version supports upper and lower case letters, preserves their case (upper/lower),
and passes through (without alteration) all non-alphabetic input characters.
/*REXX program encodes several example text strings using the ROT-13 algorithm. */$='foo' ; say "simple text=" $; say 'rot-13 text=' rot13($); say$='bar' ; say "simple text=" $; say 'rot-13 text=' rot13($); say$="Noyr jnf V, 'rer V fnj Ryon."; say "simple text=" $; say 'rot-13 text=' rot13($); say$='abc? ABC!' ; say "simple text=" $; say 'rot-13 text=' rot13($); say$='abjurer NOWHERE' ; say "simple text=" $; say 'rot-13 text=' rot13($); sayexit /*stick a fork in it, we're all done. *//*──────────────────────────────────────────────────────────────────────────────────────*/rot13: return translate( arg(1), 'abcdefghijklmABCDEFGHIJKLMnopqrstuvwxyzNOPQRSTUVWXYZ',, "nopqrstuvwxyzNOPQRSTUVWXYZabcdefghijklmABCDEFGHIJKLM")
output
simple text = foorot-13 text = sbbsimple text = barrot-13 text = onesimple text = Noyr jnf V, 'rer V fnj Ryon.rot-13 text = Able was I, 'ere I saw Elba.simple text = abc? ABC!rot-13 text = nop? NOP!simple text = abjurer NOWHERErot-13 text = nowhere ABJURER
see "enter a string : " give sans = ""for a = 1 to len(s) letter = substr(s, a, 1) if letter >= "a" and letter <= "z" char = char(ascii(letter) + 13) if char > "z" char = chr(asc(char) - 26) ok else if letter >= "a" and letter <= "z" char = char(ascii(letter) + 13) ok if char > "z" char = char(ascii(char) - 26) else char = letter ok ok ans = ans + charnextsee ans + nl
≪ "" 1 3 PICK SIZEFOR j OVER j DUP SUBIF DUP "A" ≥ OVER "Z" ≤ ANDTHEN NUM 78 - 26 MOD 65 + CHRENDIF DUP "a" ≥ OVER "z" ≤ ANDTHEN NUM 110 - 26 MOD 97 + CHREND +NEXT SWAP DROP≫ 'ROT13' STO
"abjurer NOWHERE"ROT13
1: "nowhere ABJURER"
# Returns a copy of _s_ with rot13 encoding.def rot13(s) s.tr('A-Za-z', 'N-ZA-Mn-za-m')end# Perform rot13 on files from command line, or standard input.while line = ARGF.gets print rot13(line)end
One can runruby rot13.rb file1 file2
to rot13 those files, or runruby rot13.rb
to rot13 the standard input.
Input:
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
Output:
NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm
INPUT "Enter a string: "; s$ans$ = ""FOR a = 1 TO LEN(s$) letter$ = MID$(s$, a, 1) IF letter$ >= "A" AND letter$ <= "Z" THEN char$ = CHR$(ASC(letter$) + 13) IF char$ > "Z" THEN char$ = CHR$(ASC(char$) - 26) else if letter$ >= "a" AND letter$ <= "z" THEN char$ = CHR$(ASC(letter$) + 13) IF char$ > "z" THEN char$ = CHR$(ASC(char$) - 26) ELSE char$ = letter$ END IF ans$ = ans$ + char$NEXT aPRINT ans$
Output:
Enter a string: ?abcnopEnter a string: ?ABC NOP
fn rot13(string: &str) -> String { string.chars().map(|c| { match c { 'a'..='m' | 'A'..='M' => ((c as u8) + 13) as char, 'n'..='z' | 'N'..='Z' => ((c as u8) - 13) as char, _ => c } }).collect()}fn main () { assert_eq!(rot13("abc"), "nop");}
comment Return the rot13 transformation of s, preserving case and passing non-alphabetic characters without changeendfunction rot13(s = string) = string var i, k = integer var ch = char var normal, rotated = string normal = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" rotated = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm" for i = 1 to len(s) ch = mid(s,i,1) k = instr(1,normal,ch) if k <> 0 then ch = mid(rotated,k,1) mid(s,i,1) = ch next iend = srem - exercise the functionvar plain, encoded = stringplain = "The quick brown fox jumps over the lazy red dog."encoded = rot13(plain)print "Plain text: "; plainprint "Encoded : "; encodedprint "Decoded : "; rot13(encoded)end
Plain text: The quick brown fox jumps over the lazy red dog.Encoded : Gur dhvpx oebja sbk whzcf bire gur ynml erq qbt.Decoded : The quick brown fox jumps over the lazy red dog.
Rather than use a lookup table, we can assume the ASCII character set and rely on simple arithmetic for the transformation. In S-BASIC, char is synonymous with byte, allowing us to perform addition and subtraction directly on characters as though they were numbers, and eliminating the necessity of coding, for example, ch = chr(asc(ch) + 13) as required by many BASIC dialects.
comment Return the rot13 transformation of s, preserving case and passing non-alphabetic characters unchanged.endfunction rot13(s = string) = string var i = integer var ch = char for i=1 to len(s) ch = mid(s,i,1) if (ch >= 'a' and ch <= 'm') or (ch >= 'A' and ch <= 'M') then ch = ch + 13 else if (ch >= 'n' and ch <= 'z') or (ch >= 'N' and ch <= 'Z') then ch = ch - 13 mid(s,i,1) = ch next iend = srem - exercise the routinevar plain, rotated = stringplain = "The quick brown fox jumps over the lazy red dog."rotated = rot13(plain)print "Plain text: "; plainprint "Rotated : "; rotatedprint "Restored : "; rot13(rotated)end
Plain text: The quick brown fox jumps over the lazy red dog.Rotated : Gur dhvpx oebja sbk whzcf bire gur ynml erq qbt.Restored : The quick brown fox jumps over the lazy red dog.
Still a third approach makes use of S-BASIC's awkward (and poorly documented) XLATE function, which transforms each character in the input string by using its ASCII value as an index into the translation string.
function rot13(s = string) = string var tr = string:127 rem - set up translation table tr = space$(31) + " !" + chr(34) + "#$%&'()*+,-./0123456789" + \ ":;<=>?@NOPQRSTUVWXYZABCDEFGHIJKLM[\]^_`" + \ "nopqrstuvwxyzabcdefghijklm{|}~"end = xlate(s,tr)rem - test the functionvar plain, encrypted = stringplain = "The quick brown fox jumps over the lazy dog."print "Plain text: "; plainencrypted = rot13(plain)print "Encrypted : "; encryptedprint "Restored : "; rot13(encrypted) end
Seems to work even with UTF-8 text.
variable old = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";variable new = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm";define rot13(s) { s = strtrans(s, old, new); return s;}define rot13_stream(s) { variable ln; while (-1 != fgets(&ln, s)) fputs(rot13(ln), stdout);}if (__argc > 1) { variable arg, fp; foreach arg (__argv[[1:]]) { fp = fopen(arg, "r"); rot13_stream(fp); }}else rot13_stream(stdin);
scala> def rot13(s: String) = s map { | case c if 'a' <= c.toLower && c.toLower <= 'm' => c + 13 toChar | case c if 'n' <= c.toLower && c.toLower <= 'z' => c - 13 toChar | case c => c | }rot13: (s: String)Stringscala> rot13("7 Cities of Gold.")res61: String = 7 Pvgvrf bs Tbyq.scala> rot13(res61)res62: String = 7 Cities of Gold.
(define (rot13 str) (define (rot13-char c) (integer->char (+ (char->integer c) (cond ((and (char>=? c #\a) (char<? c #\n)) 13) ((and (char>=? c #\A) (char<? c #\N)) 13) ((and (char>=? c #\n) (char<=? c #\z)) -13) ((and (char>=? c #\N) (char<=? c #\Z)) -13) (else 0))))) (list->string (map rot13-char (string->list str))))
An alternative version with the following modification:
;; Works with: chibi, csi, gosh, gsi, guile(cond-expand (r7rs (import (scheme base) (scheme write))) (gambit) (chicken (import (r7rs))))(define char-rot13 (let* ((A (char->integer #\A)) (N (char->integer #\N)) (Z (char->integer #\Z)) (a (char->integer #\a)) (n (char->integer #\n)) (z (char->integer #\z)) (inc 13) (dec (- inc)) (rot (lambda (c direction) (integer->char (+ c direction))))) (lambda (ch) (let ((c (char->integer ch))) (if (>= c A) (if (< c N) (rot c inc) (if (<= c Z) (rot c dec) (if (>= c a) (if (< c n) (rot c inc) (if (<= c z) (rot c dec) ch))))))))))(define (string-rot13 str) (string-map char-rot13 str))(if (not (and (string=? (string-rot13 "abcdefghijklmnopqrstuvwxyz") "nopqrstuvwxyzabcdefghijklm") (string=? (string-rot13 "ABCDEFGHIJKLMNOPQRSTUVWXYZ") "NOPQRSTUVWXYZABCDEFGHIJKLM"))) (error "Test failed."))(let loop ((line (read-line))) (if (string? line) (begin (display (string-rot13 line)) (newline) (loop (read-line)))))
The two translations (upper and lower case) are separate only for documentation and ease of understanding; they could be combined into one command.
y/abcdefghijklmnopqrstuvwxyz/nopqrstuvwxyzabcdefghijklm/y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/NOPQRSTUVWXYZABCDEFGHIJKLM/
This rot13 program reads from standard input and writes to standard output:
$ include "seed7_05.s7i";const proc: main is func local var char: ch is ' '; begin ch := getc(IN); while not eof(IN) do if (ch >= 'a' and ch <= 'm') or (ch >= 'A' and ch <= 'M') then ch := chr(ord(ch) + 13); elsif (ch >= 'n' and ch <= 'z') or (ch >= 'N' and ch <= 'Z') then ch := chr(ord(ch) - 13); end if; write(ch); ch := getc(IN); end while; end func;
# Returns a copy of 's' with rot13 encoding.func rot13(s) { s.tr('A-Za-z', 'N-ZA-Mn-za-m')}# Perform rot13 on standard input.STDIN.each { |line| say rot13(line) }
TEXT PROCEDURE ROT13(INP); TEXT INP; BEGIN CHARACTER PROCEDURE ROT13CHAR(C); CHARACTER C; ROT13CHAR := CHAR( RANK(C) + (IF C >= 'A' AND C <= 'M' THEN 13 ELSE IF C >= 'a' AND C <= 'm' THEN 13 ELSE IF C >= 'N' AND C <= 'Z' THEN -13 ELSE IF C >= 'n' AND C <= 'z' THEN -13 ELSE 0)); TEXT OUTP; OUTP :- BLANKS(INP.LENGTH); INP.SETPOS(1); WHILE INP.MORE DO OUTP.PUTCHAR(ROT13CHAR(INP.GETCHAR)); ROT13 :- OUTP; END ROT13;
A shell script:
#!/usr/local/bin/slatech@(String Character traits) rot13[| value | upper ::= ch isUppercase. value := ch toLowercase as: Integer. (value >= 97) /\ [value < 110] ifTrue: [value += 13] ifFalse: [(value > 109) /\ [value <= 122] ifTrue: [value -= 13]]. upper ifTrue: [(value as: String Character) toUppercase] ifFalse: [value as: String Character]].lobby define: #Rot13Encoder &parents: {Encoder}.c@(Rot13Encoder traits) convert[ [c in isAtEnd] whileFalse: [c out nextPut: c in next rot13].].(Rot13Encoder newFrom: Console reader to: Console writer) convert.
Normal functions:
ch@(String Character traits) rot13[| value | upper ::= ch isUppercase. value := ch toLowercase as: Integer. (value >= 97) /\ [value < 110] ifTrue: [value += 13] ifFalse: [(value > 109) /\ [value <= 122] ifTrue: [value -= 13]]. upper ifTrue: [(value as: String Character) toUppercase] ifFalse: [value as: String Character]].s@(String traits) rot13[ result ::= s newSameSize. s doWithIndex: [| :each :index | result at: index put: each rot13]. result].slate[37]> 'abc123' rot13.'nop123'
(define rot-char-13 (lambda (ch) (set! ch (string->rune ch)) (cond ( (or (and (>= ch (string->rune "a")) (<= ch (string->rune "m"))) (and (>= ch (string->rune "A")) (<= ch (string->rune "M")))) (rune->string (+ ch 13))) ( (or (and (>= ch (string->rune "n")) (<= ch (string->rune "z"))) (and (>= ch (string->rune "N")) (<= ch (string->rune "Z")))) (rune->string (- ch 13))) (else (rune->string ch)))))(display (list->string (map rot-char-13 (string->list "nowhere->ABJURER!"))))
abjurer->NOWHERE!
Here we implemented three ways. The first one is the simplest. The second demonstrates extending the String class with a genericrot
method, which in turn uses twonew method for the class Character (+ and -). The third one is an imitation of thetr '[a-m][n-z]' '[n-z][a-m]' approach (see UNIX Shell example), done through a block closure and using also the new methodtrFrom:to:
for Character.
"1. simple approach"rot13 := [ :string | string collect: [ :each | | index | index := 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' indexOf: each ifAbsent: [ 0 ]. "Smalltalk uses 1-based indexing" index isZero ifTrue: [ each ] ifFalse: [ 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM' at: index ] ] ].(rot13 value: 'Test123') printNl "gives 'Grfg123'""2. extending built-in classes"Character extend [ + inc [ (inc isKindOf: Character) ifTrue: [ ^ ( Character value: ((self asInteger) + (inc asInteger)) ) ] ifFalse: [ ^ ( Character value: ((self asInteger) + inc) ) ] ] - inc [ ^ ( self + (inc asInteger negated) ) ] trFrom: map1 to: map2 [ (map1 includes: self) ifTrue: [ ^ map2 at: (map1 indexOf: self) ] ifFalse: [ ^self ] ]].String extend [ rot: num [ |s| s := String new. self do: [ :c | ((c asLowercase) between: $a and: $z) ifTrue: [ |c1| c1 := ( $a + ((((c asLowercase) - $a + num) asInteger) rem:26)). (c isLowercase) ifFalse: [ c1 := c1 asUppercase ]. s := s, (c1 asString) ] ifFalse: [ s := s, (c asString) ] ]. ^s ]].('abcdefghijklmnopqrstuvwxyz123!' rot: 13) displayNl.(('abcdefghijklmnopqrstuvwxyz123!' rot: 13) rot: 13) displayNl."2. using a 'translation'. Not very idiomatic Smalltalk code"rotThirteen := [ :s | |m1 m2 r| r := String new. m1 := OrderedCollection new. 0 to: 25 do: [ :i | m1 add: ($a + i) ]. m2 := OrderedCollection new. 0 to: 25 do: [ :i | m2 add: ($a + ((i+13) rem: 26)) ]. s do: [ :c | (c between: $a and: $z) | (c between: $A and: $Z) ifTrue: [ | a | a := (c asLowercase) trFrom: m1 to: m2. (c isUppercase) ifTrue: [ a := a asUppercase ]. r := r, (a asString)] ifFalse: [ r := r, (c asString) ] ]. r].(rotThirteen value: 'abcdefghijklmnopqrstuvwxyz123!') displayNl.
* # Function using replace( ) define('rot13(s)u1,u2,l1,l2') :(rot13_end)rot13 &ucase len(13) . u1 rem . u2 &lcase len(13) . l1 rem . l2 rot13 = replace(s,&ucase &lcase,u2 u1 l2 l1) :(return)rot13_end* # Function using pattern define('rot13s(s)c') alfa = &ucase &ucase &lcase &lcase :(rot13s_end)rot13s s len(1) . c = :f(return) alfa break(c) len(13) len(1) . c rot13s = rot13s c :(rot13s)rot13s_end* # Test and display both str = rot13("I abjure the $19.99 trinket!") output = str; output = rot13(str) str = rot13s("He's a real Nowhere Man.") output = str; output = rot13s(str)end
Output:
V nowher gur $19.99 gevaxrg!I abjure the $19.99 trinket!Ur'f n erny Abjurer Zna.He's a real Nowhere Man.
As a structured script.
#!/usr/local/bin/sparpragma annotate( summary, "rot13" );pragma annotate( description, "Implement a 'rot-13' function (or procedure, class," );pragma annotate( description, "subroutine, or other 'callable' object as appropriate" );pragma annotate( description, "to your programming environment). The definition of the" );pragma annotate( description, "rot-13 function is to simply replace every letter of the" );pragma annotate( description, "ASCII alphabet with the letter which is 'rotated' 13" );pragma annotate( description, "characters 'around' the 26 letter alphabet from its" );pragma annotate( description, "normal cardinal position (wrapping around from 'z' to" );pragma annotate( description, "'a' as necessary). Thus the letters 'abc' become 'nop'" );pragma annotate( description, "and so on. Technically rot-13 is a 'monoalphabetic" );pragma annotate( description, "substitution cipher' with a trivial 'key'. A proper" );pragma annotate( description, "implementation should work on upper and lower case" );pragma annotate( description, "letters, preserve case, and pass all non-alphabetic" );pragma annotate( description, "characters in the input stream through without" );pragma annotate( description, "alteration." );pragma annotate( see_also, "http://rosettacode.org/wiki/Rot-13" );pragma annotate( author, "Ken O. Burtch" );pragma license( unrestricted );pragma restriction( no_external_commands );procedure rot13 is function to_rot13( s : string ) return string is ch : character; result : string; begin for i in 1..strings.length( s ) loop ch := strings.element( s, i ); if strings.is_letter( ch ) then if (ch in 'A'..'M') or (ch in 'a'..'m' ) then ch := strings.val( numerics.pos( ch ) + 13 ); else ch := strings.val( numerics.pos( ch ) - 13 ); end if; end if; result := @ & ch; end loop; return result; end to_rot13;begin ? to_rot13( "Big fjords vex quick waltz nymph!" );end rot13;
select translate( 'The quick brown fox jumps over the lazy dog.', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm' ) from dual;
with cte(num) as ( select 1 union all select num+1 from cte)select cast((select char(ascii(chr) +case when ascii(chr) between ascii('a') and ascii('m') orascii(chr) between ascii('A') and ascii('M') then 13when ascii(chr) between ascii('n') and ascii('z') orascii(chr) between ascii('N') and ascii('Z') then -13else 0end)from(select top(1000) num, -- your string to be converted to ROT13 substring('The Quick Brown Fox Jumps Over The Lazy Dog',num,1) chrfrom cte) tmpFor XML PATH ('')) as xml).value('.', 'VARCHAR(max)') rot13option (maxrecursion 0)
function rot13(s) {u = ascii(s)i = selectindex(u:>64 :& u:<91)if (length(i)>0) u[i] = mod(u[i]:-52, 26):+65i = selectindex(u:>96 :& u:<123)if (length(i)>0) u[i] = mod(u[i]:-84, 26):+97return(char(u))}rot13("Shall Not Perish") Funyy Abg Crevfu
a "The quick brown fox jumps over the lazy dog."b "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"c b#@c 78#\c 52#ab %.a d " " bb %.a #d .ab %.a e cb %.a #e #db %.a a .\e :af f .aa :a#a$ f
Gur dhvpx oebja sbk whzcf bire gur ynml qbt.
func rot13char(c: UnicodeScalar) -> UnicodeScalar { switch c { case "A"..."M", "a"..."m": return UnicodeScalar(UInt32(c) + 13) case "N"..."Z", "n"..."z": return UnicodeScalar(UInt32(c) - 13) default: return c }}func rot13(str: String) -> String { return String(map(str.unicodeScalars){ c in Character(rot13char(c)) })}println(rot13("The quick brown fox jumps over the lazy dog"))
Gur dhvpx oebja sbk whzcf bire gur ynml qbt
using string map:
proc rot13 line { string map { a n b o c p d q e r f s g t h u i v j w k x l y m z n a o b p c q d r e s f t g u h v i w j x k y l z m A N B O C P D Q E R F S G T H U I V J W K X L Y M Z N A O B P C Q D R E S F T G U H V I W J X K Y L Z M } $line}set tx "Hello, World !"puts "$tx : [rot13 $tx]"
Hello, World ! : Uryyb, Jbeyq !
using translit:
package require Tclxproc rot13 str { translit "A-Za-z" "N-ZA-Mn-za-m" $str}
Calculator symbol translations:
"STO" arrow: →
Perfoms ROT-13 on the contents of Str1. Also uses the string variables Str0 and Str2 and the real variable N.
:"ABCDEFGHIJKLMNOPQRSTUVWXYZ→Str0:".→Str2:For(N,1,length(Str1:If inString(Str0,sub(Str1,N,1:Then:inString(Str0,sub(Str1,N,1:Ans+13-26(Ans>13:Str2+sub(Str0,Ans,1→Str2:Else:Str2+sub(Str1,N,1→Str2:End:End:sub(Str2,2,length(Str2)-1→Str1
--Ipquarx 8:45 PM
function rot13(%string){%alph = "abcdefghijklmnopqrstuvwxyz";%len = strLen(%string);for(%a = 0; %a < %len; %a++){%char = getSubStr(%string,%a,1);%pos = striPos(%alph, %char);if(%pos < 0)%out = %out @ %char;else{if(strPos(%alph, %char) < 0)%out = %out @ strUpr(getSubStr(%alph, (%pos + 13) % 26));else%out = %out @ getSubStr(%alph, (%pos + 13) % 26);}}return %out;}
Via definition and subsequent use of a named filter.
@(deffilter rot13 ("a" "n") ("b" "o") ("c" "p") ("d" "q") ("e" "r") ("f" "s") ("g" "t") ("h" "u") ("i" "v") ("j" "w") ("k" "x") ("l" "y") ("m" "z") ("n" "a") ("o" "b") ("p" "c") ("q" "d") ("r" "e") ("s" "f") ("t" "g") ("u" "h") ("v" "i") ("w" "j") ("x" "k") ("y" "l") ("z" "m") ("A" "N") ("B" "O") ("C" "P") ("D" "Q") ("E" "R") ("F" "S") ("G" "T") ("H" "U") ("I" "V") ("J" "W") ("K" "X") ("L" "Y") ("M" "Z") ("N" "A") ("O" "B") ("P" "C") ("Q" "D") ("R" "E") ("S" "F") ("T" "G") ("U" "H") ("V" "I") ("W" "J") ("X" "K") ("Y" "L") ("Z" "M"))@(repeat)@line@ (output :filter rot13)@line@ (end)@(end)
Via TXR Lisp:
(defun rot13 (ch) (cond ((<= #\A ch #\Z) (wrap #\A #\Z (+ ch 13))) ((<= #\a ch #\z) (wrap #\a #\z (+ ch 13))) (t ch))) (whilet ((ch (get-char))) (put-char (rot13 ch)))
Rot ← +@A◿26+13-@A&p ⍥(¯∵(⍥Rot=1±.))2 &sc
Hello world!
:Uryyb jbeyq!
UNIX shell assumes availability of the standard UNIX utility commands (in the "coreutils" package on Linux systems, for example); thus thetr (translate) command is trivially provided with the proper arguments to perform the rotations.
Built from six rotonyms.
tr \'NOWHERE AZ clerk IRAQ faber gnat ABJURER NM pyrex VEND snore tang'\'abjurer nm PYREX vend SNORE TANG nowhere az CLERK iraq FABER GNAT' \'ABJURER NM pyrex VEND snore tang NOWHERE AZ clerk IRAQ faber gnat'\'nowhere az CLERK iraq FABER GNAT abjurer nm PYREX vend SNORE TANG'
#!/bin/shrot13() { tr '[a-m][n-z][A-M][N-Z]' '[n-z][a-m][N-Z][A-M]'}cat ${1+"$@"} | rot13
A simpletr a-zA-Z n-za-mN-ZA-M
would work with modern systems that followPOSIX. Ourtr '[a-m][n-z][A-M][N-Z]' '[n-z][a-m][N-Z][A-M]'
also works with those older System V systems. For newer systems, it translates '[' and ']' to themselves. (Refer toOpenBSD tr(1) manual page, section STANDARDS.)
This example shows proper quoting around "$@" (magical argument list) such that this script work properly even if some of the files named on the command line contain embedded spaces or other such characters. (The ${1+"$@"} check, unnecessary in modern systems, allows the script to work even on older systems where a bare "$@" expanded to a single empty string when no arguments were supplied).
``ci`d``@i`c``s`d```?aic.n``s`d```?bic.o``s`d```?cic.p``s`d```?dic.q``s`d```?eic.r``s`d```?fic.s``s`d```?gic.t``s`d```?hic.u``s`d```?iic.v``s`d```?jic.w``s`d```?kic.x``s`d```?lic.y``s`d```?mic.z``s`d```?nic.a``s`d```?oic.b``s`d```?pic.c``s`d```?qic.d``s`d```?ric.e``s`d```?sic.f``s`d```?tic.g``s`d```?uic.h``s`d```?vic.i``s`d```?wic.j``s`d```?xic.k``s`d```?yic.l``s`d```?zic.m``s`d```?Nic.A``s`d```?Oic.B``s`d```?Pic.C``s`d```?Qic.D``s`d```?Ric.E``s`d```?Sic.F``s`d```?Tic.G``s`d```?Uic.H``s`d```?Vic.I``s`d```?Wic.J``s`d```?Xic.K``s`d```?Yic.L``s`d```?Zic.M``s`d```?Aic.N``s`d```?Bic.O``s`d```?Cic.P``s`d```?Dic.Q``s`d```?Eic.R``s`d```?Fic.S``s`d```?Gic.T``s`d```?Hic.U``s`d```?Iic.V``s`d```?Jic.W``s`d```?Kic.X``s`d```?Lic.Y``s`d```?Mic.Z`d`|c
I/O in Ursala is meant to be handled automatically as much as possible by the run time system.This source text describes only a function that operates on the contents of a list of files passedto it as an argument, with the transformed files returned as a result. The #executable compilerdirective and its parameters mean that this source will be compiled to an executable filewith the required command line interface. The rot13 encryption algorithm itself is a simplefinite map implemented in a half line of code.
#import std#executable (<'parameterized','default-to-stdin'>,<>)rot = ~command.files; * contents:= ~contents; * * -:~& -- ^p(~&,rep13~&zyC)~~ ~=`A-~ letters
( in-place rot13, null terminated string )@rot13 ( addr* -: addr* ) DUP2 &loop LDAk ?{ POP2 JMP2r } STH2k LDAk #df AND DUP #41 LTH SWP #5a GTH ORA STH LDAk STHr ?{ DUP #df AND #0d ADD DUP #5a GTH #1a MUL SUB SWP #20 AND ORA } STH2r STA INC2 !&loop
string rot13(string s) { const string lcalph = "abcdefghijklmnopqrstuvwxyz"; const string ucalph = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string result = ""; int pos; unichar c; for (int i = 0; s.get_next_char (ref i, out c);) { if ((pos = lcalph.index_of_char(c)) != -1) result += lcalph[(pos + 13) % 26].to_string(); else if ((pos = ucalph.index_of_char(c)) != -1) result += ucalph[(pos + 13) % 26].to_string(); else result += c.to_string(); } return result;}void main() { print(rot13("The Quick Brown Fox Jumped Over the Lazy Dog!"));}
Gur Dhvpx Oebja Sbk Whzcrq Bire gur Ynml Qbt!
Using ROT13.TBL fromhere
Translate_Load("ROT13.TBL")Translate_Block(0, File_Size)
You can execute the macro from DOS command prompt with the following command:
vpw -q -x rot13.vdm inputfile -a outputfile
In addition to translating a block of text, the translate table allows viewing and editing ROT-13 text without translating the actual file into ASCII.The displayed characters and keyboard input are translated on-the-fly.This is the normal way to edit for example DOS/OEM and EBCDIC files.
Function ROT13(ByVal a As String) As String Dim i As Long Dim n As Integer, e As Integer ROT13 = a For i = 1 To Len(a) n = Asc(Mid$(a, i, 1)) Select Case n Case 65 To 90 e = 90 n = n + 13 Case 97 To 122 e = 122 n = n + 13 Case Else e = 255 End Select If n > e Then n = n - 26 End If Mid$(ROT13, i, 1) = Chr$(n) Next iEnd Function
Testing:
Sub Main() Debug.Assert ROT13("abc") = "nop" Debug.Assert ROT13("nop") = "abc"End Sub
Platform:.NET
Module Module1 Private Function rot13(ByVal str As String) As String Dim newChars As Char(), i, j As Integer, original, replacement As String original = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" replacement = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm" newChars = str.ToCharArray() For i = 0 To newChars.Length - 1 For j = 0 To 51 If newChars(i) = original(j) Then newChars(i) = replacement(j) Exit For End If Next Next Return New String(newChars) End FunctionEnd Module
This solution just uses simple textual substitution, since the number of characters involved is small. If the cipher involved more characters, it would be better to use character arithmetic; however, this is not encouraged in VB.Net.
option explicit function rot13(a) dim b,n1,n,i b="" for i=1 to len(a) n=asc(mid(a,i,1)) if n>=65 and n<= 91 then n1=(((n-65)+13)mod 26)+65 elseif n>=97 and n<= 123 then n1=(((n-97)+13)mod 26)+97 else n1=n end if b=b & chr(n1) next rot13=bend functionconst a="The quick brown fox jumps over the lazy dog."dim b,cwscript.echo a b=rot13(a)wscript.echo b c=rot13(b)wscript.echo c
The quick brown fox jumps over the lazy dog.Gur dhvpx oebja sbk whzcf bire gur ynml qbt.The quick brown fox jumps over the lazy dog.
fn main() {println(rot13('nowhere ABJURER'))println(rot13('abjurer NOWHERE'))}fn rot13char(chr u8) u8 {if (chr >= u8(97) && chr <= u8(109)) || (chr >= u8(65) && chr <= u8(77)) {return chr + 13} if (chr >= u8(110) && chr <= u8(122)) || (chr >= u8(78) && chr <= u8(90)) {return chr - 13}return chr}fn rot13(str string) string {mut chr_arr := []u8{}for elem in str.split('') {chr_arr << rot13char(elem.str) }return chr_arr.bytestr()}
abjurer NOWHEREnowhere ABJURER
def (rot13 s) (as string (map rot13 (as list s)))Alphabet <- "abcdefghijklmnopqrstuvwxyz"def (rot13 c) :case (and string?.c len.c=1) if ("a" <= c <= "z") let idx (pos c Alphabet) Alphabet (idx+13 % 26) ("A" <= c <= "Z") (downcase.c -> rot13 -> upcase) :else c
Output:
(rot13 "Moron")=> "Zbeba"
1 2#read()-N(2);2 2;3 defer(1 || N(2) > 90 || N(2) < 65) 5#65-N(5);4 defer(1 || N(2) > 122 || N(2) < 97) 5#97-N(5);5 5;6 defer(3 && 4) put(U(((N(2) - N(5) + 13) % 26) + N(5)));7 defer(1 || N(2) > 64 || N(2) == 0) put(U(N(2)));8 again(8) defer(6 && 7) 1,-6#N(6)-1,-7#N(7)-1,-3#N(3)-1,-4#N(4)-1;9 defer(1 || N(2) != 0) -3,-4,-5#N(5),-6,-7,-8;10 defer(1 || 9) put("\n");
To exit, type the character '`'
var rot13 = Fn.new { |s| var bytes = s.bytes.toList for (i in 0...bytes.count) { var c = bytes[i] if ((c >= 65 && c <= 77) || (c >= 97 && c <= 109)) { bytes[i] = c + 13 } else if ((c >= 78 && c <= 90) || (c >= 110 && c <= 122)) { bytes[i] = c - 13 } } return bytes.map { |b| String.fromByte(b) }.join()}System.print(rot13.call("nowhere ABJURER"))
abjurer NOWHERE
Using Linux/FASM.
format ELF executable 3entry startsegmentreadable writeablebufrb1segmentreadable executablestart:moveax, 3; syscall "read"movebx, 0; stdinmovecx, buf; buffer for read bytemovedx, 1; len (read one byte)int80hcmpeax, 0; EOF?jzexitxor eax, eax; load read char to eaxmoval, [buf]cmpeax, "A"; see if it is in ascii a-z or A-Zjlprintcmpeax, "z"jgprintcmpeax, "Z"jlerotupcmpeax, "a"jgerotlowjmpprintrotup:subeax, "A"-13; do rot 13 for A-Zcdqmovebx, 26divebxaddedx, "A"jmprotendrotlow:subeax, "a"-13; do rot 13 for a-zcdqmovebx, 26divebxaddedx, "a"rotend:mov[buf], dlprint: moveax, 4; syscall writemovebx, 1; stdoutmovecx, buf; *charmovedx, 1; string lengthint80hjmpstartexit: mov eax,1; syscall exitxor ebx,ebx; exit codeint 80h
Might still have a few problems.
global _startsection .text%define bsize 24%define fd(w) qword[filedescriptor + w * 8]%define sv(w) qword[rsp + w * 8]_start: mov fd(0), -1 mov fd(1), -1 pop r15 cmp r15, 1 jle .stdio0 dec r15 add rsp, 8 xor r14, r14 .readcmd: cmp r14, r15 jge .checkfd mov r13, sv(r14) cmp dword[r13], `-if\0` je .setif cmp dword[r13], `-of\0` je .setof cmp word[r13], "-h" je .usage jmp .readcmd .stdio0: mov fd(0), 0 mov fd(1), 1 jmp .checkfd .setif: xor rax, rax inc r14 cmp r14, r15 je .checkfd mov rdi, sv(r14) cmp dword[rdi], "stdi" je .stif mov rax, 2 mov rsi, 0 mov rdx, 0 syscall .stif: mov fd(0), rax inc r14 jmp .readcmd .setof: mov rax, 1 inc r14 cmp r14, r15 jge .checkfd mov rdi, sv(r14) cmp dword[rdi], "stdo" je .stof mov rax, 85 mov rsi, 0o644 syscall .stof: mov fd(1), rax inc r14 jmp .readcmd .checkfd: cmp fd(0), -1 jne .cfd0 mov fd(0), 0 .cfd0: cmp fd(0), -1 jl .err0 cmp fd(1), -1 jne .cfd1 cmp fd(0), -1 jl .err1 mov fd(1), 1 .cfd1: .readwrite: sub rsp, 8 .read: xor rax, rax mov rdi, fd(0) mov rsi, rsp mov rdx, 1 syscall or rax, rax jz .close0 .rot13_: mov dil, byte[rsp] call rot13byte mov qword[rsp], rax .write: mov rax, 1 mov rdi, fd(1) mov rsi, rsp mov rdx, 1 syscall or rax, rax js .close0 jmp .read .close0: add rsp, 8 cmp fd(0), 2 jle .close1 mov rax, 3 mov rdi, fd(0) syscall .close1: cmp fd(1), 2 jle .exit0 mov rax, 3 mov rdi, fd(1) syscall .exit0: mov rax, 60 mov rdi, 0 syscall .usage: mov rax, 1 mov rdi, 1 mov rsi, umsg mov rdx, endumsg - umsg syscall jmp .exit0 .err0: mov rax, 1 mov rdi, 1 mov rsi, e0 mov rdx, ende0 - e0 syscall jmp .close1 .err1: mov rax, 1 mov rdi, 1 mov rsi, e1 mov rdx, ende1 - e1 syscall jmp .usage;------------------------------rot13byte: push rdi push rdx push rcx mov rcx, 26 mov rax, rdi .testupper: cmp dil, 'A' jl .return0 cmp dil, 'Z' jg .testlower .rotupper: sub rdi, 'A' add rdi, 13 xor rdx, rdx mov rax, rdi div rcx mov rax, rdx add rax, 'A' jmp .return0 .testlower: cmp dil, 'a' jl .return0 cmp dil, 'z' jg .return0 .rotlower: sub rdi, 'a' add rdi, 13 xor rdx, rdx mov rax, rdi div rcx mov rax, rdx add rax, 'a' .return0: pop rcx pop rdx pop rdi retsection .dataumsg: db "Usage:", 0x0a db "rot13 [-if input_filename] [-of output_filename]", 0x0aendumsg:e0: db "Error opening input file!", 0x0aende0:e1: db "Error opening output file!", 0x0aende1:section .bssfiledescriptor resq 2
~$ nasm -f elf64 rot13.asm -o rot13.o~$ ld -s -z noexecstack -no-pie rot13.o -o rot13~$ cat test.txtImplement a rot-13 function (or procedure, class, subroutine,or other "callable" object as appropriate to your programmingenvironment).~$ ./rot13 -if test.txt -of rotated.txt~$ cat rotated.txtVzcyrzrag n ebg-13 shapgvba (be cebprqher, pynff, fhoebhgvar,be bgure "pnyynoyr" bowrpg nf nccebcevngr gb lbhe cebtenzzvatraivebazrag).~$ cat rotated.txt | ./rot13Implement a rot-13 function (or procedure, class, subroutine,or other "callable" object as appropriate to your programmingenvironment).~$
Usage: rot13 <infile.txt >outfile.txt
code ChIn=7, ChOut=8;int C, CC;repeat C:= ChIn(1); CC:= C&~$20; \CC handles lowercase too ChOut(0, C + (if CC>=^A & CC<=^M then +13 else if CC>=^N & CC<=^Z then -13 else 0));until C = $1A; \EOF
Textual transforms are one of the domains XSLT was designed for.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" /> <xsl:variable name="alpha">ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz</xsl:variable> <xsl:variable name="rot13">NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm</xsl:variable> <xsl:template match="body"> <xsl:apply-templates/> </xsl:template> <xsl:template match="rot13"> <xsl:value-of select="translate(.,$alpha,$rot13)"/> </xsl:template></xsl:stylesheet>
This will transform the input:
<body>The <rot13>Abjurer</rot13> was to be found <rot13>Nowhere</rot13>.</body>
into:
The Nowhere was to be found Abjurer.
s$ = "nowhere ABJURER"print " Cadena original : ", s$print " Tras codificar : ", Rot13$(s$)print "Tras decodificar : ", Rot13$(Rot13$(s$))endsub Rot13$ (s$) local cad$ cad$ = "" for i = 1 to len(s$) temp = asc(mid$(s$, i, 1)) if temp >= 65 and temp <= 90 then // A to Z temp = (mod((temp - 52), 26)) + 65 elsif temp >= 97 And temp <= 122 then // a to z temp = (mod((temp - 84), 26)) + 97 end if cad$ = cad$ + chr$(temp) next i return cad$end sub
Cadena original : nowhere ABJURER Tras codificar : abjurer NOWHERETras decodificar : nowhere ABJURER
!YS-v0defn main(input='Hello, World!'): s =: set(\\A .. \\Z) + (\\a .. \\z) say: cycle(s).drop(13 * 2) .zipmap(s).escape(input)
const std = @import("std");pub const Rot13 = struct { pub fn char(ch: u8) u8 { return switch (ch) { 'a'...'m', 'A'...'M' => |c| c + 13, 'n'...'z', 'N'...'Z' => |c| c - 13, else => |c| c, }; } /// Caller owns returned memory. pub fn slice(allocator: std.mem.Allocator, input: []const u8) error{OutOfMemory}![]u8 { const output = try allocator.alloc(u8, input.len); errdefer allocator.free(output); for (input, output) |input_ch, *output_ch| { output_ch.* = char(input_ch); } return output; }};pub fn main() error{OutOfMemory}!void { var gpa: std.heap.GeneralPurposeAllocator(.{}) = .{}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); const message_input = \\@@@111@@@ Lbh xabj vg vf tbvat gb or n onq qnl \\ jura gur yrggref va lbhe nycunorg fbhc \\ fcryy Q-V-F-N-F-G-R-E. ; const message_decoded = try Rot13.slice(allocator, message_input); defer allocator.free(message_decoded); std.debug.print( \\{s} \\=== Decoded to === \\{s} \\ , .{ message_input, message_decoded, }); std.debug.print("\n", .{}); const message_encoded = try Rot13.slice(allocator, message_decoded); defer allocator.free(message_encoded); std.debug.print( \\{s} \\=== Encoded to === \\{s} \\ , .{ message_decoded, message_encoded, });}
@@@111@@@ Lbh xabj vg vf tbvat gb or n onq qnl jura gur yrggref va lbhe nycunorg fbhc fcryy Q-V-F-N-F-G-R-E. === Decoded to ===@@@111@@@ You know it is going to be a bad day when the letters in your alphabet soup spell D-I-S-A-S-T-E-R. @@@111@@@ You know it is going to be a bad day when the letters in your alphabet soup spell D-I-S-A-S-T-E-R. === Encoded to ===@@@111@@@ Lbh xabj vg vf tbvat gb or n onq qnl jura gur yrggref va lbhe nycunorg fbhc fcryy Q-V-F-N-F-G-R-E.
File rot13.zkl:
#!/home/craigd/Bin/zklfcn rot13(text){ text.translate("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM");}text:=(vm.arglist or File.stdin); // command line or pipetext.pump(File.stdout,rot13); // rotate each word and print itif(text.isType(List)) File.stdout.writeln();// command line gets ending newline
$ ./rot13.zkl "Hello World!"Uryyb Jbeyq!$ ./rot13.zkl Hello " " 'World!'Uryyb Jbeyq!$ echo "Uryyb Jbeyq!" | ./rot13.zklHello World!$ ./rot13.zkl < rot13.zkl#!/ubzr/penvtq/Ova/mxyspa ebg13(grkg){ grkg.genafyngr("nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM", "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");}grkg:=(iz.netyvfg be Svyr.fgqva); // pbzznaq yvar be cvcrgrkg.chzc(Svyr.fgqbhg,ebg13); // ebgngr rnpu jbeq naq cevag vgvs(grkg.vfGlcr(Yvfg)) Svyr.fgqbhg.jevgrya();// pbzznaq yvar trgf raqvat arjyvar
program: rot13 case: 1 input: abc output: nop case: 2 input: nop output: abc case: 3 input: 'ABC' output: 'NOP' case: 4 input: 'NOP' output: 'ABC'
10 CLS20 INPUT "Enter a string: ", s$30 LET a$ = "": REM a$ is the encoded string40 FOR l = 1 TO LEN(s$)50 LET i$ = s$(l): REM i$ is the letter being worked on60 IF i$ < "A" OR i$ > "Z" THEN GO TO 10070 LET c$ = CHR$(CODE(i$) + 13): REM c$ is the encoded letter80 IF c$ > "Z" THEN LET c$ = CHR$(CODE(c$) - 26) 90 GO TO 300100 IF i$ < "a" OR i$ > "z" THEN GO TO 200110 LET c$ = CHR$(CODE(i$) + 13) 120 IF c$ > "z" THEN LET c$ = CHR$(CODE(c$) - 26) 130 GO TO 300200 LET c$ = i$300 LET a$ = a$ + c$310 NEXT l320 PRINT a$