link math

procedure main(A)
    limit := (integer(A[1])|15)+1
    every write(right(binocoef(i := 2*seq(0)\limit,i/2)-binocoef(i,i/2+1),30))
end


public class Test {
    public static void main(String[] args) {
        int N = 15;
        int[] t = new int[N + 2];
        t[1] = 1;

        for (int i = 1; i <= N; i++) {

            for (int j = i; j > 1; j--)
                t[j] = t[j] + t[j - 1];

            t[i + 1] = t[i];

            for (int j = i + 1; j > 1; j--)
                t[j] = t[j] + t[j - 1];

            System.out.printf("%d ", t[i + 1] - t[i]);
        }
    }
}


let c = 'A'
let n = 65
printfn "%d" (int c)
printfn "%c" (char n)


CHAR: katakana-letter-a .
"ア" first .

12450 1string print


def binomial(n; k):
  if k > n / 2 then binomial(n; n-k)
  else reduce range(1; k+1) as $i (1; . * (n - $i + 1) / $i)
  end;

# Direct (naive) computation using two numbers in Pascal's triangle:
def catalan_by_pascal: . as $n | binomial(2*$n; $n) - binomial(2*$n; $n-1);


# v0.6

function pascal(n::Int)
    r = ones(Int, n, n)
    for i in 2:n, j in 2:n
        r[i, j] = r[i-1, j] + r[i, j-1]
    end
    return r
end

function catalan_num(n::Int)
    p = pascal(n + 2)
    p[n+4:n+3:end-1] - diag(p, 2)
end

@show catalan_num(15)


// version 1.1.2

import java.math.BigInteger

val ONE = BigInteger.ONE

fun pascal(n: Int, k: Int): BigInteger {
    if (n == 0 || k == 0) return ONE
    val num = (k + 1..n).fold(ONE) { acc, i -> acc * BigInteger.valueOf(i.toLong()) }
    val den = (2..n - k).fold(ONE) { acc, i -> acc * BigInteger.valueOf(i.toLong()) }
    return num / den
}

fun catalanFromPascal(n: Int) {
    for (i in 1 until n step 2) {
        val mi = i / 2 + 1
        val catalan = pascal(i, mi) - pascal(i, mi - 2)
        println("${"%2d".format(mi)} : $catalan")
    }
}

fun main(args: Array<String>) {
    val n = 15
    catalanFromPascal(n * 2)
}


WRITE(*,*) ACHAR(97), IACHAR("a")
WRITE(*,*) CHAR(97), ICHAR("a")


