Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

5
Task/Rot-13/00-META.yaml Normal file
View file

@ -0,0 +1,5 @@
---
category:
- String_manipulation
from: http://rosettacode.org/wiki/Rot-13
note: Encryption

31
Task/Rot-13/00-TASK.txt Normal file
View file

@ -0,0 +1,31 @@
;Task:
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   (like [[:Category:Tr|tr]],   which acts like a common [[UNIX]] 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   [[wp:Spoiler (media)|spoiler]]   or potentially offensive material.
Many news reader and mail user agent programs have built-in '''rot-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.
Technically '''rot-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.
;Related tasks:
*   [[Caesar cipher]]
*   [[Substitution Cipher]]
*   [[Vigenère Cipher/Cryptanalysis]]
{{Template:Strings}}
<br><br>

View file

@ -0,0 +1,14 @@
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 r
print(rot13(foo))
print(rot13(sbb))

View file

@ -0,0 +1,26 @@
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 caller
CC 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

View file

@ -0,0 +1,38 @@
buffer = $fa ; or anywhere in zero page that's good
maxpage = $95 ; if non-terminated that's bad
org $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
.end
save "rot-13", rot13, end

View file

@ -0,0 +1,20 @@
(include-book "arithmetic-3/top" :dir :system)
(defun char-btn (c low high)
(and (char>= c low)
(char<= c high)))
(defun rot-13-cs (cs)
(cond ((endp cs) nil)
((or (char-btn (first cs) #\a #\m)
(char-btn (first cs) #\A #\M))
(cons (code-char (+ (char-code (first cs)) 13))
(rot-13-cs (rest cs))))
((or (char-btn (first cs) #\n #\z)
(char-btn (first cs) #\N #\Z))
(cons (code-char (- (char-code (first cs)) 13))
(rot-13-cs (rest cs))))
(t (cons (first cs) (rot-13-cs (rest cs))))))
(defun rot-13 (s)
(coerce (rot-13-cs (coerce s 'list)) 'string))

View file

@ -0,0 +1,14 @@
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)
OD
END # rot13 #

View file

@ -0,0 +1,2 @@
r1 ⎕UCS {+/,13×(65)(<78),(-(78)(90)),(97)(<110),(-(110)(122))} ⎕UCS
rot13 { r1 ¨ }

View file

@ -0,0 +1,2 @@
r1 { ⎕UCS {+/,13×(65)(<78),(-(78)(90)),(97)(<110),(-(110)(122))} ⎕UCS }
rot13 { r1 ¨ }

View file

@ -0,0 +1,4 @@
⍝ 2023-03-03
k'AaBbCcDdEeFfGgHhIiJjKkLlMmzZyYxXwWvVuUtTsSrRqQpPoOnN'
rot{k:[53-k]}¨

View file

@ -0,0 +1,23 @@
# usage: awk -f rot13.awk
BEGIN {
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)] in rot13 ) {
c = rot13[amap[tolower($i)]]
if ( tolower($i) != $i ) c = toupper(c)
o = o c
} else {
o = o $i
}
}
print o
}

View file

@ -0,0 +1,40 @@
with Ada.Text_IO.Text_Streams; use Ada.Text_IO.Text_Streams;
with Ada.Strings.Maps; use Ada.Strings.Maps;
with Ada.Command_Line; use Ada.Command_Line;
procedure Rot_13 is
From_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;
begin
if Argument_Count > 0 then
for I in 1..Argument_Count loop
begin
Ada.Text_Io.Open(File => Input, Mode => Ada.Text_Io.In_File, Name => Argument(I));
Stdio := Stream(Input);
while not Ada.Text_Io.End_Of_File(Input) loop
In_Char :=Character'Input(Stdio);
Character'Output(Stdout, Value(Rot_13_Mapping, In_Char));
end loop;
Ada.Text_IO.Close(Input);
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_Io.Put_Line(File => Ada.Text_Io.Standard_Error, Item => "File " & Argument(I) & " is not a file.");
when Ada.Text_Io.Status_Error =>
Ada.Text_Io.Put_Line(File => Ada.Text_Io.Standard_Error, Item => "File " & Argument(I) & " is already opened.");
end;
end loop;
else
while not Ada.Text_Io.End_Of_File loop
In_Char :=Character'Input(Stdio);
Character'Output(Stdout, Value(Rot_13_Mapping, In_Char));
end loop;
end if;
end Rot_13;

View file

@ -0,0 +1,3 @@
to rot13(textString)
do shell script "tr a-zA-Z n-za-mN-ZA-M <<<" & quoted form of textString
end rot13

View file

@ -0,0 +1,9 @@
to rot13(textString)
set theIDs to id of textString
repeat with thisID in theIDs
if (((thisID < 123) and (thisID > 96)) or ((thisID < 91) and (thisID > 64))) then ¬
tell (thisID mod 32) to set thisID's contents to thisID - it + (it + 12) mod 26 + 1
end repeat
return string id theIDs
end rot13

View file

@ -0,0 +1 @@
rot13("nowhere ABJURER")

View file

@ -0,0 +1,61 @@
-- ROT 13 --------------------------------------------------------------------
-- rot13 :: String -> String
on rot13(str)
script rt13
on |λ|(x)
if (x "a" and x "m") or (x "A" and x "M") then
character id ((id of x) + 13)
else if (x "n" and x "z") or (x "N" and x "Z") then
character id ((id of x) - 13)
else
x
end if
end |λ|
end script
intercalate("", map(rt13, characters of str))
end rot13
-- TEST ----------------------------------------------------------------------
on run
rot13("nowhere ABJURER")
--> "abjurer NOWHERE"
end run
-- GENERIC FUNCTIONS ---------------------------------------------------------
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn

View file

@ -0,0 +1,2 @@
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$

View file

@ -0,0 +1,11 @@
rot13: function [c][
case [in? lower c]
when? -> `a`..`m` -> return to :char (to :integer c) + 13
when? -> `n`..`z` -> return to :char (to :integer c) - 13
else -> return c
]
loop "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 'ch
-> prints rot13 ch
print ""

View file

@ -0,0 +1,15 @@
ROT13(string) ; by Raccoon July-2009
{
Static a := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "
Static b := "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM "
s=
Loop, Parse, string
{
c := substr(b,instr(a,A_LoopField,True),1)
if (c != " ")
s .= c
else
s .= A_LoopField
}
Return s
}

View file

@ -0,0 +1,14 @@
ROT13(string) ; by Raccoon July-2009
{
s=
Loop, Parse, string
{
c := asc(A_LoopField)
if (c >= 97) && (c <= 109) || (c >= 65) && (c <= 77)
c += 13
else if (c >= 110) && (c <= 122) || (c >= 78) && (c <= 90)
c -= 13
s .= chr(c)
}
Return s
}

View file

@ -0,0 +1,28 @@
Str0=Hello, This is a sample text with 1 2 3 or other digits!@#$^&*()-_=
Str1 := Rot13(Str0)
Str2 := Rot13(Str1)
MsgBox % Str0 "`n" Str1 "`n" Str2
Rot13(string)
{
Loop Parse, string
{
char := Asc(A_LoopField)
; o is 'A' code if it is an uppercase letter, and 'a' code if it is a lowercase letter
o := 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 size
char := Mod(char - o + 13, 26)
; Transform back to char, upper or lower
char := Chr(char + o)
}
Else
{
; Non alphabetic, unchanged
char := A_LoopField
}
rStr .= char
}
Return rStr
}

View file

@ -0,0 +1,9 @@
Rot13(string) {
Output := ""
Loop, Parse, string
{
a := ~Asc(A_LoopField)
Output .= Chr(~a-1//(~(a|32)//13*2-11)*13)
}
return Output
}

View file

@ -0,0 +1,17 @@
CLS
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)
ELSEIF 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 a
PRINT ans$

View file

@ -0,0 +1,10 @@
INPUT "Enter a string "; Text$
FOR c% = 1 TO LEN(Text$)
SELECT CASE ASC(MID$(Text$, c%, 1))
CASE 65 TO 90
MID$(Text$, c%, 1) = CHR$(65 + ((ASC(MID$(Text$, c%, 1)) - 65 + 13) MOD 26))
CASE 97 TO 122
MID$(Text$, c%, 1) = CHR$(97 + ((ASC(MID$(Text$, c%, 1)) - 97 + 13) MOD 26))
END SELECT
NEXT c%
PRINT "Converted......: "; Text$

View file

@ -0,0 +1,33 @@
# rot13 Cipher v2.0
# basic256 1.1.4.0
# 2101031238
dec$ = ""
type$ = "cleartext "
ctext$ = ""
sp = 0
iOffset = 13 #offset assumed to be 13 - uncomment line 11 to change
input "For decrypt enter " + "<d> " + " -- else press enter > ",dec$
# input "Enter offset > ", iOffset
if dec$ = "d" OR dec$ = "D" then
iOffset = 26 - iOffset
type$ = "ciphertext "
end if
input "Enter " + type$ + "> ", str$
str$ = upper(str$)
for i = 1 to length(str$)
iTemp = asc(mid(str$,i,1))
if iTemp > 64 AND iTemp < 91 then
iTemp = ((iTemp - 65) + iOffset) % 26
print chr(iTemp + 65);
sp = sp + 1
if sp = 5 then
print(' ');
sp = 0
endif
endif
next i

View file

@ -0,0 +1,22 @@
REPEAT
INPUT A$
PRINT FNrot13(A$)
UNTIL FALSE
END
DEF FNrot13(A$)
LOCAL A%,B$,C$
IF A$="" THEN =""
FOR A%=1 TO LEN A$
C$=MID$(A$,A%,1)
IF C$<"A" OR (C$>"Z" AND C$<"a") OR C$>"z" THEN
B$=B$+C$
ELSE
IF (ASC(C$) AND &DF)<ASC("N") THEN
B$=B$+CHR$(ASC(C$)+13)
ELSE
B$=B$+CHR$(ASC(C$)-13)
ENDIF
ENDIF
NEXT A%
=B$

View file

@ -0,0 +1,12 @@
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

View file

@ -0,0 +1,2 @@
INPUT "String: ", s$
PRINT "Output: ", REPLACE$(s$, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM", 2)

View file

@ -0,0 +1,47 @@
@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

View file

@ -0,0 +1,4 @@
~:"z"`#v_:"m"`#v_:"`"` |>
:"Z"`#v_:"M"`#v_:"@"`|>
: 0 `#v_@v-6-7< >
, < <+6+7 <<v

View file

@ -0,0 +1,4 @@
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"

View file

@ -0,0 +1,77 @@
#include <iostream>
#include <istream>
#include <ostream>
#include <fstream>
#include <cstdlib>
#include <string>
// the rot13 function
std::string rot13(std::string s)
{
static std::string const
lcalph = "abcdefghijklmnopqrstuvwxyz",
ucalph = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string result;
std::string::size_type pos;
result.reserve(s.length());
for (std::string::iterator it = s.begin(); it != s.end(); ++it)
{
if ( (pos = lcalph.find(*it)) != std::string::npos )
result.push_back(lcalph[(pos+13) % 26]);
else if ( (pos = ucalph.find(*it)) != std::string::npos )
result.push_back(ucalph[(pos+13) % 26]);
else
result.push_back(*it);
}
return result;
}
// 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 reading
int rot13_stream(std::istream& is)
{
std::string line;
while (std::getline(is, line))
{
if (!(std::cout << rot13(line) << "\n"))
return false;
}
return is.eof();
}
// the main program
int main(int argc, char* argv[])
{
if (argc == 1) // no arguments given
return rot13_stream(std::cin)? EXIT_SUCCESS : EXIT_FAILURE;
std::ifstream file;
for (int i = 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";
return EXIT_FAILURE;
}
if (!rot13_stream(file))
{
if (file.eof())
// no error occurred for file, so the error must have been in output
std::cerr << argv[0] << ": error writing to stdout\n";
else
std::cerr << argv[0] << ": error reading from " << argv[i] << "\n";
return EXIT_FAILURE;
}
file.clear();
file.close();
if (!file)
std::cerr << argv[0] << ": warning: closing failed for " << argv[i] << "\n";
}
return EXIT_SUCCESS;
}

View file

@ -0,0 +1,41 @@
#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>
namespace io = boost::iostreams;
class rot_output_filter : public io::output_filter
{
public:
explicit rot_output_filter(int r=13):rotby(r),negrot(alphlen-r){};
template<typename Sink>
bool put(Sink& dest, int c){
char uc = toupper(c);
if(('A' <= uc) && (uc <= ('Z'-rotby)))
c = c + rotby;
else if ((('Z'-rotby) <= uc) && (uc <= 'Z'))
c = c - negrot;
return boost::iostreams::put(dest, c);
};
private:
static const int alphlen = 26;
const int rotby;
const int negrot;
};
int main(int argc, char *argv[])
{
io::filtering_ostream out;
out.push(rot_output_filter(13));
out.push(std::cout);
if (argc == 1) out << std::cin.rdbuf();
else for(int i = 1; i < argc; ++i){
std::ifstream in(argv[i]);
out << in.rdbuf();
}
}

View file

@ -0,0 +1,34 @@
#include <string>
#include <iostream>
#include <fstream>
char rot13(const char c){
if (c >= 'a' && c <= 'z')
return (c - 'a' + 13) % 26 + 'a';
else if (c >= 'A' && c <= 'Z')
return (c - 'A' + 13) % 26 + 'A';
return c;
}
std::string &rot13(std::string &s){
for (auto &c : s) //range based for is the only used C++11 feature
c = rot13(c);
return s;
}
void rot13(std::istream &in, std::ostream &out){
std::string s;
while (std::getline(in, s))
out << rot13(s) << '\n';
}
int main(int argc, char *argv[]){
if (argc == 1)
rot13(std::cin, std::cout);
for (int arg = 1; arg < argc; ++arg){
std::ifstream f(argv[arg]);
if (!f)
return EXIT_FAILURE;
rot13(f, std::cout);
}
}

View file

@ -0,0 +1,38 @@
using System;
using System.IO;
using System.Linq;
using System.Text;
class Program
{
static char Rot13(char c)
{
if ('a' <= c && c <= 'm' || 'A' <= c && c <= 'M')
{
return (char)(c + 13);
}
if ('n' <= c && c <= 'z' || 'N' <= c && c <= 'Z')
{
return (char)(c - 13);
}
return c;
}
static string Rot13(string s)
{
return new string(s.Select(Rot13).ToArray());
}
static void Main(string[] args)
{
foreach (var file in args.Where(file => File.Exists(file)))
{
Console.WriteLine(Rot13(File.ReadAllText(file)));
}
if (!args.Any())
{
Console.WriteLine(Rot13(Console.In.ReadToEnd()));
}
}
}

51
Task/Rot-13/C/rot-13.c Normal file
View file

@ -0,0 +1,51 @@
#include <ctype.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
static char rot13_table[UCHAR_MAX + 1];
static void init_rot13_table(void) {
static const unsigned char upper[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static const unsigned char lower[] = "abcdefghijklmnopqrstuvwxyz";
for (int ch = '\0'; ch <= UCHAR_MAX; ch++) {
rot13_table[ch] = ch;
}
for (const unsigned char *p = upper; p[13] != '\0'; p++) {
rot13_table[p[0]] = p[13];
rot13_table[p[13]] = p[0];
}
for (const unsigned char *p = lower; p[13] != '\0'; p++) {
rot13_table[p[0]] = p[13];
rot13_table[p[13]] = p[0];
}
}
static void rot13_file(FILE *fp)
{
int ch;
while ((ch = fgetc(fp)) != EOF) {
fputc(rot13_table[ch], stdout);
}
}
int main(int argc, char *argv[])
{
init_rot13_table();
if (argc > 1) {
for (int i = 1; i < argc; i++) {
FILE *fp = fopen(argv[i], "r");
if (fp == NULL) {
perror(argv[i]);
return EXIT_FAILURE;
}
rot13_file(fp);
fclose(fp);
}
} else {
rot13_file(stdin);
}
return EXIT_SUCCESS;
}

View file

@ -0,0 +1,22 @@
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 rot13
start_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
end
end start_up

View file

@ -0,0 +1,25 @@
IDENTIFICATION DIVISION.
PROGRAM-ID. rot-13.
DATA DIVISION.
LOCAL-STORAGE SECTION.
78 STR-LENGTH VALUE 100.
78 normal-lower VALUE "abcdefghijklmnopqrstuvwxyz".
78 rot13-lower VALUE "nopqrstuvwxyzabcdefghijklm".
78 normal-upper VALUE "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
78 rot13-upper VALUE "NOPQRSTUVWXYZABCDEFGHIJKLM".
LINKAGE SECTION.
01 in-str PIC X(STR-LENGTH).
01 out-str PIC X(STR-LENGTH).
PROCEDURE DIVISION USING VALUE in-str, REFERENCE out-str.
MOVE in-str TO out-str
INSPECT out-str CONVERTING normal-lower TO rot13-lower
INSPECT out-str CONVERTING normal-upper TO rot13-upper
GOBACK
.

View file

@ -0,0 +1,17 @@
100 rem ROT-13
110 cls : rem 110 HOME for Applesoft BASIC
120 input "Enter a string: ";a$
130 gosub 160
140 print b$
150 end
160 rem FUNCTION rot13
170 for i = 1 to len(a$)
180 n = asc(mid$(a$,i,1))
190 e = 255
200 if n > 64 and n < 91 then e = 90 : rem uppercase
210 if n > 96 and n < 123 then e = 122 : rem lowercase
220 if e < 255 then n = n+13
230 if n > e then n = n-26
240 b$ = b$+chr$(n)
250 next
260 return

View file

@ -0,0 +1,19 @@
(ns rosettacode.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)]
(defn rot-13 [^Character c]
(char (let [i (int c)]
(cond-> i
(or (<= a i m) (<= A i M)) (+ 13)
(or (<= n i z) (<= N i Z)) (- 13))))))
(apply str (map rot-13 "The Quick Brown Fox Jumped Over The Lazy Dog!"))
; An alternative implementation using a map:
(let [A (into #{} "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
Am (->> (cycle A) (drop 26) (take 52) (zipmap A))]
(defn rot13 [^String in]
(apply str (map #(Am % %) in))))
(rot13 "The Quick Brown Fox Jumped Over The Lazy Dog!")

View file

@ -0,0 +1,39 @@
1 rem rot-13 cipher
2 rem rosetta code
10 print chr$(147);chr$(14);
25 gosub 1000
30 print chr$(147);"Enter a message to translate."
35 print:print "Press CTRL-Z when finished.":print
40 mg$="":gosub 2000
45 print chr$(147);"Processing...":gosub 3000
50 print chr$(147);"The translated message is:"
55 print:print cm$
100 print:print "Do another one? ";
110 get k$:if k$<>"y" and k$<>"n" then 110
120 print k$:if k$="y" then goto 10
130 end
1000 rem generate encoding table
1010 ec$="mnopqrstuvwxyzabcdefghijklMNOPQRSTUVWXYZABCDEFGHIJKL"
1099 return
2000 rem get user input routine
2005 print chr$(18);" ";chr$(146);chr$(157);
2010 get k$:if k$="" then 2010
2012 if k$=chr$(13) then print " ";chr$(157);
2015 print k$;
2020 if k$=chr$(20) then mg$=left$(mg$,len(mg$)-1):goto 2040
2025 if len(mg$)=255 or k$=chr$(26) then return
2030 mg$=mg$+k$
2040 goto 2005
3000 rem translate message
3005 cm$=""
3010 for i=1 to len(mg$)
3015 c=asc(mid$(mg$,i,1))
3020 if c<65 or (c>90 and c<193) or c>218 then cm$=cm$+chr$(c):goto 3030
3025 if c>=65 and c<=90 then c=c-64
3030 if c>=193 and c<=218 then c=(c-192)+26
3035 cm$=cm$+mid$(ec$,c,1)
3040 next i
3050 return

View file

@ -0,0 +1,13 @@
(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))
(defun rot13 (s)
(map 'string
(lambda (c &aux (n (position (char-upcase c) +alphabet+)))
(if n
(funcall
(if (lower-case-p c) #'char-downcase #'identity)
(nth (mod (+ 13 n) 26) +alphabet+))
c))
s))

View file

@ -0,0 +1,12 @@
(defun rot13 (string)
(map 'string
(lambda (char &aux (code (char-code char)))
(if (alpha-char-p char)
(if (> (- code (char-code (if (upper-case-p char)
#\A #\a))) 12)
(code-char (- code 13))
(code-char (+ code 13)))
char))
string))
(rot13 "Moron") ; -> "Zbeba"

View file

@ -0,0 +1,9 @@
(defconstant +a+ "AaBbCcDdEeFfGgHhIiJjKkLlMmzZyYxXwWvVuUtTsSrRqQpPoOnN")
(defun rot (txt)
(map 'string
#'(lambda (x)
(if (find x +a+)
(char +a+ (- 51 (position x +a+)))
x))
txt))

View file

@ -0,0 +1,27 @@
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
]

View file

@ -0,0 +1,4 @@
>>> rot13 "Hello World"
> Uryyb Jbeyq
>>> rot13 "Gur Dhvpx Oebja Sbk Whzcf Bire Gur Ynml Qbt!"
> The Quick Brown Fox Jumps Over The Lazy Dog!

12
Task/Rot-13/D/rot-13-1.d Normal file
View file

@ -0,0 +1,12 @@
import std.stdio;
import std.ascii: letters, U = uppercase, L = lowercase;
import std.string: makeTrans, translate;
immutable r13 = makeTrans(letters,
//U[13 .. $] ~ U[0 .. 13] ~
U[13 .. U.length] ~ U[0 .. 13] ~
L[13 .. L.length] ~ L[0 .. 13]);
void main() {
writeln("This is the 1st test!".translate(r13, null));
}

21
Task/Rot-13/D/rot-13-2.d Normal file
View file

@ -0,0 +1,21 @@
import std.stdio, std.string, std.traits;
pure S rot13(S)(in S s) if (isSomeString!S) {
return rot(s, 13);
}
pure S rot(S)(in S s, in int key) if (isSomeString!S) {
auto r = s.dup;
foreach (i, ref c; r) {
if ('a' <= c && c <= 'z')
c = ((c - 'a' + key) % 26 + 'a');
else if ('A' <= c && c <= 'Z')
c = ((c - 'A' + key) % 26 + 'A');
}
return cast(S) r;
}
void main() {
"Gur Dhvpx Oebja Sbk Whzcf Bire Gur Ynml Qbt!".rot13().writeln();
}

View file

@ -0,0 +1,28 @@
program Rot13;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
function Rot13char(c: AnsiChar): AnsiChar;
begin
Result := c;
if c in ['a'..'m', 'A'..'M'] then
Result := AnsiChar(ord(c) + 13)
else if c in ['n'..'z', 'N'..'Z'] then
Result := AnsiChar(ord(c) - 13);
end;
function Rot13Fn(s: ansistring): ansistring;
var i: Integer;
begin
SetLength(result, length(s));
for i := 1 to length(s) do
Result[i] := Rot13char(s[i]);
end;
begin
writeln(Rot13Fn('nowhere ABJURER'));
readln;
end.

View file

@ -0,0 +1,17 @@
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()

12
Task/Rot-13/E/rot-13.e Normal file
View file

@ -0,0 +1,12 @@
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 }) }
}

View file

@ -0,0 +1,17 @@
PROGRAM ROT13
BEGIN
INPUT("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 CASE
END FOR
PRINT("Converted: ";TEXT$)
END PROGRAM

View file

@ -0,0 +1,23 @@
proc rot13 string$ . encodedString$ .
encodedString$ = ""
for i = 1 to len string$
code = strcode substr string$ i 1
if code >= 65 and code <= 90
encodedCode = code + 13
if encodedCode > 90
encodedCode = 64 + encodedCode - 90
.
elif code >= 97 and code <= 122
encodedCode = code + 13
if encodedCode > 122
encodedCode = 96 + encodedCode - 122
.
else
encodedCode = code
.
encodedString$ &= strchar encodedCode
.
.
#
call rot13 "Rosetta Code" result$
print result$

View file

@ -0,0 +1,31 @@
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]))
}
}

View file

@ -0,0 +1,12 @@
defmodule RC do
def rot13(clist) do
f = fn(c) when (?A <= c and c <= ?M) or (?a <= c and c <= ?m) -> c + 13
(c) when (?N <= c and c <= ?Z) or (?n <= c and c <= ?z) -> c - 13
(c) -> c
end
Enum.map(clist, f)
end
end
IO.inspect encode = RC.rot13('Rosetta Code')
IO.inspect RC.rot13(encode)

View file

@ -0,0 +1,46 @@
defmodule Rot13 do
@moduledoc """
ROT13 encoding program. Takes user input and outputs encoded text.
"""
@spec sign(integer | float) :: -1 | 1
def sign(int) do
if int >= 0 do 1
else -1
end
end
@spec rotate(charlist) :: charlist
def rotate(string_chars) do
string_chars
|> Enum.map(
fn char ->
char_up = << char :: utf8 >>
|> String.upcase()
|> String.to_charlist()
|> Enum.at(0)
if ?A <= char_up and char_up <= ?Z do
<<
char + (-13 * trunc(sign(char_up - 77.5))) :: utf8
>>
else
<< char :: utf8 >>
end
end)
end
@spec start(any, any) :: {:ok, pid}
def start(_type, _args) do
IO.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)
end
end

View file

@ -0,0 +1,5 @@
(rot13-string "abc") ;=> "nop"
(with-temp-buffer
(insert "abc")
(rot13-region (point-min) (point-max))
(buffer-string)) ;=> "nop"

View file

@ -0,0 +1,15 @@
(defun rot-13 (string)
(let* ((len (length string))
(output (make-string len ?\s)))
(dotimes (i len)
(let ((char (aref string i)))
(cond
((or (and (>= char ?n) (<= char ?z))
(and (>= char ?N) (<= char ?Z)))
(aset output i (- char 13)))
((or (and (>= char ?a) (<= char ?m))
(and (>= char ?A) (<= char ?M)))
(aset output i (+ char 13)))
(t
(aset output i char)))))
output))

View file

@ -0,0 +1,6 @@
rot13(Str) ->
F = fun(C) when (C >= $A andalso C =< $M); (C >= $a andalso C =< $m) -> C + 13;
(C) when (C >= $N andalso C =< $Z); (C >= $n andalso C =< $z) -> C - 13;
(C) -> C
end,
lists:map(F, Str).

View file

@ -0,0 +1,39 @@
include std/types.e
include std/text.e
atom FALSE = 0
atom TRUE = not FALSE
function Rot13( object oStuff )
integer iOffset
integer bIsUpper
object oResult
sequence sAlphabet = "abcdefghijklmnopqrstuvwxyz"
if sequence(oStuff) then
oResult = repeat( 0, length( oStuff ) )
for i = 1 to length( oStuff ) do
oResult[ i ] = Rot13( oStuff[ i ] )
end for
else
bIsUpper = FALSE
if t_upper( oStuff ) then
bIsUpper = TRUE
oStuff = lower( oStuff )
end if
iOffset = find( oStuff, sAlphabet )
if iOffset != 0 then
iOffset += 13
iOffset = remainder( iOffset, 26 )
if iOffset = 0 then iOffset = 1 end if
oResult = sAlphabet[iOffset]
if bIsUpper then
oResult = upper(oResult)
end if
else
oResult = oStuff --sprintf( "%s", oStuff )
end if
end if
return oResult
end function
puts( 1, Rot13( "abjurer NOWHERE." ) & "\n" )

View file

@ -0,0 +1,9 @@
let rot13 (s : string) =
let rot c =
match c with
| c when c > 64 && c < 91 -> ((c - 65 + 13) % 26) + 65
| c when c > 96 && c < 123 -> ((c - 97 + 13) % 26) + 97
| _ -> c
s |> Array.of_seq
|> Array.map(int >> rot >> char)
|> (fun seq -> new string(seq))

View file

@ -0,0 +1 @@
[^$1+][$32|$$'z>'a@>|$[\%]?~[13\'m>[_]?+]?,]#%

View file

@ -0,0 +1,80 @@
#APPTYPE CONSOLE
REM Create a CircularQueue object
REM CQ.Store item
REM CQ.Find items
REM CQ.Forward nItems
REM CQ.Recall
REM SO CQ init WITH "A"... "Z"
REM CQ.Find "B"
REM QC.Forward 13
REM QC.Recall
CLASS CircularQueue
items[]
head
tail
here
SUB INITIALIZE(dArray)
head = 0
tail = 0
here = 0
FOR DIM i = LBOUND(dArray) TO UBOUND(dArray)
items[tail] = dArray[i]
tail = tail + 1
NEXT
END SUB
SUB TERMINATE()
REM
END SUB
METHOD Put(s AS STRING)
items[tail] = s
tail = tail + 1
END METHOD
METHOD Find(s AS STRING)
FOR DIM i = head TO tail - 1
IF items[i] = s THEN
here = i
RETURN TRUE
END IF
NEXT
RETURN FALSE
END METHOD
METHOD Move(n AS INTEGER)
DIM bound AS INTEGER = UBOUND(items) + 1
here = (here + n) MOD bound
END METHOD
METHOD Recall()
RETURN items[here]
END METHOD
PROPERTY Size()
RETURN COUNT(items)
END PROPERTY
END CLASS
DIM CQ AS NEW CircularQueue({"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"})
DIM c AS STRING
DIM isUppercase AS INTEGER
DIM s AS STRING = "nowhere ABJURER"
FOR DIM i = 1 TO LEN(s)
c = MID(s, i, 1)
isUppercase = lstrcmp(LCASE(c), c)
IF CQ.Find(UCASE(c)) THEN
CQ.Move(13)
PRINT IIF(isUppercase, UCASE(CQ.Recall()), LCASE(CQ.Recall())) ;
ELSE
PRINT c;
END IF
NEXT
PAUSE

View file

@ -0,0 +1,24 @@
#! /usr/bin/env factor
USING: kernel io ascii math combinators sequences ;
IN: rot13
: rot-base ( ch ch -- ch ) [ - 13 + 26 mod ] keep + ;
: rot13-ch ( ch -- ch )
{
{ [ dup letter? ] [ CHAR: a rot-base ] }
{ [ dup LETTER? ] [ CHAR: A rot-base ] }
[ ]
}
cond ;
: rot13 ( str -- str ) [ rot13-ch ] map ;
: main ( -- )
[ readln dup ]
[ rot13 print flush ]
while
drop ;
MAIN: main

View file

@ -0,0 +1,35 @@
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)}")
}
}
}

View file

@ -0,0 +1,5 @@
: r13 ( c -- o )
dup 32 or \ tolower
dup [char] a [char] z 1+ within if
[char] m > if -13 else 13 then +
else drop then ;

View file

@ -0,0 +1,21 @@
: ,chars ( end start -- )
do i c, loop ;
: xlate create does> ( c -- c' ) + c@ ;
xlate rot13
char A 0 ,chars
char Z 1+ char N ,chars
char N char A ,chars
char a char Z 1+ ,chars
char z 1+ char n ,chars
char n char a ,chars
256 char z 1+ ,chars
: rot13-string ( addr len -- )
over + swap do i c@ rot13 i c! loop ;
: .rot13" ( string -- )
[char] " parse 2dup rot13-string type ;
.rot13" abjurer NOWHERE" \ nowhere ABJURER

View file

@ -0,0 +1,58 @@
program test_rot_13
implicit none
integer, parameter :: len_max = 256
integer, parameter :: unit = 10
character (len_max) :: file
character (len_max) :: fmt
character (len_max) :: line
integer :: arg
integer :: arg_max
integer :: iostat
write (fmt, '(a, i0, a)') '(a', len_max, ')'
arg_max = iargc ()
if (arg_max > 0) then
! Encode all files listed on the command line.
do arg = 1, arg_max
call getarg (arg, file)
open (unit, file = file, iostat = iostat)
if (iostat /= 0) cycle
do
read (unit, fmt = fmt, iostat = iostat) line
if (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) line
if (iostat /= 0) exit
write (*, '(a)') trim (rot_13 (line))
end do
end if
contains
function rot_13 (input) result (output)
implicit none
character (len_max), intent (in) :: input
character (len_max) :: output
integer :: i
output = input
do i = 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 function rot_13
end program test_rot_13

View file

@ -0,0 +1,12 @@
> cat foo.txt
foo
> cat bar.txt
bar
> ./rot_13 foo.txt bar.txt
sbb
one
> ./rot_13 < foo.txt
sbb
> cat foo.txt bar.txt | ./rot_13
sbb
one

View file

@ -0,0 +1,29 @@
' FB 1.05.0 Win64
' uses in place encoding/decoding
Sub rot13(ByRef s As String)
If s = "" Then Exit Sub
Dim code As Integer
For i As Integer = 0 To Len(s) - 1
Select Case As Const s[i]
Case 65 To 90 '' A to Z
code = s[i] + 13
If code > 90 Then code -= 26
s[i] = code
Case 97 To 122 '' a to z
code = s[i] + 13
If code > 122 Then code -= 26
s[i] = code
End Select
Next
End Sub
Dim s As String = "nowhere ABJURER"
Print "Before encoding : "; s
rot13(s)
Print "After encoding : "; s
rot13(s)
Print "After decoding : "; s
Print
Print "Press any key to quit"
Sleep

View file

@ -0,0 +1,25 @@
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) )

View file

@ -0,0 +1,27 @@
rot13 := function(s)
local upper, lower, c, n, t;
upper := "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
lower := "abcdefghijklmnopqrstuvwxyz";
t := [ ];
for c in s do
n := Position(upper, c);
if n <> fail then
Add(t, upper[((n+12) mod 26) + 1]);
else
n := Position(lower, c);
if n <> fail then
Add(t, lower[((n+12) mod 26) + 1]);
else
Add(t, c);
fi;
fi;
od;
return t;
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"

View file

@ -0,0 +1,23 @@
#define rot13
var 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;

View file

@ -0,0 +1 @@
show_message(rot13("My dog has fleas!"));

View file

@ -0,0 +1,14 @@
10 INPUT "Enter a string: ",A$
20 GOSUB 50
30 PRINT B$
40 END
50 FOR I=1 TO LEN(A$)
60 N=ASC(MID$(A$,I,1))
70 E=255
80 IF N>64 AND N<91 THEN E=90 ' uppercase
90 IF N>96 AND N<123 THEN E=122 ' lowercase
100 IF E<255 THEN N=N+13
110 IF N>E THEN N=N-26
120 B$=B$+CHR$(N)
130 NEXT
140 RETURN

View file

@ -0,0 +1,2 @@
/[a-mA-M]/=@int-char{@add{@char-int{$1};13}}
/[n-zN-Z]/=@int-char{@sub{@char-int{$1};13}}

23
Task/Rot-13/Go/rot-13.go Normal file
View file

@ -0,0 +1,23 @@
package main
import (
"fmt"
"strings"
)
func rot13char(c rune) rune {
if c >= 'a' && c <= 'm' || c >= 'A' && c <= 'M' {
return c + 13
} else if c >= 'n' && c <= 'z' || c >= 'N' && c <= 'Z' {
return c - 13
}
return c
}
func rot13(s string) string {
return strings.Map(rot13char, s)
}
func main() {
fmt.Println(rot13("nowhere ABJURER"))
}

View file

@ -0,0 +1,32 @@
#!/usr/bin/env golosh
----
This module encrypts strings by rotating each character by 13.
----
module Rot13
augment java.lang.Character {
function rot13 = |this| -> match {
when this >= 'a' and this <= 'z' then charValue((this - 'a' + 13) % 26 + 'a')
when this >= 'A' and this <= 'Z' then charValue((this - 'A' + 13) % 26 + 'A')
otherwise this
}
}
augment java.lang.String {
function rot13 = |this| -> vector[this: charAt(i): rot13() foreach i in [0..this: length()]]: join("")
}
function main = |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")
foreach string in args {
print(string: rot13())
print(" ")
}
println("")
}

View file

@ -0,0 +1,12 @@
def rot13 = { String s ->
(s as List).collect { ch ->
switch (ch) {
case ('a'..'m') + ('A'..'M'):
return (((ch as char) + 13) as char)
case ('n'..'z') + ('N'..'Z'):
return (((ch as char) - 13) as char)
default:
return ch
}
}.inject ("") { string, ch -> string += ch}
}

View file

@ -0,0 +1 @@
println rot13("Noyr jnf V, 'rer V fnj Ryon.")

View file

@ -0,0 +1,11 @@
import Data.Char (chr, isAlpha, ord, toLower)
import Data.Bool (bool)
rot13 :: Char -> Char
rot13 c
| isAlpha c = chr $ bool (-) (+) ('m' >= toLower c) (ord c) 13
| otherwise = c
-- Simple test
main :: IO ()
main = print $ rot13 <$> "Abjurer nowhere"

View file

@ -0,0 +1,11 @@
import Data.Char (chr, isAlpha, ord, toLower)
import Data.Bool (bool)
rot13 :: Char -> Char
rot13 =
let rot = flip ((bool (-) (+) . ('m' >=) . toLower) <*> ord)
in (bool <*> chr . rot 13) <*> isAlpha
-- Simple test
main :: IO ()
main = print $ rot13 <$> "Abjurer nowhere"

View file

@ -0,0 +1,23 @@
import System.Environment
import System.IO
import System.Directory
import Control.Monad
hInteract :: (String -> String) -> Handle -> Handle -> IO ()
hInteract f hIn hOut =
hGetContents hIn >>= hPutStr hOut . f
processByTemp :: (Handle -> Handle -> IO ()) -> String -> IO ()
processByTemp f name = do
hIn <- openFile name ReadMode
let tmp = name ++ "$"
hOut <- openFile tmp WriteMode
f hIn hOut
hClose hIn
hClose hOut
removeFile name
renameFile tmp name
process :: (Handle -> Handle -> IO ()) -> [String] -> IO ()
process f [] = f stdin stdout
process f ns = mapM_ (processByTemp f) ns

View file

@ -0,0 +1,3 @@
main = do
names <- getArgs
process (hInteract (map rot13)) names

View file

@ -0,0 +1,16 @@
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

View file

@ -0,0 +1,20 @@
100 PROGRAM "Rot13.bas"
110 DO
120 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 ELSE
250 END SELECT
260 LET RESULT$=RESULT$&CH$
270 NEXT
280 LET ROT13$=RESULT$
290 END DEF

View file

@ -0,0 +1,14 @@
procedure main(arglist)
file := open(arglist[1],"r") | &input
every write(rot13(|read(file)))
end
procedure rot13(s) #: returns rot13(string)
static a,n
initial {
a := &lcase || &ucase
(&lcase || &lcase) ? n := ( move(13), move(*&lcase) )
(&ucase || &ucase) ? n ||:= ( move(13), move(*&ucase) )
}
return map(s,a,n)
end

1
Task/Rot-13/J/rot-13.j Normal file
View file

@ -0,0 +1 @@
rot13=: {&((65 97+/~i.2 13) |.@[} i.256)&.(a.&i.)

View file

@ -0,0 +1,18 @@
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."))
}

View file

@ -0,0 +1,33 @@
import java.io.*;
public class Rot13 {
public static void main(String[] args) throws IOException {
if (args.length >= 1) {
for (String file : args) {
try (InputStream in = new BufferedInputStream(new FileInputStream(file))) {
rot13(in, System.out);
}
}
} else {
rot13(System.in, System.out);
}
}
private static void rot13(InputStream in, OutputStream out) throws IOException {
int ch;
while ((ch = in.read()) != -1) {
out.write(rot13((char) ch));
}
}
private static char rot13(char ch) {
if (ch >= 'A' && ch <= 'Z') {
return (char) (((ch - 'A') + 13) % 26 + 'A');
}
if (ch >= 'a' && ch <= 'z') {
return (char) (((ch - 'a') + 13) % 26 + 'a');
}
return ch;
}
}

View file

@ -0,0 +1,6 @@
function rot13(c) {
return c.replace(/([a-m])|([n-z])/ig, function($0,$1,$2) {
return String.fromCharCode($1 ? $1.charCodeAt(0) + 13 : $2 ? $2.charCodeAt(0) - 13 : 0) || $0;
});
}
rot13("ABJURER nowhere") // NOWHERE abjurer

View file

@ -0,0 +1,59 @@
function rot13(value){
if (!value)
return "";
function singleChar(c) {
if (c.toUpperCase() < "A" || c.toUpperCase() > "Z")
return c;
if (c.toUpperCase() <= "M")
return String.fromCharCode(c.charCodeAt(0) + 13);
return String.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");
});
});

View file

@ -0,0 +1,19 @@
#!/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.
def rot13:
explode
| map( if 65 <= . and . <= 90 then ((. - 52) % 26) + 65
elif 97 <= . and . <= 122 then (. - 84) % 26 + 97
else .
end)
| implode;
rot13

View file

@ -0,0 +1,13 @@
#!/bin/bash
jq -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'

View file

@ -0,0 +1,41 @@
#!/usr/local/bin/jsish
/* ROT-13 in Jsish */
function rot13(msg:string) {
return msg.replace(/([a-m])|([n-z])/ig, function(m,p1,p2,ofs,str) {
return String.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 */
function processFile(fname:string) {
var str;
if (fname == "stdin") fname = "./stdin";
if (fname == "-") fname = "stdin";
var fin = new Channel(fname, 'r');
while (str = fin.gets()) puts(rot13(str));
fin.close();
}
if (console.args.length == 0) console.args.push('-');
for (var fn of console.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!=
*/

View file

@ -0,0 +1,7 @@
# Julia 1.0
function rot13(c::Char)
shft = islowercase(c) ? 'a' : 'A'
isletter(c) ? c = shft + (c - shft + 13) % 26 : c
end
rot13(str::AbstractString) = map(rot13, str)

View file

@ -0,0 +1 @@
replace("nowhere ABJURER", r"[A-Za-z]" => s -> map(c -> c + (uppercase(c) < 'N' ? 13 : -13), s))

4
Task/Rot-13/K/rot-13.k Normal file
View file

@ -0,0 +1,4 @@
rot13: {a:+65 97+\:2 13#!26;_ci@[!256;a;:;|a]_ic x}
rot13 "Testing! 1 2 3"
"Grfgvat! 1 2 3"

View file

@ -0,0 +1,19 @@
import java.io.*
fun String.rot13() = map {
when {
it.isUpperCase() -> { val x = it + 13; if (x > 'Z') x - 26 else x }
it.isLowerCase() -> { val x = it + 13; if (x > 'z') x - 26 else x }
else -> it
} }.toCharArray()
fun InputStreamReader.println() =
try { BufferedReader(this).forEachLine { println(it.rot13()) } }
catch (e: IOException) { e.printStackTrace() }
fun main(args: Array<String>) {
if (args.any())
args.forEach { FileReader(it).println() }
else
InputStreamReader(System.`in`).println()
}

View file

@ -0,0 +1,45 @@
#!/bin/ksh
# rot-13 function
# # Variables:
#
integer ROT_NUM=13 # Generalize to any ROT
string1="A2p" # Default "test"
string=${1:-${string1}} # Allow command line input
typeset -a lcalph=( 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 )
typeset -a ucalph=( 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 )
# # 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-alpha
typeset -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 _aplha
return
}
######
# main #
######
for ((i=0; i<${#string}; i++)); do
buff+=$(_rotN "${string:${i}:1}")
done
print "${string}"
print "${buff}"

Some files were not shown because too many files have changed in this diff Show more