@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


      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$


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


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"


#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;
}


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()));
        }
    }
}


#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;
}


(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!")


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


       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
           .


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


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


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
]


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));
}


program Rot13;

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

function Rot13char(c: AnsiChar): AnsiChar;
begin
  Result := c;
  if (c >= 'a') and (c <= 'm') or (c >= 'A') and (c <= 'M') then
    Result := AnsiChar(ord(c) + 13)
  else if (c >= 'n') and (c <= 'z') or (c >= 'N') and (c <= 'Z') then
    Result := AnsiChar(ord(c) - 13);

end;

function Rot13Fn(s: ansistring): ansistring;
begin
  SetLength(result, length(s));
  for var i := 1 to length(s) do
    Result[i] := Rot13char(s[i]);
end;

begin
  writeln(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()


rot-13:
	)
	for ch in chars swap:
		ord ch
		if <= 65 dup:
			if >= 90 dup:
				+ 13 - swap 65
				+ 65 % swap 26
		if <= 97 dup:
			if >= 122 dup:
				+ 13 - swap 97
				+ 97 % swap 26
		chr
	concat(

!print rot-13 "Snape kills Frodo with Rosebud."


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


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]))
    }
}


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)


(rot13-string "abc") ;=> "nop"
(with-temp-buffer
  (insert "abc")
  (rot13-region (point-min) (point-max))
  (buffer-string)) ;=> "nop"


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


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


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


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


#! /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


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)}")
    }
  }
}


#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


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


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


' 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


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


#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;


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"))
}


#!/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("")
}


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


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


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"


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


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


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


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;
    }
}


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


#!/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


#!/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!=
*/


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


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()
}


#!/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}"


F f(x)
   R x^3 - 3 * x^2 + 2 * x

-V step = 0.001
-V start = -1.0
-V stop = 3.0

V sgn = f(start) > 0
V x = start

L x <= stop
   V value = f(x)

   I value == 0
      print(‘Root found at ’x)
   E I (value > 0) != sgn
      print(‘Root found near ’x)

   sgn = value > 0
   x += step


// Extend the string type

define string->rot13 => {
    local(
        rot13 = bytes,
        i, a, b
    )

    with char in .eachCharacter
    let int = #char->integer
    do {
        // We only modify these ranges, set range if we should modify
        #int >= 65 and #int < 91  ? local(a=65,b=91)  |
        #int >= 97 and #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 character
        else
            #rot13->append(#char)       // just append the character
        }
    }

    return #rot13->asstring
}


input "Type some text to be encoded, then ENTER. ";tx$

tex$ = Rot13$(tx$)
print tex$
'check
print Rot13$(tex$)

wait

Function 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


with Ada.Text_Io; use Ada.Text_Io;

procedure Roots_Of_Function is
   package Real_Io is new Ada.Text_Io.Float_Io(Long_Float);
   use Real_Io;

   function F(X : Long_Float) return Long_Float is
   begin
      return (X**3 - 3.0*X*X + 2.0*X);
   end F;

   Step  : constant Long_Float := 1.0E-6;
   Start : constant Long_Float := -1.0;
   Stop  : constant Long_Float := 3.0;
   Value : Long_Float := F(Start);
   Sign  : Boolean := Value > 0.0;
   X     : Long_Float := Start + Step;

begin
   if Value = 0.0 then
      Put("Root found at ");
      Put(Item => Start, Fore => 1, Aft => 6, Exp => 0);
      New_Line;
   end if;
   while X <= Stop loop
      Value := F(X);
      if (Value > 0.0) /= Sign then
         Put("Root found near ");
         Put(Item => X, Fore => 1, Aft => 6, Exp => 0);
         New_Line;
      elsif Value = 0.0 then
         Put("Root found at ");
         Put(Item => X, Fore => 1, Aft => 6, Exp => 0);
         New_Line;
      end if;
      Sign := Value > 0.0;
      X := X + Step;
   end loop;
end Roots_Of_Function;


MODE DBL = LONG REAL;
FORMAT dbl = $g(-long real width, long real width-6, -2)$;

MODE XY = STRUCT(DBL x, y);
FORMAT xy root = $f(dbl)" ("b("Exactly", "Approximately")")"$;

MODE DBLOPT = UNION(DBL, VOID);
MODE XYRES = UNION(XY, VOID);

PROC find root = (PROC (DBL)DBL f, DBLOPT in x1, in x2, in x error, in y error)XYRES:(
  INT limit = ENTIER (long real width / log(2)); # worst case of a binary search) #
  DBL x1 := (in x1|(DBL x1):x1|-5.0), # if x1 is EMPTY then -5.0 #
      x2 := (in x2|(DBL x2):x2|+5.0),
      x error := (in x error|(DBL x error):x error|small real),
      y error := (in y error|(DBL y error):y error|small real);
  DBL y1 := f(x1), y2;
  DBL dx := x1 - x2, dy;

  IF y1 = 0 THEN
    XY(x1, y1) # we already have a solution! #
  ELSE
    FOR i WHILE
      y2 := f(x2);
      IF y2 = 0 THEN stop iteration FI;
      IF i = limit THEN value error FI;
      IF y1 = y2 THEN value error FI;
      dy := y1 - y2;
      dx := dx / dy * y2;
      x1 := x2; y1 := y2; # retain for next iteration #
      x2 -:= dx;
  # WHILE # ABS dx > x error AND ABS dy > y error DO
      SKIP
    OD;
    stop iteration:
      XY(x2, y2) EXIT
    value error:
      EMPTY
  FI
);

PROC f = (DBL x)DBL: x UP 3 - LONG 3.1 * x UP 2 + LONG 2.0 * x;

DBL first root, second root, third root;

XYRES first result = find root(f, LENG -1.0, LENG 3.0, EMPTY, EMPTY);
CASE first result IN
  (XY first result): (
    printf(($"1st root found at x = "f(xy root)l$, x OF first result, y OF first result=0));
    first root := x OF first result
  )
  OUT printf($"No first root found"l$); stop
ESAC;

XYRES second result = find root( (DBL x)DBL: f(x) / (x - first root), EMPTY, EMPTY, EMPTY, EMPTY);
CASE second result IN
  (XY second result): (
    printf(($"2nd root found at x = "f(xy root)l$, x OF second result, y OF second result=0));
    second root := x OF second result
  )
  OUT printf($"No second root found"l$); stop
ESAC;

XYRES third result = find root( (DBL x)DBL: f(x) / (x - first root) / ( x - second root ), EMPTY, EMPTY, EMPTY, EMPTY);
CASE third result IN
  (XY third result): (
    printf(($"3rd root found at x = "f(xy root)l$, x OF third result, y OF third result=0));
    third root := x OF third result
  )
  OUT printf($"No third root found"l$); stop
ESAC


implement Rot13;

include "sys.m"; sys: Sys;
include "draw.m";

Rot13: module
{
	init:	fn(ctxt: ref Draw->Context, argv: list of string);
};

stdout: ref Sys->FD;
tab: array of int;