function nextrow (t)
    local ret = {}
    t[0], t[#t + 1] = 0, 0
    for i = 1, #t do ret[i] = t[i - 1] + t[i] end
    return ret
end

function catalans (n)
    local t, middle = {1}
    for i = 1, n do
        middle = math.ceil(#t / 2)
        io.write(t[middle] - (t[middle + 1] or 0) .. " ")
        t = nextrow(nextrow(t))
    end
end

catalans(15)


Module CatalanNumbers {
      Def Integer count, t_row, size=31
      Dim triangle(1 to size, 1 to size)

      \\ call sub
      pascal_triangle(size, &triangle())

      Print "The first 15 Catalan numbers are"
      count = 1% : t_row = 2%

      Do {
            Print  Format$("{0:0:-3}:{1:0:-15}", count, triangle(t_row, t_row) - triangle(t_row +1, t_row -1))
            t_row++
            count++
      } Until count > 15
      End

      Sub pascal_triangle(rows As Integer, &Pas_tri())
          Local x=0%, y=0%
          For x = 1 To rows
              Pas_tri( 1%, x ) = [email protected]
              Pas_tri( x, 1% ) = [email protected]
          Next x
          if rows<2 then exit sub
          For x = 2 To rows-1
              For y = 2 To rows + 1 - x
                  Pas_tri(x, y) = pas_tri(x - 1 , y) + pas_tri(x, y - 1)
              Next y
          Next x
      End Sub
}
CatalanNumbers


nextrow[lastrow_] := Module[{output},
  output = ConstantArray[1, Length[lastrow] + 1];
  Do[
   output[[i + 1]] = lastrow[[i]] + lastrow[[i + 1]];
   , {i, 1, Length[lastrow] - 1}];
  output
  ]
pascaltriangle[size_] := NestList[nextrow, {1}, size]
catalannumbers[length_] := Module[{output, basetriangle},
  basetriangle = pascaltriangle[2 length];
  list1 = basetriangle[[# *2 + 1, # + 1]] & /@ Range[length];
  list2 = basetriangle[[# *2 + 1, # + 2]] & /@ Range[length];
  list1 - list2
  ]
(* testing *)
catalannumbers[15]


' FreeBASIC v1.05.0 win64
Print "a - > "; Asc("a")
Print "98 -> "; Chr(98)
Print
Print "Press any key to exit the program"
Sleep
End


const n = 15
var t = newSeq[int](n + 2)

t[1] = 1
for i in 1..n:
  for j in countdown(i, 1): t[j] += t[j-1]
  t[i+1] = t[i]
  for j in countdown(i+1, 1): t[j] += t[j-1]
  stdout.write t[i+1] - t[i], " "
stdout.write '\n'


let catalan : int ref = ref 0 in
Printf.printf "%d ," 1 ;
for i = 2 to 9  do
let nm : int ref = ref 1 in
let den : int ref = ref 1 in
for k = 2 to i do
nm := (!nm)*(i+k);
den := (!den)*k;
catalan := (!nm)/(!den) ;
done;
print_int (!catalan); print_string "," ;
done;;


import: mapping

: pascal( n -- [] )
   [ 1 ] n #[ dup [ 0 ] + [ 0 ] rot + zipWith( #+ ) ] times ;

: catalan( n -- m )
   n 2 * pascal at( n 1+ ) n 1+ / ;


Public Sub Form_Open()
Dim sChar As String

sChar = InputBox("Enter a character")
Print "Character " & sChar & " = ASCII " & Str(Asc(sChar))

sChar = InputBox("Enter a ASCII code")
Print "ASCII code " & sChar & " represents " & Chr(Val(sChar))

End


# Code must be in 0 .. 255.
CharInt(65);
# 'A'
IntChar('Z');
# 90


fmt.Println('a') // prints "97"
fmt.Println('π') // prints "960"


Program CatalanNumbers
type
  tElement = Uint64;
var
  Catalan : array[0..50] of tElement;
procedure GetCatalan(L:longint);
var
  PasTri : array[0..100] of tElement;
  j,k: longInt;
begin
  l := l*2;
  PasTri[0] := 1;
  j    := 0;
  while (j<L) do
  begin
    inc(j);
    k := (j+1) div 2;
    PasTri[k] :=PasTri[k-1];
    For k := k downto 1 do
      inc(PasTri[k],PasTri[k-1]);
    IF NOT(Odd(j)) then
    begin
      k := j div 2;
      Catalan[k] :=PasTri[k]-PasTri[k-1];
    end;
  end;
end;

var
  i,l: longint;
Begin
  l := 15;
  GetCatalan(L);
  For i := 1 to L do
    Writeln(i:3,Catalan[i]:20);
end.


printf ("%d\n", ('a' as char) as int)
printf ("%c\n", 97)


import Data.Char

main = do
  print (ord 'a') -- prints "97"
  print (chr 97) -- prints "'a'"
  print (ord 'π') -- prints "960"
  print (chr 960) -- prints "'\960'"


constant N = 15 -- accurate to 30, nan/inf for anything over 514 (gmp version is below).
sequence catalan = {},      -- (>=1 only)
         p = repeat(1,N+1)
atom p1
for i=1 to N do
    p1 = p[1]*2
    catalan = append(catalan,p1-p[2])
    for j=1 to N-i+1 do
        p1 += p[j+1]
        p[j] = p1
    end for
--  ?p[1..N-i+1]
end for
?catalan


#MAXNUM = 15
Declare catalan()

If OpenConsole("Catalan numbers")
  catalan()
  Input()
  End 0
Else
  End -1
EndIf

Procedure catalan()
  Define k.i, n.i, num.d, den.d, cat.d

  Print("1 ")

  For n=2 To #MAXNUM
    num=1 : den =1
    For k=2 To n
      num * (n+k)
      den * k
      cat = num / den
    Next
    Print(Str(cat)+" ")
  Next
EndProcedure


|%
++  enc
  |=  [email protected]  `@ud`char
++  dec
  |=  [email protected]  `@t`code
--


software {
	print(number('a'))
	print(text([97]))
}


  [ [] 0 rot 0 join
    witheach
     [ tuck +
       rot join swap ]
    drop ]                is nextline ( [ --> [ )

  [ ' [ 1 ] swap times
      [ nextline nextline
        dup dup size 2 /
        split nip
        2 split drop
        do - echo sp ]
    drop ]                is catalan  ( n -->   )

  15 catalan


constant @pascal = [1], -> @p { [0, |@p Z+ |@p, 0] } ... *;

constant @catalan = gather for 2, 4 ... * -> $ix {
    my @row := @pascal[$ix];
    my $mid = +@row div 2;
    take [-] @row[$mid, $mid+1]
}

.say for @catalan[^20];


procedure main(arglist)
if *arglist > 0 then L := arglist else L := [97, "a"]

every x := !L do
   write(x, " ==> ", char(integer(x)) | ord(x) )  # char produces a character, ord produces a number
end


"a" at(0) println       // --> 97
97 asCharacter println  // --> a

"π" at(0) println       // --> 960
960 asCharacter println // --> π


public class Foo {
    public static void main(String[] args) {
        System.out.println((int)'a'); // prints "97"
        System.out.println((char)97); // prints "a"
    }
}


/*REXX program  obtains and displays  Catalan numbers  from  a  Pascal's triangle.      */
parse arg N .                                    /*Obtain the optional argument from CL.*/
if N=='' | N==","  then N=15                     /*Not specified?  Then use the default.*/
numeric digits max(9, N%2 + N%8)                 /*so we can handle huge Catalan numbers*/
@.=0;   @.1=1                                    /*stem array default; define 1st value.*/

  do i=1  for N;                               ip=i+1
                      do j=i   by -1  for N;   jm=j-1;   @.[email protected].[email protected].jm;    end /*j*/
  @.[email protected].i;           do k=ip  by -1  for N;   km=k-1;   @.[email protected].[email protected].km;    end /*k*/
  say  @.ip - @.i                                /*display the   Ith   Catalan number.  */
  end   /*i*/                                    /*stick a fork in it,  we're all done. */


n=15
cat = list(n+2)
cat[1]=1
for i=1 to n
    for j=i+1 to 2 step -1
        cat[j]=cat[j]+cat[j-1]
    next
    cat[i+1]=cat[i]
    for j=i+2 to 2 step -1
        cat[j]=cat[j]+cat[j-1]
    next
    see "" + (cat[i+1]-cat[i]) + " "
next


def catalan(num)
  t = [0, 1] #grows as needed
  (1..num).map do |i|
    i.downto(1){|j| t[j] += t[j-1]}
    t[i+1] = t[i]
    (i+1).downto(1) {|j| t[j] += t[j-1]}
    t[i+1] - t[i]
  end
end

p catalan(15)


n = 15
dim t(n+2)
t(1) = 1
for i = 1 to n
  for  j = i to 1 step -1  : t(j) = t(j) + t(j-1): next j
  t(i+1) = t(i)
  for  j = i+1 to 1 step -1: t(j) = t(j) + t(j-1 : next j
print t(i+1) - t(i);" ";
next i


console.log('a'.charCodeAt(0)); // prints "97"
console.log(String.fromCharCode(97)); // prints "a"


def catalan(n: Int): Int =
  if (n <= 1) 1
  else (0 until n).map(i => catalan(i) * catalan(n - i - 1)).sum

(1 to 15).map(catalan(_))


$ include "seed7_05.s7i";

const proc: main is func
  local
    const integer: N is 15;
    var array integer: t is [] (1) & N times 0;
    var integer: i is 0;
    var integer: j is 0;
  begin
    for i range 1 to N do
      for j range i downto 2 do
        t[j] +:= t[j - 1];
      end for;
      t[i + 1] := t[i];
      for j range i + 1 downto 2 do
        t[j] +:= t[j - 1];
      end for;
      write(t[i + 1] - t[i] <& " ");
    end for;
    writeln;
  end func;


func catalan(num) {
  var t = [0, 1]
  (1..num).map { |i|
    flip(^i    ).each {|j| t[j+1] += t[j] }
    t[i+1] = t[i]
    flip(^i.inc).each {|j| t[j+1] += t[j] }
    t[i+1] - t[i]
  }
}

say catalan(15).join(' ')


fun main(args: Array<String>) {
    var c = 'a'
    var i = c.toInt()
    println("$c  <-> $i")
    i += 2
    c = i.toChar()
    println("$i <-> $c")
}


: CHAR  "!\"#$%&'()*+,-./0123456789:;<=>[email protected][" comb
        '\\ comb -1 remove append "]^_`abcdefghijklmnopqrstuvwxyz{|}~" comb append ;
: CODE  95 iota 33 + ;                : comb  "" split ;
: extract'  rot 1 compress index subscript expand drop ;
: chr  CHAR CODE extract' ;
: ord  CODE CHAR extract' ;

'a ord .    # 97
97 chr .    # a


F correct_case(string)
   R string.filter(s -> s.is_alpha()).map(s -> s.uppercase()).join(‘’)

F permu(String alp; num)
   R alp[num..]‘’alp[0 .< num]

F rotate_wheels(lalph, ralph, key)
   V newin = ralph.index(key)
   R (permu(lalph, newin), permu(ralph, newin))

F scramble_wheels(String =lalph, String =ralph)
   lalph = lalph[0]‘’lalph[2.<14]‘’lalph[1]‘’lalph[14..]
   ralph = ralph[1.<3]‘’ralph[4.<15]‘’ralph[3]‘’ralph[15..]‘’ralph[0]
   R (lalph, ralph)

F do_chao(=msg, =lalpha, =ralpha, en = 1B, show = 0B)
   msg = correct_case(msg)
   V out = ‘’
   I show
      print(‘=’ * 54)
      print((10 * ‘ ’)‘left:’(21 * ‘ ’)‘right: ’)
      print(‘=’ * 54)
      print(lalpha‘ ’ralpha" \n")
   L(l) msg
      I en
         (lalpha, ralpha) = rotate_wheels(lalpha, ralpha, l)
         out ‘’= lalpha[0]
      E
         (ralpha, lalpha) = rotate_wheels(ralpha, lalpha, l)
         out ‘’= ralpha[0]
      (lalpha, ralpha) = scramble_wheels(lalpha, ralpha)
      I show
         print(lalpha‘ ’ralpha)
   R out

V lalpha = ‘HXUCZVAMDSLKPEFJRIGTWOBNYQ’
V ralpha = ‘PTLNBQDEOYSFAVZKGJRIHWXUMC’
V msg = ‘WELLDONEISBETTERTHANWELLSAID’

print(‘L: ’lalpha)
print(‘R: ’ralpha)
print(‘I: ’msg)
V o = do_chao(msg, lalpha, ralpha, 1B, 0B)
print(‘O: ’o)
print(‘D: ’do_chao(o, lalpha, ralpha, 0B, 0B))
print()

do_chao(msg, lalpha, ralpha, 1B, 1B)


PRINT "Catalan Numbers from Pascal's Triangle"!PRINT
x = 15
DIM t(x+2)
t(1) = 1
FOR n = 1 TO x
  FOR  m = n TO 1 STEP -1
    t(m) = t(m) + t(m-1)
  NEXT m
    t(n+1) = t(n)
  FOR  m = n+1 TO 1 STEP -1
    t(m) = t(m) + t(m-1)
  NEXT m
PRINT n,"#######":t(n+1) - t(n)
NEXT n


proc catalan n {
    set result {}
    array set t {0 0 1 1}
    for {set i 1} {[set k $i] <= $n} {incr i} {
	for {set j $i} {$j > 1} {} {incr t($j) $t([incr j -1])}
	set t([incr k]) $t($i)
	for {set j $k} {$j > 1} {} {incr t($j) $t([incr j -1])}
	lappend result [expr {$t($k) - $t($i)}]
    }
    return $result
}

puts [catalan 15]


'a'->integer
'A'->integer
97->bytes
65->bytes


charCode = 97
char$ = "a"
print chr$(charCode) 'prints a
print asc(char$) 'prints 97


with Ada.Text_IO; use Ada.Text_IO;

procedure chao_slices is
   type iMode is (Encrypt, Decrypt);

   L_Alphabet : String := "HXUCZVAMDSLKPEFJRIGTWOBNYQ";
   R_Alphabet : String := "PTLNBQDEOYSFAVZKGJRIHWXUMC";
   plaintext  : String := "WELLDONEISBETTERTHANWELLSAID";
   ciphertext : String (1 .. plaintext'length);
   plaintext2 : String (1 .. plaintext'length);
   offset     : Natural;

   function IndexOf (Source : String; Value : Character) return Positive is
      Result : Positive;

   begin
      for I in Source'Range loop
         if Source (I) = Value then
            Result := I;
            exit;
         end if;
      end loop;
      return Result;
   end IndexOf;

   function Exec
     (Text : String; mode : iMode; showsteps : Boolean := False) return String
   is
      etext : String (Text'First .. Text'Last);
      temp  : String (1 .. 26);
      index : Positive;
      store : Character;
      left  : String := L_Alphabet;
      right : String := R_Alphabet;
   begin
      for I in Text'Range loop
         if showsteps then
            Put_Line (left & "  " & right);
         end if;

         if mode = Encrypt then
            index     := IndexOf (Source => right, Value => Text (I));
            etext (I) := left (index);
         else
            index     := IndexOf (Source => left, Value => Text (I));
            etext (I) := right (index);
         end if;

         exit when I = Text'Last;

         -- permute left
         -- The array value permutations are performed using array slices
         -- rather than explicit loops

         if index > 1 then
            offset                 := 26 - index;
            temp (1 .. offset + 1) := left (index .. index + offset);

            temp (offset + 2 .. 26) := left (1 .. index - 1);
            store                   := temp (2);

            temp (2 .. 13) := temp (3 .. 14);
            temp (14)      := store;
            left           := temp;

            -- permute right
            -- The array value permutations are performed using array slices
            -- rather than explicit loops

            temp (1 .. offset + 1) := right (index .. index + offset);

            temp (offset + 2 .. 26) := right (1 .. index - 1);
            store                   := temp (1);

            temp (1 .. 25) := temp (2 .. 26);
            temp (26)      := store;
            store          := temp (3);

            temp (3 .. 13) := temp (4 .. 14);
            temp (14)      := store;
            right          := temp;
         end if;

      end loop;

      return etext;

   end Exec;
begin
   Put_Line ("The original text is : " & plaintext);
   New_Line;
   Put_Line
     ("The left and right alphabets after each permutation during encryption are:");
   New_Line;
   ciphertext := Exec (plaintext, Encrypt, True);
   New_Line;
   Put_Line ("The ciphertext is : " & ciphertext);
   plaintext2 := Exec (ciphertext, Decrypt);
   New_Line;
   Put_Line ("The recovered plaintext is : " & plaintext2);
end chao_slices;


dim t()
if Wscript.arguments.count=1 then
  n=Wscript.arguments.item(0)
else
  n=15
end if
redim t(n+1)
't(*)=0
t(1)=1
for i=1 to n
  ip=i+1
  for j = i to 1 step -1
    t(j)=t(j)+t(j-1)
  next 'j
  t(i+1)=t(i)
  for j = i+1 to 1 step -1
    t(j)=t(j)+t(j-1)
  next 'j
  Wscript.echo t(i+1)-t(i)
next 'i


Sub catalan()
    Const n = 15
    Dim t(n + 2) As Long
    Dim i  As Integer, j As Integer
    t(1) = 1
    For i = 1 To n
        For j = i + 1 To 2 Step -1
            t(j) = t(j) + t(j - 1)
        Next j
        t(i + 1) = t(i)
        For j = i + 2 To 2 Step -1
            t(j) = t(j) + t(j - 1)
        Next j
        Debug.Print i, t(i + 1) - t(i)
    Next i
End Sub 'catalan


-- returns Unicode code point (=ASCII code for ASCII characters) for character
put chartonum("a")
-- 97

-- returns character for Unicode code point (=ASCII code for ASCII characters)
put numtochar(934)
-- Φ


puts("Unicode value of ñ is ${scan("ñ", "%c")}");
printf("The code 241 in Unicode is the letter: %c.\n", 241);


Since 7.0.x works with unicode
put charToNum("") && numToChar(240)


-- Chaocipher algorithm by J.F.Byrne 1918.
on chaocipher(input, |key|, mode)
    -- input: text to be enciphered or deciphered.
    -- |key|: script object or record with leftAlpha and rightAlpha properties, each of whose values is a shuffled alphabet text.
    -- mode: the text "encipher" or "decipher".
    script o
        property inputChars : input's characters
        property leftAlpha : |key|'s leftAlpha's characters
        property rightAlpha : |key|'s rightAlpha's characters
        property inAlpha : leftAlpha
        property outAlpha : rightAlpha
        property output : {}
    end script

    set alphaLen to (count o's leftAlpha)
    if ((count o's rightAlpha) ≠ alphaLen) then error
    if (mode is "encipher") then
        set {o's inAlpha, o's outAlpha} to {o's rightAlpha, o's leftAlpha}
    else if (mode is not "decipher") then
        error
    end if
    set zenith to 1
    set nadir to alphaLen div 2 + 1
    repeat with char in o's inputChars
        set char to char's contents
        set found to false
        repeat with i from 1 to alphaLen
            if (o's inAlpha's item i = char) then
                set end of o's output to o's outAlpha's item i
                set found to true
                exit repeat
            end if
        end repeat
        if (found) then
            rotate(o's leftAlpha, zenith, alphaLen, -(i - zenith))
            rotate(o's leftAlpha, zenith + 1, nadir, -1)
            rotate(o's rightAlpha, zenith, alphaLen, -i)
            rotate(o's rightAlpha, zenith + 2, nadir, -1)
        end if
    end repeat

    return join(o's output, "")
end chaocipher

on rotate(theList, l, r, amount)
    set listLength to (count theList)
    if (listLength < 2) then return
    if (l < 0) then set l to listLength + l + 1
    if (r < 0) then set r to listLength + r + 1
    if (l > r) then set {l, r} to {r, l}
    script o
        property lst : theList
        property storage : missing value
    end script

    set rangeLength to r - l + 1
    set amount to (rangeLength + rangeLength - amount) mod rangeLength
    if (amount is 0) then return
    set o's storage to o's lst's items l thru (l + amount - 1)
    repeat with i from (l + amount) to r
        set o's lst's item (i - amount) to o's lst's item i
    end repeat
    set j to r - amount
    repeat with i from 1 to amount
        set o's lst's item (j + i) to o's storage's item i
    end repeat
end rotate

on join(lst, delim)
    set astid to AppleScript's text item delimiters
    set AppleScript's text item delimiters to delim
    set txt to lst as text
    set AppleScript's text item delimiters to astid
    return txt
end join

-- Return a script object containing a couple of randomised alphabets to use as a choacipher key.
on makeKey()
    set lAlpha to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"'s characters
    copy lAlpha to rAlpha
    script |key|
        property leftAlpha : join(shuffle(lAlpha, 1, -1), "")
        property rightAlpha : join(shuffle(rAlpha, 1, -1), "")
    end script

    return |key|
end makeKey

-- Fisher-Yates (aka Durstenfeld, aka Knuth) shuffle.
on shuffle(theList, l, r)
    set listLength to (count theList)
    if (listLength < 2) then return array
    if (l < 0) then set l to listLength + l + 1
    if (r < 0) then set r to listLength + r + 1
    if (l > r) then set {l, r} to {r, l}
    script o
        property lst : theList
    end script

    repeat with i from l to (r - 1)
        set j to (random number from i to r)
        set v to o's lst's item i
        set o's lst's item i to o's lst's item j
        set o's lst's item j to v
    end repeat

    return theList
end shuffle

-- Demo using the two-alphabet key from the Rubin paper and another generated at random.
-- Decription must be with the key that was used for the encription.
on demo(originalText)
    set key1 to {leftAlpha:"HXUCZVAMDSLKPEFJRIGTWOBNYQ", rightAlpha:"PTLNBQDEOYSFAVZKGJRIHWXUMC"}
    set key2 to makeKey()
    set enciphered to chaocipher(originalText, key1, "encipher")
    set doubleEnciphered to chaocipher(enciphered, key2, "encipher")
    set deDoubleEnciphered to chaocipher(doubleEnciphered, key2, "decipher")
    set deciphered to chaocipher(deDoubleEnciphered, key1, "decipher")
    return join({"Original text = " & originalText, ¬
        "Enciphered = " & enciphered, "Double enciphered = " & doubleEnciphered, ¬
        "De-double enciphered = " & deDoubleEnciphered, "Deciphered  = " & deciphered}, linefeed)
end demo
demo("WELLDONEISBETTERTHANWELLSAID")


var n = 15
var t = List.filled(n+2, 0)
t[1] = 1
for (i in 1..n) {
    if (i > 1) for (j in i..2) t[j] = t[j] + t[j-1]
    t[i+1] = t[i]
    if (i > 0) for (j in i+1..2) t[j] = t[j] + t[j-1]
    System.write("%(t[i+1]-t[i]) ")
}
System.print()


const std = @import("std");
const stdout = std.io.getStdOut().outStream();

pub fn main() !void {
    var n: u32 = 1;
    while (n <= 15) : (n += 1) {
        const row = binomial(n * 2).?;
        try stdout.print("{d:2}  {d:8}\n", .{ n, row[n] - row[n + 1] });
    }
}

pub fn binomial(n: u32) ?[]const u64 {
    if (n >= rmax)
        return null
    else {
        const k = n * (n + 1) / 2;
        return pascal[k .. k + n + 1];
    }
}

const rmax = 68;

const pascal = build: {
    @setEvalBranchQuota(100_000);
    var coefficients: [(rmax * (rmax + 1)) / 2]u64 = undefined;
    coefficients[0] = 1;
    var j: u32 = 0;
    var k: u32 = 1;
    var n: u32 = 1;
    while (n < rmax) : (n += 1) {
        var prev = coefficients[j .. j + n];
        var next = coefficients[k .. k + n + 1];
        next[0] = 1;
        var i: u32 = 1;
        while (i < n) : (i += 1)
            next[i] = prev[i] + prev[i - 1];
        next[i] = 1;
        j = k;
        k += n + 1;
    }
    break :build coefficients;
};


fcn binomial(n,k){ (1).reduce(k,fcn(p,i,n){ p*(n-i+1)/i },1,n) }
(1).pump(15,List,fcn(n){ binomial(2*n,n)-binomial(2*n,n+1) })


10 LET N=15
20 DIM t(N+2)
30 LET t(2)=1
40 FOR i=2 TO N+1
50 FOR j=i TO 2 STEP -1: LET t(j)=t(j)+t(j-1): NEXT j
60 LET t(i+1)=t(i)
70 FOR j=i+1 TO 2 STEP -1: LET t(j)=t(j)+t(j-1): NEXT j
80 PRINT t(i+1)-t(i);" ";
90 NEXT i


print ascii "a    ; 97
print char 97     ; a


|?- char_code(Char, 97), write(Char).
a
Char = a
yes


print(string.byte("a")) -- prints "97"
print(string.char(97)) -- prints "a"


\\ ANSI
Print Asc("a")
Print Chr$(Asc("a"))
\\ Utf16-Le
Print ChrCode("a")
Print ChrCode$(ChrCode("a"))

\\ (,) is an empty array.

Function Codes(a$) {
      If Len(A$)=0 then =(,) : Exit
      Buffer Mem as byte*Len(a$)
      \\ Str$(string) return one byte character
      Return Mem, 0:=Str$(a$)
           Inventory Codes
      For i=0 to len(Mem)-1
      Append Codes, i:=Eval(Mem, i)
      Next i
      =Codes
}
Print Codes("abcd")
\\ 97 98 99 100


(= lshift '((0 1) (2 14) (1 2) (14 26)))
(= rshift '((1 3) (4 15) (3 4) (15 26) (0 1)))

(= rot (fn (alpha shift)
  (let shift (mod shift 26)
    (string (cut alpha shift) (cut alpha 0 shift)))))

(= scramble-wheel (fn (alpha moves)
  (= oput '())
  (up i 0 (- (len moves) 1)
      (push (cut alpha ((moves i) 0) ((moves i) 1)) oput))
  (= oput (string (rev oput)))))

(= chaocipher (fn (left right msg (o crypted) (o dec?))
  (unless crypted
    (prn "Encoding " msg " with chaocipher")
    (prn left " " right))
  (when dec? (swap left right))
    (= offset ((positions (msg 0) right) 0))
    (= left (rot left offset))
    (= right (rot right offset))
    (push (cut left 0 1) crypted)
  (when dec? (swap left right))
  (prn (scramble-wheel left lshift)
   " " (scramble-wheel right rshift))
  (if (> (len msg) 1)
      (chaocipher (scramble-wheel left lshift)
             (scramble-wheel right rshift)
                  (cut msg 1) crypted dec?)
      (string (rev crypted)))))

(chaocipher "HXUCZVAMDSLKPEFJRIGTWOBNYQ" "PTLNBQDEOYSFAVZKGJRIHWXUMC"
            "WELLDONEISBETTERTHANWELLSAID")
(chaocipher "HXUCZVAMDSLKPEFJRIGTWOBNYQ" "PTLNBQDEOYSFAVZKGJRIHWXUMC"
            "OAHQHCNYNXTSZJRRHJBYHQKSOUJY" nil 1)


LeftW := "HXUCZVAMDSLKPEFJRIGTWOBNYQ"
RghtW := "PTLNBQDEOYSFAVZKGJRIHWXUMC"

PlainText    := "WELLDONEISBETTERTHANWELLSAID"
CipherText    := Chao_Cipher(PlainText, LeftW, RghtW)     ; "OAHQHCNYNXTSZJRRHJBYHQKSOUJY"
DecipherText:= Chao_Decipher(CipherText, LeftW, RghtW)    ; "WELLDONEISBETTERTHANWELLSAID"

MsgBox % Result := "Original text:`t" PlainText "`nCipher text:`t" CipherText "`nDecipher text:`t" DecipherText
return
;-------------------------------------------
Chao_Cipher(PT, LeftW, RghtW){
    oRght:=StrSplit(RghtW), oLeft:=StrSplit(LeftW)
    for i, p in StrSplit(PT){
        result .= (c := Key2Val(oRght, oLeft, p))
        oLeft:=Permute(oLeft, c, 1)
        oRght:=Permute(oRght, p)
    }
    return result
}
;-------------------------------------------
Chao_Decipher(CT, LeftW, RghtW){
    oRght:=StrSplit(RghtW), oLeft:=StrSplit(LeftW)
    for i, c in StrSplit(CT){
        result .= (p := Key2Val(oLeft, oRght, c))
        oLeft:=Permute(oLeft, c, 1)
        oRght:=Permute(oRght, p)
    }
    return result
}
;-------------------------------------------
Key2Val(Key, Val, char){
    for i, ch in Key
        if (ch = char)
            return Val[i]
}
;-------------------------------------------
Permute(Arr, ch, dt:=0){
    for i, c in Arr
        if (c=ch)
            break
    loop % i-dt
        Arr.Push(Arr.RemoveAt(1))               ; shift left
    ch := Arr[3-dt]                             ; save 2nd/3rd chr
    loop % 11+dt
        Arr[A_Index+2-dt]:=Arr[A_Index+3-dt]    ; shift pos 3/4-14 left
    Arr[14] := ch                               ; place 2nd/3rd chr in pos 14
    return Arr
}


> use StringTools in Ord( "A" ); Char( 65 ) end;
                                   65

                                  "A"


message "enter a letter: ";
string a;
a := readstring;
message decimal (ASCII a); % writes the decimal number of the first character
                           % of the string a
message "enter a number: ";
num := scantokens readstring;
message char num;   % num can be anything between 0 and 255; what will be seen
                    % on output depends on the encoding used by the "terminal"; e.g.
                    % any code beyond 127 when UTF-8 encoding is in use will give
                    % a bad encoding; e.g. to see correctly an "è", we should write
message char10;  % (this add a newline...)
message char hex"c3" & char hex"a8";  % since C3 A8 is the UTF-8 encoding for "è"
end


#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define TRUE 1
#define FALSE 0

typedef int bool;
typedef enum { ENCRYPT, DECRYPT } cmode;

const char *l_alphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ";
const char *r_alphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC";

void chao(const char *in, char *out, cmode mode, bool show_steps) {
    int i, j, index;
    char store;
    size_t len = strlen(in);
    char left[27], right[27], temp[27];
    strcpy(left, l_alphabet);
    strcpy(right, r_alphabet);
    temp[26] = '\0';

    for (i = 0; i < len; ++i ) {
        if (show_steps) printf("%s  %s\n", left, right);
        if (mode == ENCRYPT) {
            index = strchr(right, in[i]) - right;
            out[i] = left[index];
        }
        else {
            index = strchr(left, in[i]) - left;
            out[i] = right[index];
        }
        if (i == len - 1) break;

        /* permute left */

        for (j = index; j < 26; ++j) temp[j - index] = left[j];
        for (j = 0; j < index; ++j) temp[26 - index + j] = left[j];
        store = temp[1];
        for (j = 2; j < 14; ++j) temp[j - 1] = temp[j];
        temp[13] = store;
        strcpy(left, temp);

        /* permute right */

        for (j = index; j < 26; ++j) temp[j - index] = right[j];
        for (j = 0; j < index; ++j) temp[26 - index + j] = right[j];
        store = temp[0];
        for (j = 1; j < 26; ++j) temp[j - 1] = temp[j];
        temp[25] = store;
        store = temp[2];
        for (j = 3; j < 14; ++j) temp[j - 1] = temp[j];
        temp[13] = store;
        strcpy(right, temp);
    }
}

int main() {
    const char *plain_text = "WELLDONEISBETTERTHANWELLSAID";
    char *cipher_text = malloc(strlen(plain_text) + 1);
    char *plain_text2 = malloc(strlen(plain_text) + 1);
    printf("The original plaintext is : %s\n", plain_text);
    printf("\nThe left and right alphabets after each permutation"
           " during encryption are :\n\n");
    chao(plain_text, cipher_text, ENCRYPT, TRUE);
    printf("\nThe ciphertext is : %s\n", cipher_text);
    chao(cipher_text, plain_text2, DECRYPT, FALSE);
    printf("\nThe recovered plaintext is : %s\n", plain_text2);
    free(cipher_text);
    free(plain_text2);
    return 0;
}


TextWindow.WriteLine("The ascii code for 'A' is: " + Text.GetCharacterCode("A") + ".")
TextWindow.WriteLine("The character for '65' is: " + Text.GetCharacter(65) + ".")


MODULE asc;

IMPORT  InOut;

VAR     letter          : CHAR;
        ascii           : CARDINAL;

BEGIN
  letter := 'a';
  InOut.Write (letter);
  ascii := ORD (letter);
  InOut.Write (11C);            (*  ASCII TAB   *)
  InOut.WriteCard (ascii, 8);
  ascii := ascii - ORD ('0');
  InOut.Write (11C);            (*  ASCII TAB   *)
  InOut.Write (CHR (ascii));
  InOut.WriteLn
END asc.


ORD('a') (* Returns 97 *)
VAL(97, CHAR); (* Returns 'a' *)


using System;

namespace Chaocipher {
    enum Mode {
        ENCRYPT,
        DECRYPT,
    }

    class Program {
        const string L_ALPHABET = "HXUCZVAMDSLKPEFJRIGTWOBNYQ";
        const string R_ALPHABET = "PTLNBQDEOYSFAVZKGJRIHWXUMC";

        static string Exec(string text, Mode mode, bool showSteps = false) {
            char[] left = L_ALPHABET.ToCharArray();
            char[] right = R_ALPHABET.ToCharArray();
            char[] eText = new char[text.Length];
            char[] temp = new char[26];

            for (int i = 0; i < text.Length; ++i) {
                if (showSteps) Console.WriteLine("{0} {1}", string.Join("", left), string.Join("", right));
                int index = 0;
                if (mode == Mode.ENCRYPT) {
                    index = Array.IndexOf(right, text[i]);
                    eText[i] = left[index];
                } else {
                    index = Array.IndexOf(left, text[i]);
                    eText[i] = right[index];
                }
                if (i == text.Length - 1) break;

                // permute left

                for (int j = index; j < 26; ++j) temp[j - index] = left[j];
                for (int j = 0; j < index; ++j) temp[26 - index + j] = left[j];
                var store = temp[1];
                for (int j = 2; j < 14; ++j) temp[j - 1] = temp[j];
                temp[13] = store;
                temp.CopyTo(left, 0);

                // permute right

                for (int j = index; j < 26; ++j) temp[j - index] = right[j];
                for (int j = 0; j < index; ++j) temp[26 - index + j] = right[j];
                store = temp[0];
                for (int j = 1; j < 26; ++j) temp[j - 1] = temp[j];
                temp[25] = store;
                store = temp[2];
                for (int j = 3; j < 14; ++j) temp[j - 1] = temp[j];
                temp[13] = store;
                temp.CopyTo(right, 0);
            }

            return new string(eText);
        }

        static void Main(string[] args) {
            var plainText = "WELLDONEISBETTERTHANWELLSAID";
            Console.WriteLine("The original plaintext is : {0}", plainText);
            Console.WriteLine("\nThe left and right alphabets after each permutation during encryption are :\n");
            var cipherText = Exec(plainText, Mode.ENCRYPT, true);
            Console.WriteLine("\nThe ciphertext is : {0}", cipherText);
            var plainText2 = Exec(cipherText, Mode.DECRYPT);
            Console.WriteLine("\nThe recovered plaintext is : {0}", plainText2);
        }
    }
}


println ord("a")
println chr(97)

println ord("π")
println chr(960)


// An 'a' and a 'b'
var s = "a";
var c = 98;
var h = " ";

$print("Character code for 'a': ", $sget(s, 0), "\n");

$sset(h, 0, c);
$print("Character code ", c,  ": ", h, "\n");


#include <iostream>

enum class Mode {
    ENCRYPT,
    DECRYPT,
};

const std::string L_ALPHABET = "HXUCZVAMDSLKPEFJRIGTWOBNYQ";
const std::string R_ALPHABET = "PTLNBQDEOYSFAVZKGJRIHWXUMC";

std::string exec(std::string text, Mode mode, bool showSteps = false) {
    auto left = L_ALPHABET;
    auto right = R_ALPHABET;
    auto eText = new char[text.size() + 1];
    auto temp = new char[27];

    memset(eText, 0, text.size() + 1);
    memset(temp, 0, 27);

    for (size_t i = 0; i < text.size(); i++) {
        if (showSteps) std::cout << left << ' ' << right << '\n';
        size_t index;
        if (mode == Mode::ENCRYPT) {
            index = right.find(text[i]);
            eText[i] = left[index];
        } else {
            index = left.find(text[i]);
            eText[i] = right[index];
        }
        if (i == text.size() - 1) break;

        // permute left

        for (int j = index; j < 26; ++j) temp[j - index] = left[j];
        for (int j = 0; j < index; ++j) temp[26 - index + j] = left[j];
        auto store = temp[1];
        for (int j = 2; j < 14; ++j) temp[j - 1] = temp[j];
        temp[13] = store;
        left = temp;

        // permurte right

        for (int j = index; j < 26; ++j) temp[j - index] = right[j];
        for (int j = 0; j < index; ++j) temp[26 - index + j] = right[j];
        store = temp[0];
        for (int j = 1; j < 26; ++j) temp[j - 1] = temp[j];
        temp[25] = store;
        store = temp[2];
        for (int j = 3; j < 14; ++j) temp[j - 1] = temp[j];
        temp[13] = store;
        right = temp;
    }

    return eText;
}

int main() {
    auto plainText = "WELLDONEISBETTERTHANWELLSAID";
    std::cout << "The original plaintext is : " << plainText << "\n\n";
    std::cout << "The left and right alphabets after each permutation during encryption are :\n";
    auto cipherText = exec(plainText, Mode::ENCRYPT, true);
    std::cout << "\nThe ciphertext is : " << cipherText << '\n';
    auto plainText2 = exec(cipherText, Mode::DECRYPT);
    std::cout << "\nThe recovered plaintext is : " << plainText2 << '\n';

    return 0;
}


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

runSample(arg)
return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
  -- create some sample data: character, hex and unicode
  samp = ' ' || 'a'.sequence('e') || '$' || '\xa2'.sequence('\xa5') || '\u20a0'.sequence('\u20b5')
  -- use the C2D C2X D2C and X2C built-in functions
  say "'"samp"'"
  say '   | Chr    C2D  C2X D2C X2C'
  say '---+ --- ------ ---- --- ---'
  loop ci = 1 to samp.length
    cc = samp.substr(ci, 1)
    cd = cc.c2d -- char to decimal
    cx = cc.c2x -- char to hexadecimal
    dc = cd.d2c -- decimal to char
    xc = cx.x2c -- hexadecimal to char
    say ci.right(3)"| '"cc"'" cd.right(6) cx.right(4, 0) "'"dc"' '"xc"'"
    end ci
  return


echo ord('a') # echoes 97
echo chr(97) # echoes a

import unicode

echo int("π".runeAt(0)) # echoes 960
echo Rune(960) # echoes π


import std.stdio;
import std.string;

immutable L_ALPHABET = "HXUCZVAMDSLKPEFJRIGTWOBNYQ";
immutable R_ALPHABET = "PTLNBQDEOYSFAVZKGJRIHWXUMC";

enum Mode {
    ENCRYPT,
    DECRYPT,
}

string exec(string text, Mode mode, bool showSteps = false) {
    char[] left = L_ALPHABET.dup;
    char[] right = R_ALPHABET.dup;
    char[] eText;
    eText.length = text.length;
    char[26] temp;

    foreach (i; 0..text.length) {
        if (showSteps) writeln(left, ' ', right);
        int index;
        if (mode == Mode.ENCRYPT) {
            index = right.indexOf(text[i]);
            eText[i] = left[index];
        } else {
            index = left.indexOf(text[i]);
            eText[i] = right[index];
        }
        if (i == text.length - 1) break;

        // permute left

        foreach (j; index..26) temp[j - index] = left[j];
        foreach (j; 0..index) temp[26 - index + j] = left[j];
        auto store = temp[1];
        foreach (j; 2..14) temp[j - 1] = temp[j];
        temp[13] = store;
        left = temp.dup;

        // permute right

        foreach (j; index..26) temp[j - index] = right[j];
        foreach (j; 0..index) temp[26 - index + j] = right[j];
        store = temp[0];
        foreach (j; 1..26) temp[j - 1] = temp[j];
        temp[25] = store;
        store = temp[2];
        foreach (j; 3..14) temp[j - 1] = temp[j];
        temp[13] = store;
        right = temp.dup;
    }

    return eText.idup;
}

void main() {
    auto plainText = "WELLDONEISBETTERTHANWELLSAID";
    writeln("The original plaintext is : ", plainText);
    writeln("\nThe left and right alphabets after each permutation during encryption are :\n");
    auto cipherText = exec(plainText, Mode.ENCRYPT, true);
    writeln("\nThe ciphertext is : ", cipherText);
    auto plainText2 = exec(cipherText, Mode.DECRYPT);
    writeln("\nThe recovered plaintext is : ", plainText2);
}


MODULE Ascii;
IMPORT Out;
VAR
	c: CHAR;
	d: INTEGER;
BEGIN
	c := CHR(97);
	d := ORD("a");
	Out.Int(d,3);Out.Ln;
	Out.Char(c);Out.Ln
END Ascii.


Printf.printf "%d\n" (int_of_char 'a'); (* prints "97" *)
Printf.printf "%c\n" (char_of_int 97); (* prints "a" *)


program Chaocipher;

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

type
  TMode = (mcEncrypt, mcDecrypt);

const
  lAlphabet = 'HXUCZVAMDSLKPEFJRIGTWOBNYQ';
  rAlphabet = 'PTLNBQDEOYSFAVZKGJRIHWXUMC';

function Chao(text: AnsiString; Mode: TMode; showSteps: boolean): AnsiString;
begin
  var len := Length(text);

  var left: AnsiString := lAlphabet;
  var right: AnsiString := rAlphabet;

  var eText: AnsiString;
  SetLength(eText, len);
  var temp: AnsiString;
  SetLength(temp, 26);

  for var i := 0 to len - 1 do
  begin
    if showSteps then
      writeln(left, ' ', right);

    var index := 0;

    if Mode = mcEncrypt then
    begin
      index := pos(text[i + 1], right) - 1;
      eText[i + 1] := left[index + 1];
    end
    else
    begin
      index := pos(text[i + 1], left) - 1;
      eText[i + 1] := right[index + 1];
    end;

    if i = len - 1 then
      Break;

    // premute left
    for var j := index to 25 do
      temp[j - index + 1] := left[j + 1];

    for var j := 0 to index - 1 do
      temp[27 - index + j] := left[j + 1];
    var store := temp[2];

    for var j := 2 to 13 do
      temp[j] := temp[j + 1];

    temp[14] := store;

    left := temp;

    // permute right
    for var j := index to 25 do
      temp[j - index + 1] := right[j + 1];

    for var j := 0 to index - 1 do
      temp[27 - index + j] := right[j + 1];

    store := temp[0 + 1];

    for var j := 1 to 25 do
      temp[j] := temp[j + 1];

    temp[26] := store;
    store := temp[3];

    for var j := 3 to 13 do
      temp[j] := temp[j + 1];

    temp[14] := store;

    right := temp;
  end;
  Result := eText;
end;

begin
  var plainText := 'WELLDONEISBETTERTHANWELLSAID';
  writeln('The original plaintext is :', plainText);
  write(#10'The left and right alphabets after each permutation ');
  writeln('during encryption are :'#10);
  var cipherText := Chao(plainText, mcEncrypt, true);
  writeln(#10'The ciphertext is :', cipherText);
  var plainText2 := Chao(cipherText, mcDecrypt, false);
  writeln(#10'The recovered plaintext is : ', plainText2);
  readln;
end.


MESSAGE
   CHR(97) SKIP
   ASC("a")
VIEW-AS ALERT-BOX.


{System.show &a}  %% prints "97"
{System.showInfo [97]}  %% prints "a"


// Implement Chaocipher. Nigel Galloway: July 13th., 2019
let pL n=function g when g=n->0 |g when g=(n+1)%26->13 |g->let x=(25+g-n)%26 in if x<13 then x else x+1
let pR n=function g when g=n->25 |g when g=(n+3)%26->13 |g when g=(n+1)%26->0 |g when g=(n+2)%26->1 |g->let x=(24+g-n)%26 in if x<13 then x else x+1
let encrypt lW rW txt=Array.scan(fun (lW,rW) t->let n=Array.findIndex(fun n->n=t) rW in ((Array.permute(pL n) lW,(Array.permute(pR n) rW))))(lW,rW) txt
                        |>Array.skip 1|>Array.map(fun(n,_)->n.[0])|>System.String
let decrypt lW rW txt=Array.scan(fun (_,lW,rW) t->let n=Array.findIndex(fun n->n=t) lW in ((Array.item n rW,Array.permute(pL n) lW,(Array.permute(pR n) rW))))('0',lW,rW) txt
                        |>Array.skip 1|>Array.map(fun(n,_,_)->n)|>System.String


use strict;
use warnings;
use utf8;
binmode(STDOUT, ':utf8');
use Encode;
use Unicode::UCD 'charinfo';
use List::AllUtils qw(zip natatime);

for my $c (split //, 'AΑА薵') {
    my $o = ord $c;
    my $utf8 = join '', map { sprintf "%x ", ord } split //, Encode::encode("utf8", $c);
    my $iterator = natatime 2, zip
        @{['Character', 'Character name',       'Ordinal(s)', 'Hex ordinal(s)',   'UTF-8', 'Round trip']},
        @{[ $c,          charinfo($o)->{'name'}, $o,           sprintf("0x%x",$o), $utf8,   chr $o,    ]};
    while ( my ($label, $value) = $iterator->() ) {
        printf "%14s: %s\n", $label, $value
    }
    print "\n";
}


USING: arrays combinators fry io kernel locals math namespaces
prettyprint sequences sequences.extras strings ;
IN: rosetta-code.chaocipher

CONSTANT: zenith 0
CONSTANT: nadir  13

SYMBOLS: l-alphabet r-alphabet last-index ;

: init-alphabets ( -- )
    "HXUCZVAMDSLKPEFJRIGTWOBNYQ" l-alphabet
    "PTLNBQDEOYSFAVZKGJRIHWXUMC" r-alphabet [ set ] [email protected] ;

: zero-alphabet ( seq -- seq' )
    last-index get rotate ;

: 3append ( a b c d -- abcd )
    append append append ;

:: permute-l-alphabet ( -- )
    l-alphabet get zero-alphabet dup
    zenith 1 + swap nth :> extracted-char
    {
        [ 1 head ]
        [ nadir 1 + head 2 tail ]
        [ drop extracted-char 1string ]
        [ nadir 1 + tail ]
    } cleave
    3append l-alphabet set ;

:: permute-r-alphabet ( -- )
    r-alphabet get zero-alphabet
    1 rotate dup
    zenith 2 + swap nth :> extracted-char
    {
        [ 2 head ]
        [ nadir 1 + head 3 tail ]
        [ drop extracted-char 1string ]
        [ nadir 1 + tail ]
    } cleave
    3append r-alphabet set ;

: encipher-char ( char alpha1 alpha2 -- char' )
    '[ _ get index dup last-index set _ get nth ] call ;

: encipher ( str quot -- str' )
    [ permute-l-alphabet permute-r-alphabet ] compose map
    init-alphabets ; inline

: encrypt ( str -- str' )
    [ r-alphabet l-alphabet encipher-char ] encipher ;

: decrypt ( str -- str' )
    [ l-alphabet r-alphabet encipher-char ] encipher ;

: main ( -- )
    init-alphabets
    "WELLDONEISBETTERTHANWELLSAID" encrypt dup decrypt
    [ print ] [email protected] ;

MAIN: main


package main

import(
    "fmt"
    "strings"
    "unicode/utf8"
)

type Mode int

const(
    Encrypt Mode = iota
    Decrypt
)

const(
    lAlphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"
    rAlphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC"
)

func Chao(text string, mode Mode, showSteps bool) string {
    len := len(text)
    if utf8.RuneCountInString(text) != len {
        fmt.Println("Text contains non-ASCII characters")
        return ""
    }
    left  := lAlphabet
    right := rAlphabet
    eText := make([]byte, len)
    temp  := make([]byte, 26)

    for i := 0; i < len; i++ {
        if showSteps {
            fmt.Println(left, " ", right)
        }
        var index int
        if mode == Encrypt {
            index = strings.IndexByte(right, text[i])
            eText[i] = left[index]
        } else {
            index = strings.IndexByte(left, text[i])
            eText[i] = right[index]
        }
        if i == len - 1 {
            break
        }

        // permute left
        for j := index; j < 26; j++ {
            temp[j - index] = left[j]
        }
        for j := 0; j < index; j++ {
            temp[26 - index + j] = left[j]
        }
        store := temp[1]
        for j := 2; j < 14; j++ {
            temp[j - 1] = temp[j]
        }
        temp[13] = store
        left = string(temp[:])

        // permute right

        for j := index; j < 26; j++ {
            temp[j - index] = right[j]
        }
        for j := 0; j < index; j++ {
            temp[26 - index + j] = right[j]
        }
        store = temp[0]
        for j := 1; j < 26; j++ {
            temp[j - 1] = temp[j]
        }
        temp[25] = store
        store = temp[2]
        for j := 3; j < 14; j++ {
            temp[j - 1] = temp[j]
        }
        temp[13] = store
        right = string(temp[:])
    }

    return string(eText[:])
}

func main() {
    plainText := "WELLDONEISBETTERTHANWELLSAID"
    fmt.Println("The original plaintext is :", plainText)
    fmt.Print("\nThe left and right alphabets after each permutation ")
    fmt.Println("during encryption are :\n")
    cipherText := Chao(plainText, Encrypt, true)
    fmt.Println("\nThe ciphertext is :",  cipherText)
    plainText2 := Chao(cipherText, Decrypt, false)
    fmt.Println("\nThe recovered plaintext is :", plainText2)
}


echo ord('a'), "\n"; // prints "97"
echo chr(97), "\n"; // prints "a"


main =>
  println(chr(97)),
  println(ord('a')),
  println(ord(a)).


declare 1 u union,
          2 c character (1),
          2 i fixed binary (8) unsigned;
c = 'a'; put skip list (i); /* prints 97  */
i = 97;  put skip list (c); /* prints 'a' */


?- char_code(a, X).
X = 97.

?- char_code(X, 97).
X = a.


class Chaocipher {
    private enum Mode {
        ENCRYPT,
        DECRYPT
    }

    private static final String L_ALPHABET = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"
    private static final String R_ALPHABET = "PTLNBQDEOYSFAVZKGJRIHWXUMC"

    private static int indexOf(char[] a, char c) {
        for (int i = 0; i < a.length; ++i) {
            if (a[i] == c) {
                return i
            }
        }
        return -1
    }

    private static String exec(String text, Mode mode) {
        return exec(text, mode, false)
    }

    private static String exec(String text, Mode mode, Boolean showSteps) {
        char[] left = L_ALPHABET.toCharArray()
        char[] right = R_ALPHABET.toCharArray()
        char[] eText = new char[text.length()]
        char[] temp = new char[26]

        for (int i = 0; i < text.length(); ++i) {
            if (showSteps) {
                println("${new String(left)}  ${new String(right)}")
            }
            int index
            if (mode == Mode.ENCRYPT) {
                index = indexOf(right, text.charAt(i))
                eText[i] = left[index]
            } else {
                index = indexOf(left, text.charAt(i))
                eText[i] = right[index]
            }
            if (i == text.length() - 1) {
                break
            }

            // permute left

            if (26 - index >= 0) System.arraycopy(left, index, temp, 0, 26 - index)
            System.arraycopy(left, 0, temp, 26 - index, index)
            char store = temp[1]
            System.arraycopy(temp, 2, temp, 1, 12)
            temp[13] = store
            left = Arrays.copyOf(temp, temp.length)

            // permute right

            if (26 - index >= 0) System.arraycopy(right, index, temp, 0, 26 - index)
            System.arraycopy(right, 0, temp, 26 - index, index)
            store = temp[0]
            System.arraycopy(temp, 1, temp, 0, 25)
            temp[25] = store
            store = temp[2]
            System.arraycopy(temp, 3, temp, 2, 11)
            temp[13] = store
            right = Arrays.copyOf(temp, temp.length)
        }

        return new String(eText)
    }

    static void main(String[] args) {
        String plainText = "WELLDONEISBETTERTHANWELLSAID"
        println("The original plaintext is : $plainText")
        println("\nThe left and right alphabets after each permutation during encryption are:")
        String cipherText = exec(plainText, Mode.ENCRYPT, true)
        println("\nThe cipher text is : $cipherText")
        String plainText2 = exec(cipherText, Mode.DECRYPT)
        println("\nThe recovered plaintext is : $plainText2")
    }
}


If OpenConsole()
  ;Results are the same when compiled for Ascii or Unicode
  charCode.c = 97
  Char.s = "a"
  PrintN(Chr(charCode))   ;prints a
  PrintN(Str(Asc(Char)))  ;prints 97

  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
  Input()
  CloseConsole()
EndIf


print ord('a') # prints "97"
print chr(97)  # prints "a"


Welcome to Quackery.

Enter "leave" to leave the shell.

/O> char a
...

Stack: 97

/O> emit
...
a
Stack empty.


import Data.List (elemIndex)

chao :: Eq a => [a] -> [a] -> Bool -> [a] -> [a]
chao _ _ _ [] = []
chao l r plain (x : xs) = maybe [] go (elemIndex x src)
  where
    (src, dst)
      | plain = (l, r)
      | otherwise = (r, l)
    go n =
      dst !! n :
      chao
        (shifted 1 14 (rotated n l))
        ((shifted 2 14 . shifted 0 26) (rotated n r))
        plain
        xs

rotated :: Int -> [a] -> [a]
rotated n = take . length <*> drop n . cycle

shifted :: Int -> Int -> [a] -> [a]
shifted src dst s = concat [x, rotated 1 y, b]
  where
    (a, b) = splitAt dst s
    (x, y) = splitAt src a

encode, decode :: Bool
encode = False
decode = True

main :: IO ()
main = do
  let chaoWheels =
        chao
          "HXUCZVAMDSLKPEFJRIGTWOBNYQ"
          "PTLNBQDEOYSFAVZKGJRIHWXUMC"
      plainText = "WELLDONEISBETTERTHANWELLSAID"
      cipherText = chaoWheels encode plainText
  mapM_
    print
    [ plainText,
      cipherText,
      chaoWheels decode cipherText
    ]


ascii <- as.integer(charToRaw("hello world")); ascii
text <- rawToChar(as.raw(ascii)); text


#lang racket

(define (code ch)
  (printf "The unicode number for ~s is ~a\n" ch (char->integer ch)))
(code #\a)
(code #\λ)

(define (char n)
  (printf "The unicode number ~a is the character ~s\n" n (integer->char n)))
(char 97)
(char 955)


for 'AΑА𪚥🇺🇸👨👩👧👦'.comb {
    .put for
    [ 'Character',
      'Character name',
      'Unicode property',
      'Unicode script',
      'Unicode block',
      'Ordinal(s)',
      'Hex ordinal(s)',
      'UTF-8',
      'UTF-16LE',
      'UTF-16BE',
      'Round trip by name',
      'Round trip by ordinal'
    ]».fmt('%21s:')
    Z
    [ $_,
      .uninames.join(', '),
      .uniprops.join(', '),
      .uniprops('Script').join(', '),
      .uniprops('Block').join(', '),
      .ords,
      .ords.fmt('0x%X'),
      .encode('utf8'   )».fmt('%02X'),
      .encode('utf16le')».fmt('%02X').join.comb(4),
      .encode('utf16be')».fmt('%02X').join.comb(4),
      .uninames».uniparse.join,
      .ords.chrs
    ];
    say '';
}


import java.util.Arrays;

public class Chaocipher {
    private enum Mode {
        ENCRYPT,
        DECRYPT
    }

    private static final String L_ALPHABET = "HXUCZVAMDSLKPEFJRIGTWOBNYQ";
    private static final String R_ALPHABET = "PTLNBQDEOYSFAVZKGJRIHWXUMC";

    private static int indexOf(char[] a, char c) {
        for (int i = 0; i < a.length; ++i) {
            if (a[i] == c) {
                return i;
            }
        }
        return -1;
    }

    private static String exec(String text, Mode mode) {
        return exec(text, mode, false);
    }

    private static String exec(String text, Mode mode, Boolean showSteps) {
        char[] left = L_ALPHABET.toCharArray();
        char[] right = R_ALPHABET.toCharArray();
        char[] eText = new char[text.length()];
        char[] temp = new char[26];

        for (int i = 0; i < text.length(); ++i) {
            if (showSteps) {
                System.out.printf("%s  %s\n", new String(left), new String(right));
            }
            int index;
            if (mode == Mode.ENCRYPT) {
                index = indexOf(right, text.charAt(i));
                eText[i] = left[index];
            } else {
                index = indexOf(left, text.charAt(i));
                eText[i] = right[index];
            }
            if (i == text.length() - 1) {
                break;
            }

            // permute left

            if (26 - index >= 0) System.arraycopy(left, index, temp, 0, 26 - index);
            System.arraycopy(left, 0, temp, 26 - index, index);
            char store = temp[1];
            System.arraycopy(temp, 2, temp, 1, 12);
            temp[13] = store;
            left = Arrays.copyOf(temp, temp.length);

            // permute right

            if (26 - index >= 0) System.arraycopy(right, index, temp, 0, 26 - index);
            System.arraycopy(right, 0, temp, 26 - index, index);
            store = temp[0];
            System.arraycopy(temp, 1, temp, 0, 25);
            temp[25] = store;
            store = temp[2];
            System.arraycopy(temp, 3, temp, 2, 11);
            temp[13] = store;
            right = Arrays.copyOf(temp, temp.length);
        }

        return new String(eText);
    }

    public static void main(String[] args) {
        String plainText = "WELLDONEISBETTERTHANWELLSAID";
        System.out.printf("The original plaintext is : %s\n", plainText);
        System.out.println("\nThe left and right alphabets after each permutation during encryption are:");
        String cipherText = exec(plainText, Mode.ENCRYPT, true);
        System.out.printf("\nThe cipher text is : %s\n", cipherText);
        String plainText2 = exec(cipherText, Mode.DECRYPT);
        System.out.printf("\nThe recovered plaintext is : %s\n", plainText2);
    }
}


Red []
print to-integer first "a" ;; -> 97
print to-integer #"a"      ;; -> 97
print to-binary "a"        ;; -> #{61}
print to-char 97           ;; -> a


/*REXX program displays a char's ASCII code/value (or EBCDIC if run on an EBCDIC system)*/
yyy= 'c'                               /*assign a lowercase       c        to   YYY.    */
yyy= "c"                               /* (same as above)                               */
say  'from char, yyy code=' yyy

yyy= '63'x                             /*assign hexadecimal      63        to   YYY.    */
yyy= '63'X                             /* (same as above)                               */
say  'from  hex, yyy code=' yyy

yyy= x2c(63)                           /*assign hexadecimal      63        to   YYY.    */
say  'from  hex, yyy code=' yyy

yyy= '01100011'b                       /*assign a binary      0011 0100    to   YYY.    */
yyy= '0110 0011'b                      /* (same as above)                               */
yyy= '0110 0011'B                      /*   "   "    "                                  */
say  'from  bin, yyy code=' yyy

yyy= d2c(99)                           /*assign decimal code     99        to   YYY.    */
say  'from  dec, yyy code=' yyy

say                                    /*     [↓]    displays the value of  YYY  in ··· */
say  'char code: '   yyy               /* character code  (as an 8-bit ASCII character).*/
say  ' hex code: '   c2x(yyy)          /*    hexadecimal                                */
say  ' dec code: '   c2d(yyy)          /*        decimal                                */
say  ' bin code: '   x2b( c2x(yyy) )   /*         binary  (as a bit string)             */
                                       /*stick a fork in it, we're all done with display*/


reset =:  verb define
  LEFT  =:  'HXUCZVAMDSLKPEFJRIGTWOBNYQ'
  RIGHT =:  'PTLNBQDEOYSFAVZKGJRIHWXUMC'
)

enc =:  verb define
  z =.  LEFT  {~ i =. RIGHT i. y
  permute {. i
  z
)

dec =:  verb define
  z =.  RIGHT {~ i =. LEFT i. y
  permute {. i
  z
)

permute =: verb define
  LEFT  =:  LEFT  |.~ - y
  LEFT  =:  (1 |. 13 {. LEFT) , 13 }. LEFT

  RIGHT =:  RIGHT |.~ - y + 1
  RIGHT =:  ({. RIGHT) , (1 |. RIGHT {~ 2+i.12) , 13 }. RIGHT
)

chao =:  enc :. dec

reset ''
smoutput E =.  chao 'WELLDONEISBETTERTHANWELLSAID'
reset ''
smoutput D =.  chao^:_1 E


const L_ALPHABET = "HXUCZVAMDSLKPEFJRIGTWOBNYQ";
const R_ALPHABET = "PTLNBQDEOYSFAVZKGJRIHWXUMC";

const ENCRYPT = 0;
const DECRYPT = 1;

function setCharAt(str, index, chr) {
    if (index > str.length - 1) return str;
    return str.substr(0, index) + chr + str.substr(index + 1);
}

function chao(text, mode, show_steps) {
    var left = L_ALPHABET;
    var right = R_ALPHABET;
    var out = text;
    var temp = "01234567890123456789012345";
    var i = 0;
    var index, j, store;

    if (show_steps) {
        console.log("The left and right alphabets after each permutation during encryption are :");
    }
    while (i < text.length) {
        if (show_steps) {
            console.log(left + "  " + right);
        }
        if (mode == ENCRYPT) {
            index = right.indexOf(text[i]);
            out = setCharAt(out, i, left[index]);
        } else {
            index = left.indexOf(text[i]);
            out = setCharAt(out, i, right[index]);
        }
        if (i == text.length - 1) {
            break;
        }

        //permute left
        j = index;
        while (j < 26) {
            temp = setCharAt(temp, j - index, left[j])
            j += 1;
        }
        j = 0;
        while (j < index) {
            temp = setCharAt(temp, 26 - index + j, left[j]);
            j += 1;
        }
        store = temp[1];
        j = 2;
        while (j < 14) {
            temp = setCharAt(temp, j - 1, temp[j]);
            j += 1;
        }
        temp = setCharAt(temp, 13, store);
        left = temp;

        //permute right
        j = index;
        while (j < 26) {
            temp = setCharAt(temp, j - index, right[j]);
            j += 1;
        }
        j = 0;
        while (j < index) {
            temp = setCharAt(temp, 26 - index + j, right[j]);
            j += 1;
        }
        store = temp[0];
        j = 1;
        while (j < 26) {
            temp = setCharAt(temp, j - 1, temp[j]);
            j += 1;
        }
        temp = setCharAt(temp, 25, store);
        store = temp[2];
        j = 3;
        while (j < 14) {
            temp = setCharAt(temp, j - 1, temp[j]);
            j += 1;
        }
        temp = setCharAt(temp, 13, store);
        right = temp;

        i += 1;
    }

    return out;
}

function main() {
    var out = document.getElementById("content");
    const plain_text = "WELLDONEISBETTERTHANWELLSAID";

    out.innerHTML = "
The original plaintext is : " + plain_text + "
";
    var cipher_text = chao(plain_text, ENCRYPT, true);
    out.innerHTML += "
The ciphertext is : " + cipher_text + "
";
    var decipher_text = chao(cipher_text, DECRYPT, false);
    out.innerHTML += "
The recovered plaintext is : " + decipher_text + "
";
}


print chr$(97) 'prints a
print asc("a") 'prints 97


use std::char::from_u32;

fn main() {
    //ascii char
    println!("{}", 'a' as u8);
    println!("{}", 97 as char);

    //unicode char
    println!("{}", 'π' as u32);
    println!("{}", from_u32(960).unwrap());
}


const leftalphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"
const rightalphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC"

function chacocoding(text, encoding, verbose=false)
    left, right = Vector{Char}(leftalphabet), Vector{Char}(rightalphabet)
    len, coded = length(text), similar(Vector{Char}(text))
    for i in 1:len
        verbose && println(String(left), "   ", String(right))
        n = indexin(text[i], encoding ? right : left)[1]
        coded[i] = encoding ? left[n] : right[n]
        if i < len
            left .= circshift(left, -n + 1)
            left[2:14] .= circshift(left[2:14], -1)
            right .= circshift(right, -n)
            right[3:14] .= circshift(right[3:14], -1)
        end
    end
    String(coded)
end

function testchacocipher(txt)
    println("The original plaintext is: $txt")
    println("\nThe left and right alphabets for each character during encryption are:")
    encoded = chacocoding(txt, true, true)
    println("\nThe encoded ciphertext is: $encoded")
    decoded = chacocoding(encoded, false)
    println("\nDecoded, the recovered plaintext is: $decoded")
end

testchacocipher("WELLDONEISBETTERTHANWELLSAID")


// Version 1.2.40

enum class Mode { ENCRYPT, DECRYPT }

object Chao {
    private val lAlphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"
    private val rAlphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC"

    fun exec(text: String, mode: Mode, showSteps: Boolean = false): String {
        var left  = lAlphabet
        var right = rAlphabet
        val eText = CharArray(text.length)
        val temp  = CharArray(26)

        for (i in 0 until text.length) {
            if (showSteps) println("$left  $right")
            var index: Int
            if (mode == Mode.ENCRYPT) {
                index = right.indexOf(text[i])
                eText[i] = left[index]
            }
            else {
                index = left.indexOf(text[i])
                eText[i] = right[index]
            }
            if (i == text.length - 1) break

            // permute left

            for (j in index..25) temp[j - index] = left[j]
            for (j in 0 until index) temp[26 - index + j] = left[j]
            var store = temp[1]
            for (j in 2..13) temp[j - 1] = temp[j]
            temp[13] = store
            left = String(temp)

            // permute right

            for (j in index..25) temp[j - index] = right[j]
            for (j in 0 until index) temp[26 - index + j] = right[j]
            store = temp[0]
            for (j in 1..25) temp[j - 1] = temp[j]
            temp[25] = store
            store = temp[2]
            for (j in 3..13) temp[j - 1] = temp[j]
            temp[13] = store
            right = String(temp)
        }

        return String(eText)
    }
}

fun main(args: Array<String>) {
    val plainText = "WELLDONEISBETTERTHANWELLSAID"
    println("The original plaintext is : $plainText")
    println("\nThe left and right alphabets after each permutation" +
             " during encryption are :\n")
    val cipherText = Chao.exec(plainText, Mode.ENCRYPT, true)
    println("\nThe ciphertext is : $cipherText")
    val plainText2 = Chao.exec(cipherText, Mode.DECRYPT)
    println("\nThe recovered plaintext is : $plainText2")
}


class MAIN is
  main is
    #OUT + 'a'.int + "\n"; -- or
    #OUT + 'a'.ascii_int + "\n";
    #OUT + CHAR::from_ascii_int(97) + "\n";
  end;
end;


scala> 'a' toInt
res2: Int = 97

scala> 97 toChar
res3: Char = a

scala> '\u0061'
res4: Char = a

scala> "\uD869\uDEA5"
res5: String = 𪚥


(display (char->integer #\a)) (newline) ; prints "97"
(display (integer->char 97)) (newline) ; prints "a"


-- Chaocipher, in Lua, 6/19/2020 db
local Chaocipher = {
  ct = "HXUCZVAMDSLKPEFJRIGTWOBNYQ",
  pt = "PTLNBQDEOYSFAVZKGJRIHWXUMC",
  encrypt = function(self, text) return self:_encdec(text, true) end,
  decrypt = function(self, text) return self:_encdec(text, false) end,
  _encdec = function(self, text, encflag)
    local ct, pt, s = self.ct, self.pt, ""
    local cshl = function(s,i) return s:sub(i) .. s:sub(1,i-1) end
    local sshl = function(s,i) return s:sub(1,i-1) .. s:sub(i+1,14) .. s:sub(i,i) .. s:sub(15) end
    for ch in text:gmatch(".") do
      local i = (encflag and pt or ct):find(ch)
      s = s .. (encflag and ct or pt):sub(i,i)
      if encflag then print(ct, pt, ct:sub(i,i), pt:sub(i,i)) end
      ct, pt = sshl(cshl(ct, i), 2), sshl(cshl(pt, i+1), 3)
    end
    return s
  end,
}
local plainText = "WELLDONEISBETTERTHANWELLSAID"
local encryptText = Chaocipher:encrypt(plainText)
local decryptText = Chaocipher:decrypt(encryptText)
print()
print("The original text was:  " .. plainText)
print("The encrypted text is:  " .. encryptText)
print("The decrypted text is:  " .. decryptText)


ClearAll[ichaoalphabet, iMoveToFront, ChaoCipher]
ichaoalphabet = CharacterRange["A", "Z"];
iMoveToFront[l_List, sel_] := Module[{p},
  p = FirstPosition[l, sel];
  RotateLeft[l, p - 1]
  ]
ChaoCipher::wrongcipheralpha =
  "The cipher alphabet `1` is not a permutation of \
\"A\"\[LongDash]\"Z\".";
ChaoCipher::wrongplainalpha =
  "The plain alphabet `1` is not a permutation of \"A\"\[LongDash]\"Z\
\".";
ChaoCipher[str_String, {plainalpha_List, cipheralpha_List}] :=
 Module[{pa, ca, plain, new, papermute, capermute, out},
  ca = ToUpperCase[cipheralpha];
  pa = ToUpperCase[plainalpha];
  If[Sort[ca] =!= Sort[ichaoalphabet],
   Message[ChaoCipher::wrongcipheralpha, ca];
   $Failed
   ,
   If[Sort[pa] =!= Sort[ichaoalphabet],
    Message[ChaoCipher::wrongplainalpha, pa];
    $Failed
    ,
    capermute = SubsetMap[RotateLeft, Range[26], Range[2, 14]];
    papermute =
     SubsetMap[RotateLeft, RotateLeft[Range[26], 1], Range[3, 14]];
    plain =
     Select[Characters[ToUpperCase[str]], MemberQ[ichaoalphabet, #] &];

    out = Table[
      new = Association[Thread[pa -> ca]][p];
      pa = iMoveToFront[pa, p];
      ca = iMoveToFront[ca, new];
      pa = pa[[papermute]];
      ca = ca[[capermute]];
      new
      ,
      {p, plain}
      ];
    StringJoin[out]
    ]
   ]
  ]
ChaoCipher["WELLDONEISBETTERTHANWELLSAID",{[email protected]"PTLNBQDEOYSFAVZKGJRIHWXUMC",[email protected]"HXUCZVAMDSLKPEFJRIGTWOBNYQ"}]


cmd:>asciiToInt('a')
97
cmd:>intToAscii(97)
'a'


($a asInteger) displayNl. "output 97"
(Character value: 97) displayNl. "output a"


import strformat

type
  Mode = enum
    Encrypt
    Decrypt

const lAlphabet: string = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"
const rAlphabet: string = "PTLNBQDEOYSFAVZKGJRIHWXUMC"

proc chao(text: string, mode: Mode, verbose: bool = false): string =
  var left = lAlphabet
  var right = rAlphabet
  var eText = newSeq[char](text.len)
  var temp: array[26, char]

  for i in 0..<text.len:
    if verbose:
      echo &"{left}  {right}"
    var index: int
    if mode == Encrypt:
      index = right.find(text[i])
      eText[i] = left[index]
    else:
      index = left.find(text[i])
      eText[i] = right[index]
    if (i == text.len - 1):
      break

    # permute left
    for j in index..25:
      temp[j - index] = left[j]
    for j in 0..<index:
      temp[26 - index + j] = left[j]
    var store = temp[1]
    for j in 2..13:
      temp[j - 1] = temp[j]
    temp[13] = store
    left = ""
    for i in temp:
      left &= $i

    # permute right
    for j in index..25:
      temp[j - index] = right[j]
    for j in 0..<index:
      temp[26 - index + j] = right[j]
    store = temp[0]
    for j in 1..25:
      temp[j - 1] = temp[j]
    temp[25] = store
    store = temp[2]
    for j in 3..13:
      temp[j - 1] = temp[j]
    temp[13] = store
    right = ""
    for i in temp:
      right &= $i

  for i in eText:
    result &= $i

var plainText = "WELLDONEISBETTERTHANWELLSAID"
echo &"The original plaintext is: {plainText}"
echo "\nThe left and right alphabets after each permutation during encryption are:\n"
var cipherText = chao(plainText, Encrypt, true)
echo &"\nThe ciphertext is: {cipherText}"
var plainText2 = chao(cipherText, Decrypt, false)
echo &"\nThe recovered plaintext is: {plainText2}"


class Chaocipher {
  L_ALPHABET : static : Char[];
  R_ALPHABET : static : Char[];

  function : Main(args : String[]) ~ Nil {
    L_ALPHABET := "HXUCZVAMDSLKPEFJRIGTWOBNYQ"->ToCharArray();
    R_ALPHABET := "PTLNBQDEOYSFAVZKGJRIHWXUMC"->ToCharArray();
    plainText := "WELLDONEISBETTERTHANWELLSAID"->ToCharArray();

    System.IO.Console->Print("The original plaintext is: ")->PrintLine(plainText);
    "\nThe left and right alphabets after each permutation during encryption are:\n"->PrintLine();
    cipherText := Chao(plainText, Mode->ENCRYPT, true);
    System.IO.Console->Print("\nThe ciphertext is: ")->PrintLine(cipherText);
    plainText2 := Chao(cipherText, Mode->DECRYPT, false);
    System.IO.Console->Print("The recovered plaintext is: ")->PrintLine(plainText2);
  }

  function : Chao(in : Char[], mode : Mode, show_steps : Bool) ~ Char[] {
    i : Int; j : Int; index : Int;
    store : Char;
    len := in->Size();
    left := Char->New[26];   right := Char->New[26]; temp := Char->New[26];
    eText := Char->New[len];

    Runtime->Copy(left, 0, L_ALPHABET, 0, L_ALPHABET->Size());
    Runtime->Copy(right, 0, R_ALPHABET, 0, R_ALPHABET->Size());

    for(i := 0; i < len; i += 1;) {
      if (show_steps) {
        System.IO.Console->Print(left)->Print(' ')->PrintLine(right);
      };
      if (mode = Mode->ENCRYPT) {
        index := IndexOf(right, in[i]);
        eText[i] := left[index];
      }
      else {
        index := IndexOf(left, in[i]);
        eText[i] := right[index];
      };

      if (i = len - 1) {
        break;
      };

      # left
      for(j := index; j < 26; j += 1;) { temp[j - index] := left[j]; };
      for(j :=0; j < index; j += 1;) { temp[26 - index + j] := left[j]; };
      store := temp[1];
      for(j := 2; j < 14; j += 1;) { temp[j - 1] := temp[j]; };
      temp[13] := store;
      Runtime->Copy(left, 0, temp, 0, temp->Size());

      # right
      for(j := index; j < 26; j += 1;) { temp[j - index] := right[j]; };
      for(j :=0; j < index; j += 1;) { temp[26 - index + j] := right[j]; };
      store := temp[0];
      for(j :=1; j < 26; j += 1;) { temp[j - 1] := temp[j]; };
          temp[25] := store;
          store := temp[2];
          for(j := 3; j < 14; j += 1;) { temp[j - 1] := temp[j]; };
          temp[13] := store;
          Runtime->Copy(right, 0, temp, 0, temp->Size());
    };

    return eText;
  }

  function : IndexOf(str : Char[], c : Char) ~ Int {
    for(i := 0; i < str->Size(); i += 1;) {
      if(c = str[i]) {
        return i;
      };
    };

    return -1;
  }

  enum Mode { ENCRYPT, DECRYPT }
}


        define('chr(n)') :(chr_end)
chr     &alphabet tab(n) len(1) . chr :s(return)f(freturn)
chr_end

        define('asc(str)c') :(asc_end)
asc     str len(1) . c
        &alphabet break(c) @asc :s(return)f(freturn)
asc_end

*       # Test and display
        output = char(65) ;* Built-in
        output = chr(65)
        output = asc('A')
end


print (Int.toString (ord #"a") ^ "\n"); (* prints "97" *)
print (Char.toString (chr 97) ^ "\n"); (* prints "a" *)


program chaocipher(input, output);

const
	{ This denotes a `set` literal: }
	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'];
	{ The `card` function is an Extended Pascal (ISO 10206) extension. }
	alphabetCardinality = card(alphabet);
	{ 1st character denotes “zenith”. }
	zenith = 1;
	{ In a 26-character alphabet the 14th character denotes “nadir”. }
	nadir = alphabetCardinality div 2 + 1;
	{ For simplicity use compile-time-defined maximum lengths. }
	messageMaximumLength = 80;

type
	{ This “discriminates” the Extended Pascal schema data type `string` to be }
	{ capable of holding strings up to `alphabetCardinality` `char` values. }
	map = string(alphabetCardinality);
	{ Variables of this data type can only assume integer values within 1..26: }
	mapCharacterIndex = 1..alphabetCardinality;
	{ Later used as a buffer for the input/output. }
	message = string(messageMaximumLength);
	messageCharacterIndex = 1..messageMaximumLength;
	{ Stores a key for the Chaocipher algorithm. }
	key = record
			cipherText: map;
			plainText: map;
		end;

{ --- auxilliary routines ---------------------------------------------- }

{
	\brief verifies that a key is valid for the Chaocipher
	\param sample a potential `key` for a Chaocipher
	\return `true` iff \param sample is an acceptable `key`
}
{ `protected` (Extended Pascal extension) denotes an immutable parameter. }
function isValid(protected sample: key): Boolean;
	{ Determines whether a `map` contains all characters of `alphabet`. }
	{ Nesting this function allows for a neat expression below. }
	function isComplete(protected text: map): Boolean;
	var
		i: integer;
		{ `value []` will initialize this variable to an empty set value. }
		{ This is an Extended Pascal (ISO 10206) extension. }
		s: set of char value [];
	begin
		{ NB: In Pascal `for`-loop limits are inclusive. }
		for i := 1 to length(text) do
		begin
			{ This adds the set containing one character to the set `s`. }
			s := s + [text[i]]
		end;
		isComplete := card(s) = alphabetCardinality
	end;
begin
	{ This way `sample.cipherText` can be simply written as `cipherText`. }
	with sample do
	begin
		{ `and_then` is an EP extension indicating “lazy evaluation”. }
		isValid := (alphabetCardinality > 8) and_then
			isComplete(cipherText) and_then isComplete(plainText)
	end
end;

{
	\brief permutes a key for the next encryption/decryption step
	\param shift the index of the characters just substituted
}
{ `var` means the parameter value will be modified _at_ the call site. }
procedure permute(var state: key; protected shift: mapCharacterIndex);
begin
	with state do
	begin
		{ Indices in `cipherText[1..pred(shift)]` _must_ be non-descending: }
		if shift > 1 then
		begin
			cipherText := subStr(cipherText, shift) + cipherText[1..pred(shift)]
			{ `subStr(str, ini)` is equivalent to `str[ini..length(str)]`. }
		end;
		{ Likewise, `succ(shift)` must be a valid index in `plainText`: }
		if shift < alphabetCardinality then
		begin
			plainText := subStr(plainText, succ(shift)) + plainText[1..shift]
		end;

		{ If it does _not_ _alter_ the _entire_ string’s _length_, you can }
		{ modify parts of a string like this (Extended Pascal extension): }
		cipherText[zenith+1..nadir] := cipherText[zenith+2..nadir] + cipherText[zenith+1];
		plainText[zenith+2..nadir] := plainText[zenith+3..nadir] + plainText[zenith+2]
	end
end;

{ --- the core routine of the algorithm -------------------------------- }

{
	\brief performs Chaocipher common steps
	\param line the message to encrypt/decrypt
	\param state the initial key to start encrpytion/decryption with
	\param locate a function determining the 2-tuple index in the key
	\param substitute the procedure substituting the correct characters
}
procedure chaocipher(
		var line: message;
		var state: key;
		{ These are “routine parameters”. Essentially the address of a routine }
		{ matching the specified routine signature is passed to `chaocipher`. }
		function locate(protected i: messageCharacterIndex): mapCharacterIndex;
		procedure substitute(
				protected i: messageCharacterIndex;
				protected z: mapCharacterIndex
			)
	);
var
	{ For demonstration purposes: In this program }
	{ `line.capacity` refers to `messageMaximumLength`. }
	i: 1..line.capacity;
	substitutionPairIndex: mapCharacterIndex;
begin
	{ Don’t trust user input, even though this is just a RosettaCode example. }
	if not isValid(state) then
	begin
		writeLn('Error: Key is invalid. Got:');
		writeLn('Cipher text: ', state.cipherText);
		writeLn(' Plain text: ', state.plainText);
		halt
	end;

	for i := 1 to length(line) do
	begin
		{ We’ll better skip characters that aren’t in the `alphabet`. }
		if line[i] in alphabet then
		begin
			{ Here you see the beauty of using routine parameters. }
			{ Depending on whether we’re encrypting or decrypting, }
			{ you need to find a character in the `cipherText` or }
			{ `plainText` key value respectively, yet the basic order
			{ of the steps are still the same. }
			substitutionPairIndex := locate(i);
			substitute(i, substitutionPairIndex);
			permute(state, substitutionPairIndex)
		end
	end
end;

{ --- entry routines --------------------------------------------------- }

{
	\brief encrypts a message according to Chaocipher
	\param line a message to encrypt
	\param state the key to begin with
	\return the encrypted message \param line using the provided key
}
{ Note: without `var` or `protected` both `encrypt` and `decrypt`get }
{       and have their own independent copies of the parameter values. }
function encrypt(line: message; state: key): message;
	function encryptor(protected i: messageCharacterIndex): mapCharacterIndex;
	begin
		encryptor := index(state.plainText, line[i])
	end;
	procedure substitutor(
			protected i: messageCharacterIndex;
			protected z: mapCharacterIndex
		);
	begin
		line[i] := state.cipherText[z]
	end;
begin
	chaocipher(line, state, encryptor, substitutor);
	encrypt := line
end;

{
	\brief decrypts a message according to Chaocipher
	\param line the encrypted message
	\param state the key to begin with
	\return the decrypted message \param line using the provided key
}
function decrypt(line: message; state: key): message;
	function decryptor(protected i: messageCharacterIndex): mapCharacterIndex;
	begin
		decryptor := index(state.cipherText, line[i])
	end;
	procedure substitutor(
			protected i: messageCharacterIndex;
			protected z: mapCharacterIndex
		);
	begin
		line[i] := state.plainText[z]
	end;
begin
	chaocipher(line, state, decryptor, substitutor);
	decrypt := line
end;

{ === MAIN ============================================================= }
var
	exampleKey: key;
	line: message;
begin
	{ Instead of writing `exampleKey.cipherText := '…', you can }
	{ write in Extended Pascal a `record` literal like this: }
	exampleKey := key[
			cipherText: 'HXUCZVAMDSLKPEFJRIGTWOBNYQ';
			plainText: 'PTLNBQDEOYSFAVZKGJRIHWXUMC';
		];

	{ `EOF` is shorthand for `EOF(input)`. }
	while not EOF do
	begin
		{ `readLn(line)` is shorthand for `readLn(input, line)`. }
		readLn(line);
		line := encrypt(line, exampleKey);
		writeLn(decrypt(line, exampleKey));
		{ Likewise, `writeLn(line)` is short for `writeLn(output, line)`. }
		writeLn(line)
	end
end.


let c1: UnicodeScalar = "a"
println(c1.value) // prints "97"
let c2: UnicodeScalar = "π"
println(c2.value) // prints "960"


'abc' -> $::asCodePoints -> !OUT::write
'$#10;' -> !OUT::write
'$#97;' -> !OUT::write


# ASCII
puts [scan "a" %c]   ;# ==> 97
puts [format %c 97]  ;# ==> a
# Unicode is the same
puts [scan "π" %c]   ;# ==> 960
puts [format %c 960] ;# ==> π


"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789→Str1
Disp inString(Str1,"A
Input "CODE? ",A
Disp sub(Str1,A,1


sub init {
    @left  = split '', 'HXUCZVAMDSLKPEFJRIGTWOBNYQ';
    @right = split '', 'PTLNBQDEOYSFAVZKGJRIHWXUMC';
}

sub encode {
    my($letter) = @_;
    my $index = index join('', @right), $letter;
    my $enc   = $left[$index];
    left_permute($index);
    right_permute($index);
    $enc
}

sub decode {
    my($letter) = @_;
    my $index = index join('', @left), $letter;
    my $dec   = $right[$index];
    left_permute($index);
    right_permute($index);
    $dec
}

sub right_permute {
    my($index) = @_;
    rotate(\@right, $index + 1);
    rotate(\@right, 1, 2, 13);
}

sub left_permute {
    my($index) = @_;
    rotate(\@left, $index);
    rotate(\@left, 1, 1, 13);
}

sub rotate {
    our @list; local *list = shift;
    my($n,$s,$e) = @_;
    @list = $s ? @list[0..$s-1, $s+$n..$e+$n-1, $s..$s+$n-1, $e+1..$#list]
               : @list[$n..$#list, 0..$n-1]
}

init; $e_msg .= encode($_) for split '', 'WELLDONEISBETTERTHANWELLSAID';
init; $d_msg .= decode($_) for split '', $e_msg;

print "$e_msg\n";
print "$d_msg\n";


Prgm
  Local k, s
  ClrIO
  Loop
    Disp "Press a key, or ON to exit."
    getKey() © clear buffer
    0 → k : While k = 0 : getKey() → k : EndWhile
    ClrIO
    If k ≥ 256 Then
      Disp "Not a character."
      Disp "Code: " & string(k)
    Else

      char(k) → s                           ©
      © char() and ord() are inverses.      ©
      Disp "Character: " & s                ©
      Disp "Code: " & string(ord(s))        ©

    EndIf
  EndLoop
EndPrgm


$$ MODE TUSCRIPT
SET character ="a", code=DECODE (character,byte)
PRINT character,"=",code


z = ORD("a") : PRINT CHR(z)    ' Prints "a"


# outputs the character value for 'a'
out (ord "a") endl console
# outputs the character 'a' given its value
out (chr 97) endl console


-- demo\rosetta\Chao_cipher.exw
with javascript_semantics
constant l_alphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ",
         r_alphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC"

enum ENCRYPT, DECRYPT

function chao_cipher(string s, integer mode, bool show_steps)
    integer len = length(s)
    string out = repeat(' ',len),
           left = l_alphabet,
           right = r_alphabet
    for i=1 to len do
        if show_steps then printf(1,"%s  %s\n", {left, right}) end if
        integer index = find(s[i],iff(mode==ENCRYPT?right:left))
        out[i] = iff(mode==ENCRYPT?left:right)[index]

        if i==len then exit end if

        /* permute left */
        left = left[index..26]&left[1..index-1]
        left[2..14] = left[3..14]&left[2]

        /* permute right */
        right = right[index+1..26]&right[1..index]
        right[3..14] = right[4..14]&right[3]
    end for
    return out
end function

string plain_text = "WELLDONEISBETTERTHANWELLSAID"
printf(1,"The original plaintext is : %s\n", {plain_text})

--printf(1,"\nThe left and right alphabets after each permutation"&
--       " during encryption are :\n\n")
--string cipher_text = chao_cipher(plain_text, ENCRYPT, true)
string cipher_text = chao_cipher(plain_text, ENCRYPT, false)
printf(1,"\nThe ciphertext is : %s\n", {cipher_text})

string plain_text2 = chao_cipher(cipher_text, DECRYPT, false)
printf(1,"\nThe recovered plaintext is : %s\n", {plain_text2})


#import std
#import nat

chr = -: num characters
asc = -:@rlXS num characters

#cast %cnX

test = (chr97,asc`a)


Debug.Print Chr(97) 'Prints a
Debug.Print [Code("a")] ' Prints 97


'prints a
WScript.StdOut.WriteLine Chr(97)

'prints 97
WScript.StdOut.WriteLine Asc("a")


"encoding is set to utf-8
echo char2nr("a")
"Prints 97

echo nr2char(97)
"Prints a


Console.WriteLine(Chr(97)) 'Prints a
Console.WriteLine(Asc("a")) 'Prints 97


# Python3 implementation of Chaocipher
# left wheel = ciphertext wheel
# right wheel = plaintext wheel

def main():
    # letters only! makealpha(key) helps generate lalpha/ralpha.
    lalpha = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"
    ralpha = "PTLNBQDEOYSFAVZKGJRIHWXUMC"
    msg = "WELLDONEISBETTERTHANWELLSAID"

    print("L:", lalpha)
    print("R:", ralpha)
    print("I:", msg)
    print("O:", do_chao(msg, lalpha, ralpha, 1, 0), "\n")

    do_chao(msg, lalpha, ralpha, 1, 1)

def do_chao(msg, lalpha, ralpha, en=1, show=0):
    msg = correct_case(msg)
    out = ""
    if show:
        print("="*54)
        print(10*" " + "left:" + 21*" " + "right: ")
        print("="*54)
        print(lalpha, ralpha, "\n")
    for L in msg:
        if en:
            lalpha, ralpha = rotate_wheels(lalpha, ralpha, L)
            out += lalpha[0]
        else:
            ralpha, lalpha = rotate_wheels(ralpha, lalpha, L)
            out += ralpha[0]
        lalpha, ralpha = scramble_wheels(lalpha, ralpha)
        if show:
            print(lalpha, ralpha)
    return out

def makealpha(key=""):
    alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    z = set()
    key = [x.upper() for x in (key + alpha[::-1])
           if not (x.upper() in z or z.add(x.upper()))]
    return "".join(key)

def correct_case(string):
    return "".join([s.upper() for s in string if s.isalpha()])

def permu(alp, num):
    alp = alp[:num], alp[num:]
    return "".join(alp[::-1])

def rotate_wheels(lalph, ralph, key):
    newin = ralph.index(key)
    return permu(lalph, newin), permu(ralph, newin)

def scramble_wheels(lalph, ralph):
    # LEFT = cipher wheel
    # Cycle second[1] through nadir[14] forward
    lalph = list(lalph)
    lalph = "".join([*lalph[0],
                    *lalph[2:14],
                    lalph[1],
                    *lalph[14:]])

    # RIGHT = plain wheel
    # Send the zenith[0] character to the end[25],
    # cycle third[2] through nadir[14] characters forward
    ralph = list(ralph)
    ralph = "".join([*ralph[1:3],
                     *ralph[4:15],
                     ralph[3],
                     *ralph[15:],
                     ralph[0]])
    return lalph, ralph

main()


fn main() {
    println('a'[0]) // prints "97"
	println('π'[0]) // prints "207"

	s := 'aπ'
	println('string cast to bytes: ${s.bytes()}')
	for c in s {
		print('0x${c:x} ')
	}
}


var cps = []
for (c in ["a", "π", "字", "🐘"]) {
    var cp = c.codePoints[0]
    cps.add(cp)
    System.print("%(c) = %(cp)")
}
System.print()
for (i in cps) {
    var c = String.fromCodePoint(i)
    System.print("%(i) = %(c)")
}


[1] (INTEGER->CHAR 97)

#\a
[2] (CHAR->INTEGER #\a)

97


IntOut(0, ^a);  \(Integer Out)  displays "97" on the console (device 0)
ChOut(0, 97);   \(Character Out) displays "a" on the console (device 0)


my @left;
my @right;

sub reset {
    @left  = <HXUCZVAMDSLKPEFJRIGTWOBNYQ>.comb;
    @right = <PTLNBQDEOYSFAVZKGJRIHWXUMC>.comb;
}

sub encode ($letter) {
    my $index = @right.first: $letter.uc, :k;
    my $enc   = @left[$index];
    $index.&permute;
    $enc
}

sub decode ($letter) {
    my $index = @left.first: $letter.uc, :k;
    my $dec   = @right[$index];
    $index.&permute;
    $dec
}

sub permute ($index) {
    @left.=rotate: $index;
    @left[1..13].=rotate;
    @right.=rotate: $index + 1;
    @right[2..13].=rotate;
}

reset;
say 'WELLDONEISBETTERTHANWELLSAID'.comb».&encode.join;
reset;
say 'OAHQHCNYNXTSZJRRHJBYHQKSOUJY'.comb».&decode.join;


txt    = "WELLDONEISBETTERTHANWELLSAID"
@left  = "HXUCZVAMDSLKPEFJRIGTWOBNYQ".chars
@right = "PTLNBQDEOYSFAVZKGJRIHWXUMC".chars

def encrypt(char)
  coded_char = @left[@right.index(char)]

  @left.rotate!(@left.index(coded_char))
  part = @left.slice!(1,13).rotate
  @left.insert(1, *part)

  @right.rotate!(@right.index(char)+1)
  part = @right.slice!(2,12).rotate
  @right.insert(2, *part)

  @left[0]
end

puts txt.each_char.map{|c| encrypt(c) }.join


const std = @import("std");

const debug = std.debug;
const unicode = std.unicode;

test "character codes" {
    debug.warn("\n", .{});

    // Zig's string is just an array of bytes (u8).
    const message = "ABCabc";

    for (message) |val| {
        debug.warn("  '{c}' code: {} [hexa: 0x{x}]\n", .{ val, val, val });
    }
}

test "character (uni)codes" {
    debug.warn("\n", .{});

    const message = "あいうえお";

    const utf8_view = unicode.Utf8View.initUnchecked(message);
    var iter = utf8_view.iterator();

    while (iter.nextCodepoint()) |val| {
        var array: [4]u8 = undefined;
        var slice = array[0..try unicode.utf8Encode(val, &array)];

        debug.warn("  '{}' code: {} [hexa: U+{x}]\n", .{ slice, val, val });
    }
}


program: character_codes
  input: a
  output: 97


10 PRINT CHR$ 97: REM prints a
20 PRINT CODE "a": REM prints 97


const LEFT_ALPHABET_CT: &str = "HXUCZVAMDSLKPEFJRIGTWOBNYQ";
const RIGHT_ALPHABET_PT: &str = "PTLNBQDEOYSFAVZKGJRIHWXUMC";
const ZENITH: usize = 0;
const NADIR: usize = 12;
const SEQUENCE: &str = "WELLDONEISBETTERTHANWELLSAID";

fn cipher(letter: &char, left: &String, right: &String) -> (usize, char) {
    let pos = right.find(*letter).unwrap();
    let cipher = left.chars().nth(pos).unwrap();
    (pos, cipher)
}

fn main() {
    let mut left = LEFT_ALPHABET_CT.to_string();
    let mut right = RIGHT_ALPHABET_PT.to_string();

    let ciphertext = SEQUENCE.chars()
        .map(|letter| {
            let (pos, cipher_char) = cipher(&letter, &left, &right);
            left = format!("{}{}", &left[pos..], &left[..pos]);
            left = format!("{}{}{}{}", &left[ZENITH..1], &left[2..NADIR+2], &left[1..2], &left[NADIR+2..]);
            if pos != right.len() - 1 {
                right = format!("{}{}", &right[pos + 1..], &right[..pos + 1]);
            }
            right = format!("{}{}{}{}", &right[ZENITH..2], &right[3..NADIR+2], &right[2..3], &right[NADIR+2..]);
            cipher_char
        })
        .collect::<String>();

    println!("Plaintext: {}", SEQUENCE);
    println!("Ciphertext: {}", ciphertext);
}


templates chaocipher&{left:,right:,decode:}
  templates permute
    def ctshift: [ [email protected]($..last)..., [email protected](1..$-1)...];
    def p1: $ mod 26 + 1;
    def ptshift: [ [email protected]($p1..last)..., [email protected](1..$p1-1)...];
    ..|@chaocipher: { ct: [ $ctshift(1), $ctshift(3..14)..., $ctshift(2), $ctshift(15..last)...],
      pt: [ $ptshift(1..2)..., $ptshift(4..14)..., $ptshift(3), $ptshift(15..last)...] };
  end permute

  @: {ct:[ $left... ], pt: [ $right... ], result:[]};
  $... -> #
  '[email protected];' !

  when <?($decode <=0>)> do
    def plain: $;
    def index: [email protected] -> \[i](<=$plain> $i!\) -> $(1);
    ..|@.result: [email protected]($index);
    $index -> permute -> !VOID
  otherwise
    def cipher: $;
    def index: [email protected] -> \[i](<=$cipher> $i!\) -> $(1);
    ..|@.result: [email protected]($index);
    $index -> permute -> !VOID
end chaocipher

'WELLDONEISBETTERTHANWELLSAID' -> chaocipher&{left:'HXUCZVAMDSLKPEFJRIGTWOBNYQ', right:'PTLNBQDEOYSFAVZKGJRIHWXUMC',decode:0} -> '$;
' -> !OUT::write

'OAHQHCNYNXTSZJRRHJBYHQKSOUJY' -> chaocipher&{left:'HXUCZVAMDSLKPEFJRIGTWOBNYQ', right:'PTLNBQDEOYSFAVZKGJRIHWXUMC',decode:1} -> '$;
' -> !OUT::write


Module Module1

    ReadOnly L_ALPHABET As String = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"
    ReadOnly R_ALPHABET As String = "PTLNBQDEOYSFAVZKGJRIHWXUMC"

    Enum Mode
        ENCRYPT
        DECRYPT
    End Enum

    Function Exec(text As String, mode As Mode, Optional showSteps As Boolean = False) As String
        Dim left = L_ALPHABET.ToCharArray()
        Dim right = R_ALPHABET.ToCharArray()
        Dim eText(text.Length - 1) As Char
        Dim temp(25) As Char

        For i = 0 To text.Length - 1
            If showSteps Then Console.WriteLine("{0} {1}", String.Join("", left), String.Join("", right))
            Dim index As Integer
            If mode = Mode.ENCRYPT Then
                index = Array.IndexOf(right, text(i))
                eText(i) = left(index)
            Else
                index = Array.IndexOf(left, text(i))
                eText(i) = right(index)
            End If
            If i = text.Length - 1 Then Exit For

            'permute left

            For j = index To 25
                temp(j - index) = left(j)
            Next
            For j = 0 To index - 1
                temp(26 - index + j) = left(j)
            Next
            Dim store = temp(1)
            For j = 2 To 13
                temp(j - 1) = temp(j)
            Next
            temp(13) = store
            temp.CopyTo(left, 0)

            'permute right

            For j = index To 25
                temp(j - index) = right(j)
            Next
            For j = 0 To index - 1
                temp(26 - index + j) = right(j)
            Next
            store = temp(0)
            For j = 1 To 25
                temp(j - 1) = temp(j)
            Next
            temp(25) = store
            store = temp(2)
            For j = 3 To 13
                temp(j - 1) = temp(j)
            Next
            temp(13) = store
            temp.CopyTo(right, 0)
        Next

        Return eText
    End Function

    Sub Main()
        Dim plainText = "WELLDONEISBETTERTHANWELLSAID"
        Console.WriteLine("The original plaintext is : {0}", plainText)
        Console.WriteLine(vbNewLine + "The left and right alphabets after each permutation during encryption are :" + vbNewLine)
        Dim cipherText = Exec(plainText, Mode.ENCRYPT, True)
        Console.WriteLine(vbNewLine + "The ciphertext is : {0}", cipherText)
        Dim plainText2 = Exec(cipherText, Mode.DECRYPT)
        Console.WriteLine(vbNewLine + "The recovered plaintext is : {0}", plainText2)
    End Sub

End Module


type Mode = int
const(
    encrypt = Mode(0)
    decrypt = Mode(1)
)

const(
    l_alphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"
    r_alphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC"
)

fn chao(text string, mode Mode, show_steps bool) string {
    len := text.len
    if text.bytes().len != len {
        println("Text contains non-ASCII characters")
        return ""
    }
    mut left  := l_alphabet
    mut right := r_alphabet
    mut e_text := []u8{len: len}
    mut temp  := []u8{len: 26}

    for i in 0..len {
        if show_steps {
            println('$left $right')
        }
        mut index := 0
        if mode == encrypt {
            index = right.index_u8(text[i])
            e_text[i] = left[index]
        } else {
            index = left.index_u8(text[i])
            e_text[i] = right[index]
        }
        if i == len - 1 {
            break
        }

        // permute left
        for j in index..26 {
            temp[j - index] = left[j]
        }
        for j in 0..index {
            temp[26 - index + j] = left[j]
        }
        mut store := temp[1]
        for j in 2..14 {
            temp[j - 1] = temp[j]
        }
        temp[13] = store
        left = temp.bytestr()

        // permute right

        for j in index..26 {
            temp[j - index] = right[j]
        }
        for j in 0..index {
            temp[26 - index + j] = right[j]
        }
        store = temp[0]
        for j in 1..26 {
            temp[j - 1] = temp[j]
        }
        temp[25] = store
        store = temp[2]
        for j in 3..14 {
            temp[j - 1] = temp[j]
        }
        temp[13] = store
        right = temp.bytestr()
    }

    return e_text.bytestr()
}

fn main() {
    plain_text := "WELLDONEISBETTERTHANWELLSAID"
    println("The original plaintext is : $plain_text")
    print("\nThe left and right alphabets after each permutation ")
    println("during encryption are :\n")
    cypher_text := chao(plain_text, encrypt, true)
    println("\nThe ciphertext is : $cypher_text")
    plain_text2 := chao(cypher_text, decrypt, false)
    println("\nThe recovered plaintext is : $plain_text2")
}


class Chao {
    static encrypt { 0 }
    static decrypt { 1 }

    static exec(text, mode, showSteps) {
        var len = text.count
        if (len != text.bytes.count) Fiber.abort("Text contains non-ASCII characters.")
        var left  = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"
        var right = "PTLNBQDEOYSFAVZKGJRIHWXUMC"
        var eText = List.filled(len, "")
        var temp  = List.filled(26, "")
        for (i in 0...len) {
            if (showSteps) System.print("%(left)  %(right)")
            var index
            if (mode == Chao.encrypt) {
                index = right.indexOf(text[i])
                eText[i] = left[index]
            } else {
                index = left.indexOf(text[i])
                eText[i] = right[index]
            }
            if (i == len - 1) break

            // permute left
            for (j in index..25) temp[j-index] = left[j]
            for (j in 0...index) temp[26-index+j] = left[j]
            var store = temp[1]
            for (j in 2..13) temp[j-1] = temp[j]
            temp[13] = store
            left = temp.join()

            // permute right
            for (j in index..25) temp[j-index] = right[j]
            for (j in 0...index) temp[26-index+j] = right[j]
            store = temp[0]
            for (j in 1..25) temp[j-1] = temp[j]
            temp[25] = store
            store = temp[2]
            for (j in 3..13) temp[j-1] = temp[j]
            temp[13] = store
            right = temp.join()
        }
        return eText.join()
    }
}

var plainText = "WELLDONEISBETTERTHANWELLSAID"
System.print("The original plaintext is : %(plainText)")
System.write("\nThe left and right alphabets after each permutation ")
System.print("during encryption are :\n")
var cipherText = Chao.exec(plainText, Chao.encrypt, true)
System.print("\nThe ciphertext is : %(cipherText)")
var plainText2 = Chao.exec(cipherText, Chao.decrypt, false)
System.print("\nThe recovered plaintext is : %(plainText2)")


class Chao{
   var [const private] lAlphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ",
		       rAlphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC";
   fcn encode(text){ code(text,encodeL); }
   fcn decode(text){ code(text,decodeL); }
   // reset alphabets each [en|de]code and maintain re-entrancy
   fcn code(text,f){ text.apply(f,Data(Void,lAlphabet),Data(Void,rAlphabet)) }
   fcn [private] encodeL(letter,left,right){  // encode a letter
      index:=right.index(letter);
      enc  :=left[index].toChar();
      permute(left,right,index);
      println(left.text," ",right.text,"  ",index);
      enc
   }
   fcn [private] decodeL(letter,left,right){  // decode a letter
      index:=left.index(letter);
      dec  :=right[index].toChar();
      permute(left,right,index);
      dec
   }
   fcn [private] permute(left,right,index){
      left.append(left.pop(0,index));		// rotate index times
      left.insert(13,left.pop(1));		// rotate [1..13] once

      right.append(right.pop(0,index+1)); # rotate index+1 times, idx==25==noop
      right.insert(13,right.pop(2));		// rotate [2..13] once
   }
}


define catbuf $10
define catbuf_temp $12

ldx #0
ramloop:
txa
sta $00,x
inx
cpx #$10
bne ramloop
;load zero page addresses $00-$0f with values equal
;to that address

ldx #0		;zero X
loop_cata:
lda $00,x	;load the zeroth element
clc
adc $01,x	;add the first to it.
inx
inx		;inx twice. Otherwise the same element
		;would get added twice
sta catbuf_temp ;store in temp ram
lda catbuf
clc
adc catbuf_temp ;add to previously stored value
sta catbuf	;store in result
cpx #$10	;is the range over?
bne loop_cata	;if not, loop again

ldx #$00
lda catbuf
sta $00,x
;store the sum in the zeroth entry of the range

inx
lda #$00

;now clear the rest of zeropage, leaving only the sum

clear_ram:
sta $00,x
inx
cpx #$ff
bne clear_ram


report z_catamorphism.

data(numbers) = value int4_table( ( 1 ) ( 2 ) ( 3 ) ( 4 ) ( 5 ) ).

write: |numbers = { reduce string(
  init output = `[`
       index = 1
  for number in numbers
  next output = cond string(
         when index eq lines( numbers )
         then |{ output }, { number } ]|
         when index > 1
         then |{ output }, { number }|
         else |{ output } { number }| )
       index = index + 1 ) }|, /.

write: |sum(numbers) = { reduce int4(
  init result = 0
  for number in numbers
  next result = result + number ) }|, /.

write: |product(numbers) = { reduce int4(
  init result = 1
  for number in numbers
  next result = result * number ) }|, /.

data(strings) = value stringtab( ( `reduce` ) ( `in` ) ( `ABAP` ) ).

write: |strings = { reduce string(
  init output = `[`
       index = 1
  for string in strings
  next output = cond string(
         when index eq lines( strings )
         then |{ output }, { string } ]|
         when index > 1
         then |{ output }, { string }|
         else |{ output } { string }| )
       index = index + 1 ) }|, /.

write: |concatenation(strings) = { reduce string(
  init text = ``
  for string in strings
  next text = |{ text } { string }| ) }|, /.


with Ada.Text_IO;

procedure Catamorphism is

   type Fun is access function (Left, Right: Natural) return Natural;
   type Arr is array(Natural range <>) of Natural;

   function Fold_Left (F: Fun; A: Arr) return Natural is
      Result: Natural := A(A'First);
   begin
      for I in A'First+1 .. A'Last loop
	 Result := F(Result, A(I));
      end loop;
      return Result;
   end Fold_Left;

   function Max (L, R: Natural) return Natural is (if L > R then L else R);
   function Min (L, R: Natural) return Natural is (if L < R then L else R);
   function Add (Left, Right: Natural) return Natural is (Left + Right);
   function Mul (Left, Right: Natural) return Natural is (Left * Right);

   package NIO is new Ada.Text_IO.Integer_IO(Natural);

begin
   NIO.Put(Fold_Left(Min'Access, (1,2,3,4)), Width => 3);
   NIO.Put(Fold_Left(Max'Access, (1,2,3,4)), Width => 3);
   NIO.Put(Fold_Left(Add'Access, (1,2,3,4)), Width => 3);
   NIO.Put(Fold_Left(Mul'Access, (1,2,3,4)), Width => 3);
end Catamorphism;