init(nil: ref Draw->Context, args: list of string)
{
	sys = load Sys Sys->PATH;
	stdout = sys->fildes(1);
	inittab();
	args = tl args;
	if(args == nil)
		args = "-" :: nil;
	for(; args != nil; args = tl args){
		file := hd args;
		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);
		}else
			rot13cat(sys->fildes(0), "<stdin>");
	}
}

inittab()
{
	tab = array[256] of int;
	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 < len s; i++) {
		if(s[i] < 256)
			s[i] = tab[s[i]];
	}
	return s;
}

rot13cat(fd: ref Sys->FD, file: string)
{
	buf := array[Sys->ATOMICIO] of byte;

	while((n := sys->read(fd, buf, len buf)) > 0) {
		obuf := array of byte (rot13(string buf));
		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 S
end rot13


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


#include
"share/atspre_staload.hats"

typedef d = double

fun
findRoots
(
  start: d, stop: d, step: d, f: (d) -> d, nrts: int, A: d
) : void = (
//
if
start < stop
then let
  val A2 = f(start)
  var nrts: int = nrts
  val () =
  if A2 = 0.0
    then (
      nrts := nrts + 1;
      $extfcall(void, "printf", "An exact root is found at %12.9f\n", start)
    ) (* end of [then] *)
  // end of [if]
  val () =
  if A * A2 < 0.0
    then (
      nrts := nrts + 1;
      $extfcall(void, "printf", "An approximate root is found at %12.9f\n", start)
    ) (* end of [then] *)
  // end of [if]
in
  findRoots(start+step, stop, step, f, nrts, A2)
end // end of [then]
else (
  if nrts = 0
    then $extfcall(void, "printf", "There are no roots found!\n")
  // end of [if]
) (* end of [else] *)
//
) (* end of [findRoots] *)

(* ****** ****** *)

implement
main0 () =
findRoots (~1.0, 3.0, 0.001, lam (x) => x*x*x - 3.0*x*x + 2.0*x, 0, 0.0)


MsgBox % roots("poly", -0.99, 2, 0.1, 1.0e-5)
MsgBox % roots("poly", -1, 3, 0.1, 1.0e-5)

roots(f,x1,x2,step,tol) { ; search for roots in intervals of length "step", within tolerance "tol"
   x := x1, y := %f%(x), s := (y>0)-(y<0)
   Loop % ceil((x2-x1)/step) {
      x += step, y := %f%(x), t := (y>0)-(y<0)
      If (s=0 || s!=t)
         res .= root(f, x-step, x, tol) " [" ErrorLevel "]`n"
      s := t
   }
   Sort res, UN ; remove duplicate endpoints
   Return res
}

root(f,x1,x2,d) { ; find x in [x1,x2]: f(x)=0 within tolerance d, by bisection
   If (!y1 := %f%(x1))
      Return x1, ErrorLevel := "Exact"
   If (!y2 := %f%(x2))
      Return x2, ErrorLevel := "Exact"
   If (y1*y2>0)
      Return "", ErrorLevel := "Need different sign ends!"
   Loop {
      x := (x2+x1)/2, y := %f%(x)
      If (y = 0 || x2-x1 < d)
         Return x, ErrorLevel := y ? "Approximate" : "Exact"
      If ((y>0) = (y1>0))
         x1 := x, y1 := y
      Else
         x2 := x, y2 := y
   }
}

poly(x) {
   Return ((x-3)*x+2)*x
}


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 :c
end

print map "rot13 "|abjurer NOWHERE|
nowhere ABJURER


function rot13(s)
	local a = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
	local b = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm"
	return (s:gsub("%a", function(c) return b:sub(a:find(c)) end))
end


      function$ = "x^3-3*x^2+2*x"
      rangemin = -1
      rangemax = 3
      stepsize = 0.001
      accuracy = 1E-8
      PROCroots(function$, rangemin, rangemax, stepsize, accuracy)
      END

      DEF PROCroots(func$, min, max, inc, eps)
      LOCAL x, sign%, oldsign%
      oldsign% = 0
      FOR x = min TO max STEP inc
        sign% = SGN(EVAL(func$))
        IF sign% = 0 THEN
          PRINT "Root found at x = "; x
          sign% = -oldsign%
        ELSE IF sign% <> oldsign% AND oldsign% <> 0 THEN
            IF inc < eps THEN
              PRINT "Root found near x = "; x
            ELSE
              PROCroots(func$, x-inc, x+inc/8, inc/8, eps)
            ENDIF
          ENDIF
        ENDIF
        oldsign% = sign%
      NEXT x
      ENDPROC


#include <math.h>
#include <stdio.h>

double f(double x)
{
    return x*x*x-3.0*x*x +2.0*x;
}

double secant( double xA, double xB, double(*f)(double) )
{
    double e = 1.0e-12;
    double fA, fB;
    double d;
    int i;
    int limit = 50;

    fA=(*f)(xA);
    for (i=0; i<limit; i++) {
        fB=(*f)(xB);
        d = (xB - xA) / (fB - fA) * fB;
        if (fabs(d) < e)
            break;
        xA = xB;
        fA = fB;
        xB -= d;
    }
    if (i==limit) {
        printf("Function is not converging near (%7.4f,%7.4f).\n", xA,xB);
        return -99.0;
    }
    return xB;
}

int main(int argc, char *argv[])
{
    double step = 1.0e-2;
    double e = 1.0e-12;
    double x = -1.032;		// just so we use secant method
    double xx, value;

    int s = (f(x)> 0.0);

    while (x < 3.0) {
        value = f(x);
        if (fabs(value) < e) {
            printf("Root found at x= %12.9f\n", x);
            s = (f(x+.0001)>0.0);
        }
        else if ((value > 0.0) != s) {
            xx = secant(x-step, x,&f);
            if (xx != -99.0)   // -99 meaning secand method failed
                printf("Root found at x= %12.9f\n", xx);
            else
                printf("Root found near x= %7.4f\n", x);
            s = (f(x+.0001)>0.0);
        }
        x += step;
    }
    return 0;
}


using System;

class Program
{
    public static void Main(string[] args)
    {
        Func<double, double> f = x => { return x * x * x - 3 * x * x + 2 * x; };

        double step = 0.001; // Smaller step values produce more accurate and precise results
        double start = -1;
        double stop = 3;
        double value = f(start);
        int sign = (value > 0) ? 1 : 0;

        // Check for root at start
        if (value == 0)
            Console.WriteLine("Root found at {0}", start);

        for (var x = start + step; x <= stop; x += step)
        {
            value = f(x);

            if (((value > 0) ? 1 : 0) != sign)
                // We passed a root
                Console.WriteLine("Root found near {0}", x);
            else if (value == 0)
                // We hit a root
                Console.WriteLine("Root found at {0}", x);

            // Update our sign
            sign = (value > 0) ? 1 : 0;
        }
    }
}


#include <iostream>

double f(double x)
{
	return (x*x*x - 3*x*x + 2*x);
}

int main()
{
	double step = 0.001; // Smaller step values produce more accurate and precise results
	double start = -1;
	double stop = 3;
	double value = f(start);
	double sign = (value > 0);

	// Check for root at start
	if ( 0 == value )
		std::cout << "Root found at " << start << std::endl;

	for(	double x = start + step;
			x <= stop;
			x += step )
	{
		value = f(x);

		if ( ( value > 0 ) != sign )
			// We passed a root
			std::cout << "Root found near " << x << std::endl;
		else if ( 0 == value )
			// We hit a root
			std::cout << "Root found at " << x << std::endl;

		// Update our sign
		sign = ( value > 0 );
	}
}


> 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[%]


(defn findRoots [f start stop step eps]
      (filter #(-> (f %) Math/abs (< eps)) (range start stop step)))


print_roots = (f, begin, end, step) ->
  # Print approximate roots of f between x=begin and x=end,
  # using sign changes as an indicator that a root has been
  # encountered.
  x = begin
  y = f(x)
  last_y = y

  cross_x_axis = ->
    (last_y < 0 and y > 0) or (last_y > 0 and y < 0)

  console.log '-----'
  while x <= end
    y = f(x)
    if y == 0
      console.log "Root found at", x
    else if cross_x_axis()
      console.log "Root found near", x
    x += step
    last_y = y

do ->
  # Smaller steps produce more accurate/precise results in general,
  # but for many functions we'll never get exact roots, either due
  # to imperfect binary representation or irrational roots.
  step = 1 / 256

  f1 = (x) -> x*x*x - 3*x*x + 2*x
  print_roots f1, -1, 5, step
  f2 = (x) -> x*x - 4*x + 3
  print_roots f2, -1, 5, step
  f3 = (x) -> x - 1.5
  print_roots f3, 0, 4, step
  f4 = (x) -> x*x - 2
  print_roots f4, -2, 2, step


function r=rot13(s)
    if ischar(s)
        r=s;  % preallocation and copy of non-letters
        for i=1:size(s,1)
            for j=1:size(s,2)
                if isletter(s(i,j))
                    if s(i,j)>=97   % lower case
                        base = 97;
                    else            % upper case
                        base = 65;
                    end
                    r(i,j)=char(mod(s(i,j)-base+13,26)+base);
                end
            end
        end
    else
        error('Argument must be a CHAR')
    end
end


rot13(a) := simplode(map(ascii, map(lambda([n],
      if (n >= 65 and n <= 77) or (n >= 97 and n <= 109) then n + 13
      elseif (n >= 78 and n <= 90) or (n >= 110 and n <= 122) then n - 13
      else n), 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"


(defun find-roots (function start end &optional (step 0.0001))
  (let* ((roots '())
         (value (funcall function start))
         (plusp (plusp value)))
    (when (zerop value)
      (format t "~&Root found at ~W." start))
    (do ((x (+ start step) (+ x step)))
        ((> x end) (nreverse roots))
      (setf value (funcall function x))
      (cond
       ((zerop value)
        (format t "~&Root found at ~w." x)
        (push x roots))
       ((not (eql plusp (plusp value)))
        (format t "~&Root found near ~w." x)
        (push (cons (- x step) x) roots)))
      (setf plusp (plusp value)))))


import std.stdio, std.math, std.algorithm;

bool nearZero(T)(in T a, in T b = T.epsilon * 4) pure nothrow {
    return abs(a) <= b;
}

T[] findRoot(T)(immutable T function(in T) pure nothrow fi,
                in T start, in T end, in T step=T(0.001L),
                T tolerance = T(1e-4L)) {
    if (step.nearZero)
        writefln("WARNING: step size may be too small.");

    /// Search root by simple bisection.
    T searchRoot(T a, T b) pure nothrow {
        T root;
        int limit = 49;
        T gap = b - a;

        while (!nearZero(gap) && limit--) {
            if (fi(a).nearZero)
                return a;
            if (fi(b).nearZero)
                return b;
            root = (b + a) / 2.0L;
            if (fi(root).nearZero)
                return root;
            ((fi(a) * fi(root) < 0) ? b : a) = root;
            gap = b - a;
        }

        return root;
    }

    immutable dir = T(end > start ? 1.0 : -1.0);
    immutable step2 = (end > start) ? abs(step) : -abs(step);
    T[T] result;
    for (T x = start; (x * dir) <= (end * dir); x += step2)
        if (fi(x) * fi(x + step2) <= 0) {
            immutable T r = searchRoot(x, x + step2);
            result[r] = fi(r);
        }

    return result.keys.sort().release;
}

void report(T)(in T[] r, immutable T function(in T) pure f,
               in T tolerance = T(1e-4L)) {
    if (r.length) {
        writefln("Root found (tolerance = %1.4g):", tolerance);

        foreach (const x; r) {
            immutable T y = f(x);

            if (nearZero(y))
                writefln("... EXACTLY at %+1.20f, f(x) = %+1.4g",x,y);
            else if (nearZero(y, tolerance))
                writefln(".... MAY-BE at %+1.20f, f(x) = %+1.4g",x,y);
            else
                writefln("Verify needed, f(%1.4g) = " ~
                         "%1.4g > tolerance in magnitude", x, y);
        }
    } else
        writefln("No root found.");
}

void main() {
    static real f(in real x) pure nothrow {
        return x ^^ 3 - (3 * x ^^ 2) + 2 * x;
    }

    findRoot(&f, -1.0L, 3.0L, 0.001L).report(&f);
}


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


rot13 = function(s)
    chars = s.values
    for i in chars.indexes
        c = chars[i]
        if c >= "a" and c <= "z" then chars[i] = char(97 + (code(c)-97+13)%26)
        if c >= "A" and c <= "Z" then chars[i] = char(65 + (code(c)-65+13)%26)
    end for
    return chars.join("")
end function

print rot13("Hello world!")
print rot13("Uryyb jbeyq!")


double fn(double x) => x * x * x - 3 * x * x + 2 * x;

findRoots(Function(double) f, double start, double stop, double step, double epsilon) sync* {
  for (double x = start; x < stop; x = x + step) {
    if (fn(x).abs() < epsilon) yield x;
  }
}

main() {
  // Vector(-9.381755897326649E-14, 0.9999999999998124, 1.9999999999997022)
  print(findRoots(fn, -1.0, 3.0, 0.0001, 0.000000001));
}


type TFunc = function (x : Float) : Float;

function f(x : Float) : Float;
begin
   Result := x*x*x-3.0*x*x +2.0*x;
end;

const e = 1.0e-12;

function Secant(xA, xB : Float; f : TFunc) : Float;
const
   limit = 50;
var
   fA, fB : Float;
   d : Float;
   i : Integer;
begin
   fA := f(xA);
   for i := 0 to limit do begin
      fB := f(xB);
      d := (xB-xA)/(fB-fA)*fB;
      if Abs(d) < e then
         Exit(xB);
      xA := xB;
      fA := fB;
      xB -= d;
   end;
   PrintLn(Format('Function is not converging near (%7.4f,%7.4f).', [xA, xB]));
   Result := -99.0;
end;

const fstep = 1.0e-2;

var x := -1.032;		// just so we use secant method
var xx, value : Float;
var s := f(x)>0.0;

while (x < 3.0) do begin
   value := f(x);
   if Abs(value)<e then begin
      PrintLn(Format("Root found at x= %12.9f", [x]));
      s := (f(x+0.0001)>0.0);
   end else if (value>0.0) <> s then begin
      xx := Secant(x-fstep, x, f);
      if xx <> -99.0 then   // -99 meaning secand method failed
         PrintLn(Format('Root found at x = %12.9f', [xx]))
      else PrintLn(Format('Root found near x= %7.4f', [xx]));
      s := (f(x+0.0001)>0.0);
   end;
   x += fstep;
end;


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
    result
end

puts 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
    c

val rot13 = String.map rot13char


// main registers
p	IS	$255	% text pointer
c	GREG		% char
cc	GREG		% uppercase copy of c
u	GREG		% all purpose

	LOC	Data_Segment
	GREG	@
Test	BYTE	"dit is een bericht voor de keizer",#a,0

	LOC	#100
Main	LDA	p,Test
	TRAP	0,Fputs,StdOut	% show text to encrypt
	LDA	p,Test		% points to text to encrypt
	JMP	4F
// do in place text encryption
				% REPEAT
2H	ADD	cc,c,0		%  copy char
	SUB	cc,cc,' '	%  make uppercase
	CMP	u,cc,'A'
	BN	u,3F		%  IF c < 'A' OR c > 'Z' THEN next char
	CMP	u,cc,'Z'
	BP	u,3F
	CMP	u,cc,'N'	%  ELSE
	BN	u,1F		%    IF c < 'N' THEN encrypt 'up'
	SUB	c,c,26		%    ELSE char ready for encrypt 'down'
1H	INCL	c,13		%  encrypt char
	STBU	c,p		%  replace char with encrypted char
3H	INCL	p,1		%  move to next char
4H	LDBU	c,p		%  get next char
	PBNZ	c,2B		% UNTIL EOT
// print result
	LDA	p,Test
	TRAP	0,Fputs,StdOut	% show encrypted text
	TRAP	0,Halt,0


defmodule RC do
  def find_roots(f, range, step \\ 0.001) do
    first .. last = range
    max = last + step / 2
    Stream.iterate(first, &(&1 + step))
    |> Stream.take_while(&(&1 < max))
    |> Enum.reduce(sign(first), fn x,sn ->
         value = f.(x)
         cond do
           abs(value) < step / 100 ->
             IO.puts "Root found at #{x}"
             0
           sign(value) == -sn ->
             IO.puts "Root found between #{x-step} and #{x}"
             -sn
           true -> sign(value)
         end
       end)
  end

  defp sign(x) when x>0, do: 1
  defp sign(x) when x<0, do: -1
  defp sign(0)         , do: 0
end

f = fn x -> x*x*x - 3*x*x + 2*x end
RC.find_roots(f, -1..3)


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.


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.


% Implemented by Arjun Sunel
-module(roots).
-export([main/0]).
main() ->
	F = fun(X)->X*X*X - 3*X*X + 2*X end,
	Step = 0.001,	 % Using smaller steps will provide more accurate results
	Start = -1,
	Stop = 3,
	Sign = F(Start) > 0,
	X = Start,
	while(X, Step, Start, Stop, Sign,F).

while(X, Step, Start, Stop, Sign,F) ->
	Value = F(X),
	if
		Value == 0  ->		% We hit a root
        	io:format("Root found at ~p~n",[X]),
        	while(X+Step, Step, Start, Stop,  Value > 0,F);

		(Value < 0) == Sign ->	% We passed a root
		io:format("Root found near ~p~n",[X]),
		while(X+Step , Step, Start, Stop,  Value > 0,F);

		 X > Stop ->
		 	io:format("") ;
		true ->
        	while(X+Step, Step, Start, Stop,  Value > 0,F)
	end.


Rot13(in)	New low,rot,up
	Set 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 plaintext
		if uppercase .contains. char
			cypher += uppercase[uppercase[char] - 13]
		else if lowercase .contains. char
			cypher += lowercase[lowercase[char] - 13]
		else
			cypher += char
		end
	end

	return cypher
end


PROGRAM ROOTS_FUNCTION

!VAR E,X,STP,VALUE,S%,I%,LIMIT%,X1,X2,D

FUNCTION F(X)
    F=X*X*X-3*X*X+2*X
END FUNCTION

BEGIN
  X=-1
  STP=1.0E-6
  E=1.0E-9
  S%=(F(X)>0)

  PRINT("VERSION 1: SIMPLY STEPPING X")
  WHILE X<3.0 DO
    VALUE=F(X)
    IF ABS(VALUE)<E THEN
        PRINT("ROOT FOUND AT X =";X)
        S%=NOT S%
      ELSE
        IF ((VALUE>0)<>S%) THEN
          PRINT("ROOT FOUND AT X =";X)
          S%=NOT S%
        END IF
    END IF
    X=X+STP
  END WHILE

  PRINT
  PRINT("VERSION 2: SECANT METHOD")
  X1=-1.0
  X2=3.0
  E=1.0E-15
  I%=1
  LIMIT%=300
  LOOP
    IF I%>LIMIT% THEN
       PRINT("ERROR: FUNCTION NOT CONVERGING")
       EXIT
    END IF
    D=(X2-X1)/(F(X2)-F(X1))*F(X2)
    IF ABS(D)<E THEN
      IF D=0 THEN
         PRINT("EXACT ";)
       ELSE
         PRINT("APPROXIMATE ";)
      END IF
      PRINT("ROOT FOUND AT X =";X2)
      EXIT
    END IF
    X1=X2
    X2=X2-D
    I%=I%+1
  END LOOP
END PROGRAM


PROGRAM ROOTS_OF_A_FUNCTION

  IMPLICIT NONE

  INTEGER, PARAMETER :: dp = SELECTED_REAL_KIND(15)
  REAL(dp) :: f, e, x, step, value
  LOGICAL :: s

  f(x) = x*x*x - 3.0_dp*x*x + 2.0_dp*x

  x = -1.0_dp ; step = 1.0e-6_dp ; e = 1.0e-9_dp

  s = (f(x) > 0)
  DO WHILE (x < 3.0)
    value = f(x)
    IF(ABS(value) < e) THEN
      WRITE(*,"(A,F12.9)") "Root found at x =", x
      s = .NOT. s
    ELSE IF ((value > 0) .NEQV. s) THEN
      WRITE(*,"(A,F12.9)") "Root found near x = ", x
      s = .NOT. s
    END IF
    x = x + step
  END DO

END PROGRAM ROOTS_OF_A_FUNCTION


/*
 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")


#Include "crt.bi"
const iterations=20000000

sub bisect( f1 as function(as double) as double,min as double,max as double,byref O as double,a() as double)
    dim as double last,st=(max-min)/iterations,v
    for n as double=min to max step st
        v=f1(n)
        if sgn(v)<>sgn(last) then
            redim preserve a(1 to ubound(a)+1)
            a(ubound(a))=n
            O=n+st:exit sub
        end if
        last=v
    next
end sub

function roots(f1 as function(as double) as double,min as double,max as double, a() as double) as long
    redim a(0)
    dim as double last,O,st=(max-min)/iterations,v
    for n as double=min to max step st
        v=f1(n)
        if sgn(v)<>sgn(last) and n>min then bisect(f1,n-st,n,O,a()):n=O
        last=v
    next
    return ubound(a)
end function

Function CRound(Byval x As Double,Byval precision As Integer=30) As String
    If precision>30 Then precision=30
    Dim As zstring * 40 z:Var s="%." &str(Abs(precision)) &"f"
    sprintf(z,s,x)
    If Val(z) Then Return Rtrim(Rtrim(z,"0"),".")Else Return "0"
End Function

function defn(x as double) as double
    return x^3-3*x^2+2*x
end function

redim as double r()

print
if roots(@defn,-20,20,r()) then
    print "in range -20 to 20"
    print "All roots approximate"
    print "number","root to 6 dec places","function value at root"
    for n as long=1 to ubound(r)
        print n,CRound(r(n),6),,defn(r(n))
    next n
end if
sleep


/* NetRexx */
options replace format comments java crossref savelog symbols nobinary

parse arg fileNames

rdr = BufferedReader

do
  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)
    end
catch ex = IOException
  ex.printStackTrace
end

return

method 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_
  return

method 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 cipher

method 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


package main

import (
	"fmt"
	"math"
)

func main() {
	example := func(x float64) float64 { return x*x*x - 3*x*x + 2*x }
	findroots(example, -.5, 2.6, 1)
}

func findroots(f func(float64) float64, lower, upper, step float64) {
	for x0, x1 := lower, lower+step; x0 < upper; x0, x1 = x1, x1+step {
		x1 = math.Min(x1, upper)
		r, status := secant(f, x0, x1)
		if status != "" && r >= x0 && r < x1 {
			fmt.Printf("  %6.3f %s\n", r, status)
		}
	}
}

func secant(f func(float64) float64, x0, x1 float64) (float64, string) {
	var f0 float64
	f1 := f(x0)
	for i := 0; i < 100; i++ {
		f0, f1 = f1, f(x1)
		switch {
		case f1 == 0:
			return x1, "exact"
		case math.Abs(x1-x0) < 1e-6:
			return x1, "approximate"
		}
		x0, x1 = x1, x1-f1*(x1-x0)/(f1-f0)
	}
	return 0, ""
}


(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 strutils

proc rot13(c: char): char =
  case toLowerAscii(c)
  of 'a'..'m': chr(ord(c) + 13)
  of 'n'..'z': chr(ord(c) - 13)
  else:        c

for line in stdin.lines:
  for c in line:
    stdout.write rot13(c)
  stdout.write "\n"


f x = x^3-3*x^2+2*x

findRoots start stop step eps =
  [x | x <- [start, start+step .. stop], abs (f x) < eps]


OPEN(FIle='test.txt')

1 DLG(NameEdit=x0, DNum=3)

x = x0
chi2 = SOLVE(NUL=x^3 - 3*x^2 + 2*x, Unknown=x, I=iterations, NumDiff=1E-15)
EDIT(Text='approximate exact ', Word=(chi2 == 0), Parse=solution)

WRITE(FIle='test.txt', LENgth=6, Name) x0, x, solution, chi2, iterations
GOTO 1


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;
    }
  }
}


procedure main()
    showRoots(f, -1.0, 4, 0.002)
end

procedure f(x)
    return x^3 - 3*x^2 + 2*x
end

procedure showRoots(f, lb, ub, step)
    ox := x := lb
    oy := f(x)
    os := sign(oy)
    while x <= ub do {
        if (s := sign(y := f(x))) = 0 then write(x)
        else if s ~= os then {
            dx := x-ox
            dy := y-oy
            cx := x-dx*(y/dy)
            write("~",cx)
            }
        (ox := x, oy := y, os := s)
        x +:= step
        }
end

procedure sign(x)
    return (x<0, -1) | (x>0, 1) | 0
end


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


: encryptRot13(c)
   c dup isLetter ifFalse: [ return ]
   isUpper ifTrue: [ 'A' ] else: [ 'a' ] c 13 + over - 26 mod + ;

: rot13   map(#encryptRot13) charsAsString ;


public class Roots {
    public interface Function {
	public double f(double x);
    }

    private static int sign(double x) {
	return (x < 0.0) ? -1 : (x > 0.0) ? 1 : 0;
    }

    public static void printRoots(Function f, double lowerBound,
				  double upperBound, double step) {
	double x = lowerBound, ox = x;
	double y = f.f(x), oy = y;
	int s = sign(y), os = s;

	for (; x <= upperBound ; x += step) {
	    s = sign(y = f.f(x));
	    if (s == 0) {
		System.out.println(x);
	    } else if (s != os) {
		double dx = x - ox;
		double dy = y - oy;
		double cx = x - dx * (y / dy);
		System.out.println("~" + cx);
	    }
	    ox = x; oy = y; os = s;
	}
    }

    public static void main(String[] args) {
	Function poly = new Function () {
	    public double f(double x) {
		return x*x*x - 3*x*x + 2*x;
	    }
	};
	printRoots(poly, -1.0, 4, 0.002);
    }
}


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


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}
  end
in
  {System.showInfo {Rot13 "NOWHERE Abjurer 42"}}
  {System.showInfo {Rot13 {Rot13 "NOWHERE Abjurer 42"}}}


// This function notation is sorta new, but useful here
// Part of the EcmaScript 6 Draft
// developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope
var poly = (x => x*x*x - 3*x*x + 2*x);

function sign(x) {
	return (x < 0.0) ? -1 : (x > 0.0) ? 1 : 0;
}

function printRoots(f, lowerBound, upperBound, step) {
	var  x = lowerBound, ox = x,
		 y = f(x), oy = y,
		 s = sign(y), os = s;

	for (; x <= upperBound ; x += step) {
	    s = sign(y = f(x));
	    if (s == 0) {
			console.log(x);
	    }
	    else if (s != os) {
			var dx = x - ox;
			var dy = y - oy;
			var cx = x - dx * (y / dy);
			console.log("~" + cx);
	    }
	    ox = x; oy = y; os = s;
	}
}

printRoots(poly, -1.0, 4, 0.002);


def sign:
  if . < 0 then -1 elif . > 0 then 1 else 0 end;

def printRoots(f; lowerBound; upperBound; step):
 lowerBound as $x
 | ($x|f) as $y
 | ($y|sign) as $s
 | reduce range($x; upperBound+step; step) as $x
   # state: [ox, oy, os, roots]
   ( [$x, $y, $s, [] ];
     .[0] as $ox | .[1] as $oy | .[2] as $os
     | ($x|f) as $y
     | ($y | sign) as $s
     | if $s == 0 then  [$x, $y, $s, (.[3] + [$x] )]
       elif $s != $os and $os != 0 then
	  ($x - $ox) as $dx
          | ($y - $oy) as $dy
    	  | ($x - ($dx *  $y / $dy)) as $cx       # by geometry
          | [$x, $y, $s, (.[3] + [ "~\($cx)" ])]  # an approximation
       else [$x, $y, $s, .[3] ]
       end )
  | .[3] ;


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.


using Roots

println(find_zero(x -> x^3 - 3x^2 + 2x, (-100, 100)))


// version 1.1.2

typealias DoubleToDouble = (Double) -> Double

fun f(x: Double) = x * x * x - 3.0 * x * x + 2.0 * x

fun secant(x1: Double, x2: Double, f: DoubleToDouble): Double {
    val e = 1.0e-12
    val limit = 50
    var xa = x1
    var xb = x2
    var fa = f(xa)
    var  i = 0
    while (i++ < limit) {
        var fb = f(xb)
        val d = (xb - xa) / (fb - fa) * fb
        if (Math.abs(d) < e) break
        xa = xb
        fa = fb
        xb -= d
    }
    if (i == limit) {
        println("Function is not converging near (${"%7.4f".format(xa)}, ${"%7.4f".format(xb)}).")
        return -99.0
    }
    return xb
}

fun main(args: Array<String>) {
    val step = 1.0e-2
    val e = 1.0e-12
    var x = -1.032
    var s = f(x) > 0.0
    while (x < 3.0) {
        val value = f(x)
        if (Math.abs(value) < e) {
            println("Root found at x = ${"%12.9f".format(x)}")
            s = f(x + 0.0001) > 0.0
        }
        else if ((value > 0.0) != s) {
            val xx = secant(x - step, x, ::f)
            if (xx != -99.0)
                println("Root found at x = ${"%12.9f".format(xx)}")
            else
                println("Root found near x = ${"%7.4f".format(x)}")
            s = f(x + 0.0001) > 0.0
        }
        x += step
    }
}


sub rot13 {
  shift =~ tr/A-Za-z/N-ZA-Mn-za-m/r;
}

print rot13($_) while (<>);


function rot13(string s)
integer ch
    for i=1 to length(s) do
        ch = upper(s[i])
        if ch>='A' and ch<='Z' then
            s[i] += iff(ch<='M',+13,-13)
        end if
    end for
    return s
end function
?rot13("abjurer NOWHERE.")


1) defining the function:
{def func {lambda {:x} {+ {* 1 :x :x :x} {* -3 :x :x} {* 2 :x}}}}
-> func

2) printing roots:
{S.map {lambda {:x}
               {if {< {abs {func :x}} 0.0001}
                then {br}- a root found at :x else}}
       {S.serie -1 3 0.01}}
->
- a root found at 7.528699885739343e-16
- a root found at 1.0000000000000013
- a root found at 2.000000000000002

3) printing the roots of the "sin" function between -720° to +720°;

{S.map {lambda {:x}
               {if {< {abs {sin {* {/ {PI} 180} :x}}} 0.01}
                then {br}- a root found at :x° else}}
       {S.serie -720 +720 10}}
->
- a root found at -720°
- a root found at -540°
- a root found at -360°
- a root found at -180°
- a root found at 0°
- a root found at 180°
- a root found at 360°
- a root found at 540°
- a root found at 720°


'   Finds and output the roots of a given function f(x),
'       within a range of x values.

'   [RC]Roots of an function

    mainwin 80 12

    xMin  =-1
    xMax  = 3
    y     =f( xMin) '   Since Liberty BASIC has an 'eval(' function the fn
    '                       and limits would be better entered via 'input'.
    LastY =y

    eps  =1E-12 '   closeness acceptable

    bigH=0.01

    print
    print " Checking for roots of x^3 -3 *x^2 +2 *x =0 over range -1 to +3"
    print

    x=xMin: dx = bigH
    do
        x=x+dx
        y = f(x)
        'print x, dx, y
        if y*LastY <0 then 'there is a root, should drill deeper
            if dx < eps then    'we are close enough
                print " Just crossed axis, solution f( x) ="; y; " at x ="; using( "#.#####", x)
                LastY = y
                dx = bigH   'after closing on root, continue with big step
            else
                x=x-dx  'step back
                dx = dx/10  'repeat with smaller step
            end if
        end if
    loop while x<xMax

    print
    print " Finished checking in range specified."

    end

    function f( x)
        f =x^3 -3 *x^2 +2 *x
    end function


go =>
  S = "Big fjords vex quick waltz nymph!",
  println(S),
  println(rot13(S)),
  println(rot13(rot13(S))),
  nl.

% Rot 13 using a map
rot13(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").


(de rot13-Ch (C)
   (if
      (or
         (member C '`(apply circ (chop "ABCDEFGHIJKLMNOPQRSTUVWXYZ")))
         (member C '`(apply circ (chop "abcdefghijklmnopqrstuvwxyz"))) )
      (get @ 14)
      C ) )


-- Function to have roots found
function f (x) return x^3 - 3*x^2 + 2*x end

-- Find roots of f within x=[start, stop] or approximations thereof
function root (f, start, stop, step)
    local roots, x, sign, foundExact, value = {}, start, f(start) > 0
    while x <= stop do
        value = f(x)
        if value == 0 then
            table.insert(roots, {val = x, err = 0})
            foundExact = true
        end
        if value > 0 ~= sign then
            if foundExact then
                foundExact = false
            else
                table.insert(roots, {val = x, err = step})
            end
        end
        sign = value > 0
        x = x + step
    end
    return roots
end

-- Main procedure
print("Root (to 12DP)\tMax. Error\n")
for _, r in pairs(root(f, -1, 3, 10^-6)) do
    print(string.format("%0.12f", r.val), r.err)
end


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;


import math
import strformat

func f(x: float): float = x ^ 3 - 3 * x ^ 2 + 2 * x

var
  step = 0.01
  start = -1.0
  stop = 3.0
  sign = f(start) > 0
  x = start

while x <= stop:
  var value = f(x)

  if value == 0:
    echo fmt"Root found at {x:.5f}"
  elif (value > 0) != sign:
    echo fmt"Root found near {x:.5f}"

  sign = value > 0
  x += step


-- 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;
/


bundle Default {
  class Roots {
    function : f(x : Float) ~ Float
    {
      return (x*x*x - 3.0*x*x + 2.0*x);
    }

    function : Main(args : String[]) ~ Nil
    {
      step := 0.001;
      start := -1.0;
      stop := 3.0;
      value := f(start);
      sign := (value > 0);

      if(0.0 = value) {
        start->PrintLine();
      };

      for(x := start + step; x <= stop;  x += step;)  {
        value := f(x);

        if((value > 0) <> sign) {
          IO.Console->Instance()->Print("~")->PrintLine(x);
        }
        else if(0 = value) {
          IO.Console->Instance()->Print("~")->PrintLine(x);
        };

        sign := (value > 0);
      };
    }
  }
}


let bracket u v =
  ((u > 0.0) && (v < 0.0)) || ((u < 0.0) && (v > 0.0));;

let xtol a b = (a = b);; (* or use |a-b| < epsilon *)

let rec regula_falsi a b fa fb f =
  if xtol a b then (a, fa) else
  let c = (fb*.a -. fa*.b) /. (fb -. fa) in
  let fc = f c in
  if fc = 0.0 then (c, fc) else
  if bracket fa fc then
    regula_falsi a c fa fc f
  else
    regula_falsi c b fc fb f;;

let search lo hi step f =
  let rec next x fx =
    if x > hi then [] else
      let y = x +. step in
      let fy = f y in
      if fx = 0.0 then
        (x,fx) :: next y fy
      else if bracket fx fy then
        (regula_falsi x y fx fy f) :: next y fy
      else
        next y fy in
  next lo (f lo);;

let showroot (x,fx) =
  Printf.printf "f(%.17f) = %.17f [%s]\n"
    x fx (if fx = 0.0 then "exact" else "approx") in
let f x = ((x -. 3.0)*.x +. 2.0)*.x  in
List.iter showroot (search (-5.0) 5.0 0.1 f);;


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') =>


a = [ 1, -3, 2, 0 ];
r = roots(a);
% let's print it
for i = 1:3
  n = polyval(a, r(i));
  printf("x%d = %f (%f", i, r(i), n);
  if (n != 0.0)
    printf(" not");
  endif
  printf(" exact)\n");
endfor


: findRoots(f, a, b, st)
| x y lasty |
   a f perform dup ->y ->lasty

   a b st step: x [
      x f perform -> y
      y ==0 ifTrue: [ System.Out "Root found at " << x << cr ]
      else: [ y lasty * sgn -1 == ifTrue: [ System.Out "Root near " << x << cr ] ]
      y ->lasty
      ] ;

: f(x)   x 3 pow x sq 3 * - x 2 * + ;


#COMPILE EXE
#COMPILER PBWIN 9.05
#DIM ALL

FUNCTION 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
  LOOP
FUNCTION = res
END FUNCTION

'testing:

FUNCTION PBMAIN () AS LONG
#DEBUG PRINT ROT13("abc")
#DEBUG PRINT ROT13("nop")
END FUNCTION


/* REXX  program to solve a cubic polynom equation
a*x**3+b*x**2+c*x+d =(x-x1)*(x-x2)*(x-x3)
*/
Numeric Digits 16
pi3=Rxcalcpi()/3
Parse Value '1 -3 2 0' with a b c d
p=3*a*c-b**2
q=2*b**3-9*a*b*c+27*a**2*d
det=q**2+4*p**3
say 'p='p
say 'q='q
Say 'det='det
If det<0 Then Do
  phi=Rxcalcarccos(-q/(2*rxCalcsqrt(-p**3)),16,'R')
  Say 'phi='phi
  phi3=phi/3
  y1=rxCalcsqrt(-p)*2*Rxcalccos(phi3,16,'R')
  y2=rxCalcsqrt(-p)*2*Rxcalccos(phi3+2*pi3,16,'R')
  y3=rxCalcsqrt(-p)*2*Rxcalccos(phi3+4*pi3,16,'R')
  End
Else Do
  t=q**2+4*p**3
  tu=-4*q+4*rxCalcsqrt(t)
  tv=-4*q-4*rxCalcsqrt(t)
  u=qroot(tu)/2
  v=qroot(tv)/2
  y1=u+v
  y2=-(u+v)/2 (u+v)/2*rxCalcsqrt(3)
  y3=-(u+v)/2 (-(u+v)/2*rxCalcsqrt(3))
  End
say 'y1='y1
say 'y2='y2
say 'y3='y3
x1=y2x(y1)
x2=y2x(y2)
x3=y2x(y3)
Say 'x1='x1
Say 'x2='x2
Say 'x3='x3
Exit

qroot: Procedure
Parse Arg a
return sign(a)*rxcalcpower(abs(a),1/3,16)

y2x: Procedure Expose a b
Parse Arg real imag
xr=(real-b)/(3*a)
If imag<>'' Then Do
  xi=(imag-b)/(3*a)
  Return xr xi'i'
  End
Else
  Return xr
::requires 'rxmath' LIBRARY


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


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()
EndIf

Procedure.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 u
EndProcedure


Program RootsFunction;

var
  e, x, step, value: double;
  s: boolean;
  i, limit: integer;
  x1, x2, d: double;

function f(const x: double): double;
  begin
    f := x*x*x - 3*x*x + 2*x;
  end;

begin
  x    := -1;
  step := 1.0e-6;
  e    := 1.0e-9;
  s    := (f(x) > 0);

  writeln('Version 1: simply stepping x:');
  while x < 3.0 do
  begin
    value := f(x);
    if abs(value) < e then
    begin
      writeln ('root found at x = ', x);
      s := not s;
    end
    else if ((value > 0) <> s) then
    begin
      writeln ('root found at x = ', x);
      s := not s;
    end;
    x := x + step;
  end;

  writeln('Version 2: secant method:');
  x1 := -1.0;
  x2 :=  3.0;
  e  :=  1.0e-15;
  i  :=  1;
  limit := 300;
  while true do
  begin
    if i > limit then
    begin
      writeln('Error: function not converging');
      exit;
    end;
    d := (x2 - x1) / (f(x2) - f(x1)) * f(x2);
    if abs(d) < e then
    begin
      if d = 0 then
        write('Exact ')
      else
        write('Approximate ');
      writeln('root found at x = ', x2);
      exit;
    end;
    x1 := x2;
    x2 := x2 - d;
    i  := i + 1;
  end;
end.


>>> u'foo'.encode('rot13')
'sbb'
>>> 'sbb'.decode('rot13')
u'foo'


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$
    NEXT
END FUNCTION


sub f
{
        my $x = shift;

        return ($x * $x * $x - 3*$x*$x + 2*$x);
}

my $step = 0.001; # Smaller step values produce more accurate and precise results
my $start = -1;
my $stop = 3;
my $value = &f($start);
my $sign = $value > 0;

# Check for root at start

print "Root found at $start\n" if ( 0 == $value );

for(    my $x = $start + $step;
        $x <= $stop;
        $x += $step )
{
        $value = &f($x);

        if ( 0 == $value )
        {
                # We hit a root
                print "Root found at $x\n";
        }
        elsif ( ( $value > 0 ) != $sign )
        {
                # We passed a root
                print "Root found near $x\n";
        }

        # Update our sign
        $sign = ( $value > 0 );
}


procedure print_roots(integer f, atom start, stop, step)
    --
    -- Print approximate roots of f between x=start and x=stop, using
    --  sign changes as an indicator that a root has been encountered.
    --
    atom x = start, y = 0
    puts(1,"-----\n")
    while x<=stop do
        atom last_y = y
        y = f(x)
        if y=0
        or (last_y<0 and y>0)
        or (last_y>0 and y<0) then
            printf(1,"Root found %s %.10g\n", {iff(y=0?"at":"near"),x})
        end if
        x += step
    end while
end procedure

-- Smaller steps produce more accurate/precise results in general,
-- but for many functions we'll never get exact roots, either due
-- to imperfect binary representation or irrational roots.
constant step = 1/256

function f1(atom x) return x*x*x-3*x*x+2*x  end function
function f2(atom x) return x*x-4*x+3        end function
function f3(atom x) return x-1.5            end function
function f4(atom x) return x*x-2            end function

print_roots(f1, -1, 5, step)
print_roots(f2, -1, 5, step)
print_roots(f3,  0, 4, step)
print_roots(f4, -2, 2, step)


[ $ "" 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 ( $ --> $ )


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"


(de findRoots (F Start Stop Step Eps)
   (filter
      '((N) (> Eps (abs (F N))))
      (range Start Stop Step) ) )

(scl 12)

(mapcar round
   (findRoots
      '((X) (+ (*/ X X X `(* 1.0 1.0)) (*/ -3 X X 1.0) (* 2 X)))
      -1.0 3.0 0.0001 0.00000001 ) )


f: procedure (x) returns (float (18));
   declare x float (18);
   return (x**3 - 3*x**2 + 2*x );
end f;

declare eps float, (x, y) float (18);
declare dx fixed decimal (15,13);

eps = 1e-12;

do dx = -5.03 to 5 by 0.1;
   x = dx;
   if sign(f(x)) ^= sign(f(dx+0.1)) then
      call locate_root;
end;

locate_root: procedure;
   declare (left, mid, right) float (18);

   put skip list ('Looking for root in [' || x, x+0.1 || ']' );
   left = x; right = dx+0.1;
   PUT SKIP LIST (F(LEFT), F(RIGHT) );
   if abs(f(left) ) < eps then
      do; put skip list ('Found a root at x=', left); return; end;
   else if abs(f(right) ) < eps then
      do; put skip list ('Found a root at x=', right); return; end;
   do forever;
      mid = (left+right)/2;
      if sign(f(mid)) = 0 then
         do; put skip list ('Root found at x=', mid); return; end;
      else if sign(f(left)) ^= sign(f(mid)) then
         right = mid;
      else
         left = mid;
      /* put skip list (left || right); */
      if abs(right-left) < eps then
         do; put skip list ('There is a root near ' ||
            (left+right)/2); return;
         end;
   end;
end locate_root;


Procedure.d f(x.d)
  ProcedureReturn x*x*x-3*x*x+2*x
EndProcedure

Procedure main()
  OpenConsole()
  Define.d StepSize= 0.001
  Define.d Start=-1, stop=3
  Define.d value=f(start), x=start
  Define.i oldsign=Sign(value)

  If value=0
    PrintN("Root found at "+StrF(start))
  EndIf

  While x<=stop
    value=f(x)
    If Sign(value) <> oldsign
      PrintN("Root found near "+StrF(x))
    ElseIf value = 0
      PrintN("Root found at "+StrF(x))
    EndIf
    oldsign=Sign(value)
    x+StepSize
  Wend
EndProcedure

main()


#!/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)))))))


f = lambda x: x * x * x - 3 * x * x + 2 * x

step = 0.001 # Smaller step values produce more accurate and precise results
start = -1
stop = 3

sign = f(start) > 0

x = start
while x <= stop:
    value = f(x)

    if value == 0:
        # We hit a root
        print "Root found at", x
    elif (value > 0) != sign:
        # We passed a root
        print "Root found near", x

    # Update our sign
    sign = value > 0

    x += step


f <- function(x) x^3 -3*x^2 + 2*x

findroots <- function(f, begin, end, tol = 1e-20, step = 0.001) {
  se <- ifelse(sign(f(begin))==0, 1, sign(f(begin)))
  x <- begin
  while ( x <= end ) {
    v <- f(x)
    if ( abs(v) < tol ) {
      print(sprintf("root at %f", x))
    } else if ( ifelse(sign(v)==0, 1, sign(v)) != se )  {
      print(sprintf("root near %f", x))
    }
    se <- ifelse( sign(v) == 0 , 1, sign(v))
    x <- x + step
  }
}

findroots(f, -1, 3)


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
    next
end function

Input "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


#lang racket

;; Attempts to find all roots of a real-valued function f
;; in a given interval [a b] by dividing the interval into N parts
;; and using the root-finding method on each subinterval
;; which proves to contain a root.
(define (find-roots f a b
                    #:divisions [N 10]
                    #:method [method secant])
  (define h (/ (- b a) N))
  (for*/list ([x1 (in-range a b h)]
              [x2 (in-value (+ x1 h))]
              #:when (or (root? f x1)
                         (includes-root? f x1 x2)))
    (find-root f x1 x2 #:method method)))

;; Finds a root of a real-valued function f
;; in a given interval [a b].
(define (find-root f a b #:method [method secant])
  (cond
    [(root? f a) a]
    [(root? f b) b]
    [else (and (includes-root? f a b) (method f a b))]))

;; Returns #t if x is a root of a real-valued function f
;; with absolute accuracy (tolerance).
(define (root? f x) (almost-equal? 0 (f x)))

;; Returns #t if interval (a b) contains a root
;; (or the odd number of roots) of a real-valued function f.
(define (includes-root? f a b) (< (* (f a) (f b)) 0))

;; Returns #t if a and b are equal with respect to
;; the relative accuracy (tolerance).
(define (almost-equal? a b)
  (or (< (abs (+ b a)) (tolerance))
      (< (abs (/ (- b a) (+ b a))) (tolerance))))

(define tolerance (make-parameter 5e-16))


sub f(\x) { x³ - 3*x² + 2*x }

my $start = -1;
my $stop = 3;
my $step = 0.001;

for $start, * + $step ... $stop -> $x {
    state $sign = 0;
    given f($x) {
        my $next = .sign;
        when 0.0 {
            say "Root found at $x";
        }
        when $sign and $next != $sign {
            say "Root found near $x";
        }
        NEXT $sign = $next;
    }
}


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 y
	case [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]


/*REXX program finds the roots of a specific function:  x^3 - 3*x^2 + 2*x  via bisection*/
parse arg bot top inc .                          /*obtain optional arguments from the CL*/
if bot=='' | bot==","  then bot= -5              /*Not specified?  Then use the default.*/
if top=='' | top==","  then top= +5              /* "       "        "   "   "     "    */
if inc=='' | inc==","  then inc=   .0001         /* "       "        "   "   "     "    */
z= f(bot - inc)                                  /*compute 1st value to start compares. */
!= sign(z)                                       /*obtain the sign of the initial value.*/
           do j=bot  to top  by  inc             /*traipse through the specified range. */
           z= f(j);              $= sign(z)      /*compute new value;  obtain the sign. */
           if z=0  then                               say  'found an exact root at'   j/1
                   else if !\==$  then if !\==0  then say  'passed a root at'         j/1
           != $                                  /*use the new sign for the next compare*/
           end   /*j*/                           /*dividing by unity normalizes J  [↑]  */
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
f:  parse arg x;     return x * (x * (x-3) +2)   /*formula used   ──► x^3 - 3x^2  + 2x  */
                                                 /*with factoring ──► x{ x^2 -3x  + 2 } */
                                                 /*more     "     ──► x{ x( x-3 ) + 2 } */


load "stdlib.ring"
function = "return pow(x,3)-3*pow(x,2)+2*x"
rangemin = -1
rangemax = 3
stepsize = 0.001
accuracy = 0.1
roots(function, rangemin, rangemax, stepsize, accuracy)

func roots funct, min, max, inc, eps
     oldsign = 0
     for x = min to max step inc
         num = sign(eval(funct))
         if num = 0
            see "root found at x = " + x + nl
            num = -oldsign
         else if num != oldsign and oldsign != 0
              if inc < eps
                 see "root found near x = " + x + nl
              else roots(funct, x-inc, x+inc/8, inc/8, eps) ok ok ok
         oldsign = num
     next


{{
  : 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 [email protected] ;
}}

"abcdef123GHIJKL" rot13 dup puts cr rot13 puts
"abjurer NOWHERE" rot13 puts