% Recaman sequence
recaman = cluster is new, fetch
    rep = array[int]

    new = proc () returns (cvt)
        a: rep := rep$predict(0,1000000)
        rep$addh(a,0)
        return(a)
    end new

    % Find the N'th element of the Recaman sequence
    fetch = proc (a: cvt, n: int) returns (int)
        if n > rep$high(a) then extend(a,n) end
        return(a[n])
    end fetch

    % See if N has already been generated
    prev = proc (a: rep, n: int) returns (bool)
        for el: int in rep$elements(a) do
            if el = n then return(true) end
        end
        return(false)
    end prev

    % Generate members of the sequence until 'top' is reached
    extend = proc (a: rep, top: int)
        while rep$high(a) < top do
            n: int := rep$high(a) + 1
            sub: int := a[n-1] - n
            add: int := a[n-1] + n
            if sub>0 cand ~prev(a, sub)
                then rep$addh(a, sub)
                else rep$addh(a, add)
            end
        end
    end extend
end recaman

start_up = proc ()
    po: stream := stream$primary_output()
    A: recaman := recaman$new()

    % Print the first 15 members
    stream$puts(po, "First 15 items:")
    for i: int in int$from_to(0, 14) do
        stream$puts(po, " " || int$unparse(A[i]))
    end

    % Find the first duplicated number
    begin
        i: int := 0
        while true do
            i := i + 1
            for j: int in int$from_to(0, i-1) do
                if A[i]=A[j] then exit found(i, A[i]) end
            end
        end
    end except when found(i, n: int):
        stream$putl(po, "\nFirst duplicated number: A("
                      || int$unparse(i) || ") = " || int$unparse(n))
    end

    % Find the amount of terms needed to generate all integers 0..1000
    begin
        seen: array[bool] := array[bool]$fill(0,1001,false)
        left: int := 1001
        n: int := -1
        while left > 0 do
            n := n + 1
            if A[n] <= 1000 cand ~seen[A[n]] then
                left := left - 1
                seen[A[n]] := true
            end
        end
        stream$putl(po, "Terms needed to generate [0..1000]: "
                     || int$unparse(n))
    end
end start_up


0010 DIM a#(0:100)
0020 //
0030 // Print the first 15 items
0040 PRINT "First 15 items: ",
0050 FOR i#:=0 TO 14 DO PRINT reca#(i#);
0060 PRINT
0070 //
0080 // Find and print the first repeated item
0090 i#:=15
0100 WHILE NOT find#(i#,reca#(i#)) DO i#:+1
0110 PRINT "First repeated item: A(",i#,") = ",a#(i#)
0120 //
0130 // Generate the n'th member of the Recaman sequence
0140 FUNC reca#(n#)
0150   IF n#=0 THEN RETURN 0
0160   a#(n#):=a#(n#-1)-n#
0180   IF a#(n#)<=0 OR find#(n#,a#(n#)) THEN a#(n#):=a#(n#-1)+n#
0190   RETURN a#(n#)
0200 ENDFUNC reca#
0210 //
0220 // See if a number occurs before the n'th member of the Recaman sequence
0230 FUNC find#(n#,num#)
0240   FOR x#:=0 TO n#-1 DO IF a#(x#)=num# THEN RETURN x#
0250   RETURN 0
0260 ENDFUNC find#
0270 END


        IDENTIFICATION DIVISION.
        PROGRAM-ID. RECAMAN.

        DATA DIVISION.
        WORKING-STORAGE SECTION.
        01 RECAMAN-SEQUENCE COMP.
           02 A     PIC 999 OCCURS 99 TIMES INDEXED BY I.
           02 N     PIC 999 VALUE 0.

        01 VARIABLES COMP.
           02 ADDC  PIC S999.
           02 SUBC  PIC S999.
           02 SPTR  PIC 99 VALUE 1.

        01 OUTPUT-FORMAT.
           02 OUTI  PIC Z9.
           02 OUTN  PIC BZ9.
           02 OUTS  PIC X(79).

        PROCEDURE DIVISION.
        BEGIN.
            PERFORM GENERATE-NEXT-ITEM 15 TIMES.
            PERFORM COLLATE-ITEM VARYING I FROM 1 BY 1
                UNTIL I IS GREATER THAN 15.
            DISPLAY 'First 15 items:' OUTS.

        FIND-REPEATING.
            PERFORM GENERATE-NEXT-ITEM.
            SET I TO 1.
            SEARCH A VARYING I
                WHEN I IS NOT LESS THAN N
                    NEXT SENTENCE
                WHEN A(I) IS EQUAL TO A(N)
                    SUBTRACT 1 FROM N GIVING OUTI
                    MOVE A(N) TO OUTN
                    DISPLAY 'First repeated item: A(' OUTI ') =' OUTN
                    STOP RUN.
            GO TO FIND-REPEATING.

        GENERATE-NEXT-ITEM.
            IF N IS EQUAL TO ZERO
                MOVE ZERO TO A(1)
            ELSE
                ADD N, A(N) GIVING ADDC
                SUBTRACT N FROM A(N) GIVING SUBC
                IF SUBC IS NOT GREATER THAN ZERO
                    MOVE ADDC TO A(N + 1)
                ELSE
                    SET I TO 1
                    SEARCH A VARYING I
                        WHEN I IS NOT LESS THAN N
                            MOVE SUBC TO A(N + 1)
                        WHEN A(I) IS EQUAL TO SUBC
                            MOVE ADDC TO A(N + 1).
            ADD 1 TO N.

        COLLATE-ITEM.
            MOVE A(I) TO OUTN.
            STRING OUTN DELIMITED BY SIZE INTO OUTS WITH POINTER SPTR.


Ada.Numerics.e  -- Euler's number
Ada.Numerics.pi -- pi
sqrt(x)         -- square root
log(x, base)    -- logarithm to any specified base
exp(x)          -- exponential
abs(x)          -- absolute value
S'floor(x)      -- Produces the floor of an instance of subtype S
S'ceiling(x)    -- Produces the ceiling of an instance of subtype S
x**y            -- x raised to the y power


# e
exp(1);
# pi
2 * asin(1);

sqrt(x);
log(x);
exp(x);
fabs(x);
floor(x);
ceil(x);
pow(x, y);


REAL x:=exp(1), y:=4*atan(1);
printf(($g(-8,5)"; "$,
    exp(1),    # e #
    pi,        # pi #
    sqrt(x),   # square root #
    log(x),    # logarithm base 10 #
    ln(x),     # natural logarithm #
    exp(x),    # exponential #
    ABS x,     # absolute value #
    ENTIER x,  # floor #
   -ENTIER -x, # ceiling #
    x ** y     # power #
))


rebol [
	Title: "Regular Expression Matching"
	URL: http://rosettacode.org/wiki/Regular_expression_matching
]

string: "This is a string."

; REBOL doesn't use a conventional Perl-compatible regular expression
; syntax. Instead, it uses a variant Parsing Expression Grammar with
; the 'parse' function. It's also not limited to just strings. You can
; define complex grammars that actually parse and execute program
; files.

; Here, I provide a rule to 'parse' that specifies searching through
; the string until "string." is found, then the end of the string. If
; the subject string satisfies the rule, the expression will be true.

if parse string [thru "string." end] [
	print "Subject ends with 'string.'"]

; For replacement, I take advantage of the ability to call arbitrary
; code when a pattern is matched -- everything in the parens will be
; executed when 'to " a "' is satisfied. This marks the current string
; location, then removes the offending word and inserts the replacement.

parse string [
	to " a " ; Jump to target.
	mark: (
		remove/part mark 3 ; Remove target.
		mark: insert mark " another " ; Insert replacement.
	)
	:mark ; Pick up where I left off.
]
print [crlf "Parse replacement:" string]

; For what it's worth, the above operation is more conveniently done
; with the 'replace' function:

replace string " another " " a " ; Change string back.
print [crlf "Replacement:" string]


/*REXX program demonstrates   testing      (modeled after Perl example).*/
$string="I am a string"
                                                  say 'The string is:'  $string
x="string" ;  if right($string,length(x))=x  then say 'It ends with:'  x
y="You"    ;  if left($string,length(y))\=y  then say 'It does not start with:'  y
z="ring"   ;  if pos(z,$string)\==0          then say 'It contains the string:'  z
z="ring"   ;  if wordpos(z,$string)==0       then say 'It does not contain the word:'  z
                                       /*stick a fork in it, we're done.*/


# Project : Regular expressions

text = "I am a text"
if right(text,4) = "text"
   see "'" + text +"' ends with 'text'" + nl
ok
i = substr(text,"am")
text = left(text,i - 1) + "was" + substr(text,i + 2)
see "replace 'am' with 'was' = " + text + nl


str = concat(apply(s->concat(s,"\n"), readstr("file.txt")))


perl -n -0777 -e 'print "file len: ".length' stuff.txt


import std.stdio;

void main() {
    int[] a;
    bool[int] used;
    bool[int] used1000;
    bool foundDup;

    a ~= 0;
    used[0] = true;
    used1000[0] = true;

    int n = 1;
    while (n <= 15 || !foundDup || used1000.length < 1001) {
        int next = a[n - 1] - n;
        if (next < 1 || (next in used) !is null) {
            next += 2 * n;
        }
        bool alreadyUsed = (next in used) !is null;
        a ~= next;
        if (!alreadyUsed) {
            used[next] = true;
            if (0 <= next && next <= 1000) {
                used1000[next] = true;
            }
        }
        if (n == 14) {
            writeln("The first 15 terms of the Recaman sequence are: ", a);
        }
        if (!foundDup && alreadyUsed) {
            writefln("The first duplicated term is a[%d] = %d", n, next);
            foundDup = true;
        }
        if (used1000.length == 1001) {
            writefln("Terms up to a[%d] are needed to generate 0 to 1000", n);
        }
        n++;
    }
}


proc nonrec find([*] int A; word top; int n) bool:
    word i;
    bool found;
    i := 0;
    found := false;
    while i < top and not found do
        found := A[i] = n;
        i := i + 1
    od;
    found
corp

proc nonrec gen_next([*] int A; word n) int:
    int add, sub;
    add := A[n-1] + n;
    sub := A[n-1] - n;
    A[n] :=
        if sub > 0 and not find(A, n, sub)
            then sub
            else add
        fi;
    A[n]
corp

proc nonrec main() void:
    [30] int A;
    word i;

    A[0] := 0;
    write("First 15 items:  0");
    for i from 1 upto 14 do write(gen_next(A, i):3) od;
    writeln();

    while not find(A, i, gen_next(A, i)) do i := i + 1 od;
    writeln("First repeated item: A(", i:2, ") = ", A[i]:2)
corp


begin
    real t, u;
    t := 10;
    u := -2.3;
    i_w := 4; s_w := 0; r_format := "A"; r_d := 4; r_w := 9; % set output format %
    write( "         e: ", exp( 1 ) );         % e              %
    write( "        pi: ", pi );               % pi             %
    write( "    root t: ", sqrt( t ) );        % square root    %
    write( "     log t: ", log( t ) );         % log base 10    %
    write( "      ln t: ", ln( t ) );          % log base e     %
    write( "     exp u: ", exp( u ) );         % exponential    %
    write( "     abs u: ", abs u );            % absolute value %
    write( "  floor pi: ", entier( pi ) );     % floor          %
    write( "ceiling pi: ", - entier( - pi ) ); % ceiling        %
    % the raise-to-the-power operator is "**" - it only allows integers for the power %
    write( "  pi cubed: ", pi ** 3 ) % use exp( ln( x ) * y ) for general x^y %
end.


print ["Euler:" e]
print ["Pi:" pi]

print ["sqrt 2.0:" sqrt 2.0]
print ["ln 100:" ln 100]
print ["log(10) 100:" log 100 10]
print ["exp 3:" exp 3]
print ["abs -1:" abs neg 1]
print ["floor 23.536:" floor 23.536]
print ["ceil 23.536:" ceil 23.536]
print ["2 ^ 8:" 2 ^ 8]


real e = exp(1);                 // e  not available
write("e     = ", e);
write("pi    = ", pi);

real x = 12.345;
real y = 1.23;

write("sqrt  = ", sqrt(2));      // square root
write("ln    = ", log(e));       // natural logarithm base e
write("log   = ", log10(x));     // base 10 logarithm
write("log1p = ", log1p(x));     // log (1+x)
write("exp   = ", exp(e));       // exponential
write("abs   = ", abs(-1));      // absolute value
write("fabs  = ", fabs(-1));     // absolute value
write("floor = ", floor(-e));    // floor
write("ceil  = ", ceil(-e));     // ceiling
write("power = ", x ^ y);        // power
write("power = ", x ** y);       // power


str = "I am a string"
p "Ends with 'string'" if str =~ /string$/
p "Does not start with 'You'" unless str =~ /^You/


string$ = "I am a string"
if right$(string$,6) = "string" then print "'";string$;"' ends with 'string'"
i = instr(string$,"am")
string$ = left$(string$,i - 1) + "was" + mid$(string$,i + 2)
print "replace 'am' with 'was' = ";string$


use regex::Regex;

fn main() {
    let s = "I am a string";

    if Regex::new("string$").unwrap().is_match(s) {
        println!("Ends with string.");
    }

    println!("{}", Regex::new(" a ").unwrap().replace(s, " another "));
}


class MAIN is
  -- we need to implement the substitution
  regex_subst(re:REGEXP, s, sb:STR):STR is
    from, to:INT;
    re.match(s, out from, out to);
    if from = -1 then return s; end;
    return s.head(from) + sb + s.tail(s.size - to);
  end;

  main is
    s ::= "I am a string";
    re ::= REGEXP::regexp("string$", true);
    if re.match(s) then
      #OUT + "'" + s + "'" + " ends with 'string'\n";
    end;
    if ~REGEXP::regexp("^You", false).match(s) then
      #OUT + "'" + s + "'" + " does not begin with 'You'\n";
    end;
    #OUT + regex_subst(re, s, "integer") + "\n";
    #OUT + regex_subst(REGEXP::regexp("am +a +st", true), s, "get the ") + "\n";
  end;
end;


main(Args) =>
    File = Args[1],
    String = read_file_chars(File).


get file (in) edit ((substr(s, i, 1) do i = 1 to 32767)) (a);


: array ( n -- ) ( i -- addr)
  create cells allot
  does> swap cells + ;

100 array sequence

: sequence. ( n -- ) cr 0 ?do i sequence @ . loop ;

: ?unused ( n -- t | n )
  100 0 ?do
    dup i sequence @ = if unloop exit then
  loop drop true ;

: sequence-next ( n -- a[n] )
  dup 0= if 0 0 sequence ! exit then     ( case a[0]=0   )
  dup dup 1- sequence @ swap -           ( a[n]=a[n-1]-n )
  dup dup 0> swap ?unused true = and if
    nip exit then drop
  dup 1- sequence @ swap + ;             ( a[n]=a[n-1]+n )

: sequence-gen ( n -- )
  0 ?do i sequence-next i sequence ! loop ;

: sequence-repeated
  100 0 ?do
    i 0 ?do
      i sequence @ j sequence @ = if
        cr ." first repeated : a[" i . ." ]=a[" j . ." ]=" i sequence @ .  unloop unloop exit then
    loop
  loop ;

100 sequence-gen
15 sequence.
sequence-repeated


' version 26-01-2019
' compile with: fbc -s console

Dim As UByte used()
Dim As Integer sum, temp
Dim As UInteger n, max, count, i

max = 1000 : ReDim used(max)

Print "The first 15 terms are 0";

For n = 0 To 14
    temp = sum - n
    If temp < 1 OrElse used(temp) = 1 Then
        temp = sum + n
    End If
    If temp <= max Then used(temp) = 1
    sum = temp
    Print sum;
Next

sum = 0 : max = 1000 : ReDim used(max)
Print : Print

For n = 0 To 50
    temp = sum - n
    If temp < 1 OrElse used(temp) = 1 Then
        temp = sum + n
    End If
    If used(temp) = 1 Then
        Print "First duplicated number is a(" + Str(n) + ")"
        Exit For
    End If
    If temp <= max Then used(temp) = 1
    sum = temp
Next

sum = 0 : max = 2000000 : ReDim used(max)
Print : Print

For n = 0 To max
    temp = sum - n
    If temp < 1 OrElse used(temp) = 1 Then
        temp = sum + n
    End If
    If temp <= max Then used(temp) = 1
    If i = temp Then
        While used(i) = 1
            i += 1
            If i > 1000 Then
                Exit For
            End If
        Wend
    End If
    sum = temp
    count += 1
Next

Print "All integers from 0 to 1000 are generated in " & count & " terms"
Print

' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End


Sqrt(Number) ; square root
Log(Number) ; logarithm (base 10)
Ln(Number) ; natural logarithm (base e)
Exp(N) ; e to the power N
Abs(Number) ; absolute value
Floor(Number) ; floor
Ceil(Number) ; ceiling
x**y ; x to the power y


BEGIN {
	print sqrt(2)		# square root
	print log(2)		# logarithm base e
	print exp(2)		# exponential
	print 2 ^ -3.4		# power
}
# outputs 1.41421, 0.693147, 7.38906, 0.0947323


ABS(x) 'absolute value
SQR(x) 'square root
EXP(x) 'exponential
LOG(x) 'natural logarithm
x ^ y 'power
'floor, ceiling, e, and pi not available


val Bottles1 = "(\\d+) bottles of beer".r                                            // syntactic sugar
val Bottles2 = """(\d+) bottles of beer""".r                                         // using triple-quotes to preserve backslashes
val Bottles3 = new scala.util.matching.Regex("(\\d+) bottles of beer")               // standard
val Bottles4 = new scala.util.matching.Regex("""(\d+) bottles of beer""", "bottles") // with named groups


set text to "This is a story about R2D2 and C3P0 who are best friends."
set pattern to <word start, letter, digit, letter, digit, word end>

put the sixth word of text matches pattern -- (note: the sixth word is "R2D2")

put every occurrence of pattern in text

replace the second occurrence of pattern in text with "Luke"
put text


var str = "I am a string";
if (str =~ /string$/) {
    print "Ends with 'string'\n";
}


:- initialization(main).

main :-
    current_prolog_flag(argv, [File|_]),
    read_file_to_string(File, String, []).


Number.b = ReadByte(#File)
Length.i = ReadData(#File, *MemoryBuffer, LengthToRead)
Number.c = ReadCharacter(#File)
Number.d = ReadDouble(#File)
Number.f = ReadFloat(#File)
Number.i = ReadInteger(#File)
Number.l = ReadLong(#File)
Number.q = ReadQuad(#File)
Text$    = ReadString(#File [, Flags])
Number.w = ReadWord(#File)


q)file:read0`:file.txt
"First line of file"
"Second line of file"
""


package main

import "fmt"

func main() {
    a := []int{0}
    used := make(map[int]bool, 1001)
    used[0] = true
    used1000 := make(map[int]bool, 1001)
    used1000[0] = true
    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {
        next := a[n-1] - n
        if next < 1 || used[next] {
            next += 2 * n
        }
        alreadyUsed := used[next]
        a = append(a, next)

        if !alreadyUsed {
            used[next] = true
            if next >= 0 && next <= 1000 {
                used1000[next] = true
            }
        }

        if n == 14 {
            fmt.Println("The first 15 terms of the Recaman's sequence are:", a)
        }

        if !foundDup && alreadyUsed {
            fmt.Printf("The first duplicated term is a[%d] = %d\n", n, next)
            foundDup = true
        }

        if len(used1000) == 1001 {
            fmt.Printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n)
        }
    }
}


e = exp(1)                       # e  not available
print "e     = "; e
print "PI    = "; PI

x = 12.345
y = 1.23

print "sqrt  = "; sqr(x)         # square root
print "ln    = "; log(e)         # natural logarithm base e
print "log10 = "; log10(e)       # base 10 logarithm
print "log   = "; log(x)/log(y)	 # arbitrary base logarithm
print "exp   = "; exp(e)         # exponential
print "abs   = "; abs(-1)        # absolute value
print "floor = "; floor(-e)      # floor
print "ceil  = "; ceil(-e)       # ceiling
print "power = "; x ^ y          # power


scale = 6
sqrt(2)		/* 1.414213	square root */
4.3 ^ -2	/* .054083	power (integer exponent) */


x \D (10^x) { \D is the differentiation operator }


#include <math.h>

M_E; /* e - not standard but offered by most implementations */
M_PI; /* pi - not standard but offered by most implementations */
sqrt(x); /* square root--cube root also available in C99 (cbrt) */
log(x); /* natural logarithm--log base 10 also available (log10) */
exp(x); /* exponential */
abs(x); /* absolute value (for integers) */
fabs(x); /* absolute value (for doubles) */
floor(x); /* floor */
ceil(x); /* ceiling */
pow(x,y); /* power */


|re s s1|
re := Regex fromString: '[a-z]+ing'.
s := 'this is a matching string'.
s1 := 'this does not match'.

(s =~ re)
ifMatched: [ :b |
   b match displayNl
].
(s1 =~ re)
ifMatched: [ :b |
   'Strangely matched!' displayNl
]
ifNotMatched: [
   'no match!' displayNl
].

(s replacingRegex: re with: 'modified') displayNl.


label   subject  pattern  =  object          :(goto)


CM.make "$/regexp-lib.cm";
structure RE = RegExpFn (
      structure P = AwkSyntax
      structure E = BackTrackEngine);
val re = RE.compileString "string$";
val string = "I am a string";
case StringCvt.scanString (RE.find re) string
 of NONE => print "match failed\n"
  | SOME match =>
      let
        val {pos, len} = MatchTree.root match
      in
        print ("matched at position " ^ Int.toString pos ^ "\n")
      end;


fname <- "notes.txt"
contents <- readChar(fname, file.info(fname)$size)


Function readFile(theFile As FolderItem, txtEncode As TextEncoding = Nil) As String
  Dim fileContents As String
  Dim tis As TextInputStream
  tis = tis.Open(theFile)
  fileContents = tis.ReadAll(txtEncode)
  tis.Close
  Return fileContents

Exception err As NilObjectException
  MsgBox("File Not Found.")
End Function


read %my-file  ; read as text
read/binary %my-file       ; preserve contents exactly


recaman :: Int -> [Int]
recaman n = fst <$> reverse (go n)
  where
    go 0 = []
    go 1 = [(0, 1)]
    go x =
        let xs@((r, i):_) = go (pred x)
            back = r - i
        in ( if 0 < back && not (any ((back ==) . fst) xs)
               then back
               else r + i
           , succ i) :
           xs

main :: IO ()
main = print $ recaman 15


   positive =: >&0
   unique =: [email protected]:e.
   condition =: ([email protected]:] *. unique~) ({: - #)

   NB. with the agenda set by the condition, add or subtract tail with tally
   recaman_term =: ({: + #)`({: - #)@.condition

   NB. generate four hundred thousand terms and display the first 15
   15 {. R=:(, recaman_term)^:400000]0
0 1 3 6 2 7 13 20 12 21 11 22 10 23 9

   NB. plot the sequence to see why numberphile might be interested.
   load'plot'
   plot 470{.R

   NB. binaryish search for first duplicate.
   (-:&# ~.) 100 {. R
0
   (-:&# ~.) 50 {. R
0
   (-:&# ~.) 25 {. R
0
   (-:&# ~.) 12 {. R
1
   (-:&# ~.) 18 {. R
1
   (-:&# ~.) 21 {. R
1
   (-:&# ~.) 23 {. R
1
   (-:&# ~.) 24 {. R
1
   (-:&# ~.) 25 {. R
0


import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class RecamanSequence {
    public static void main(String[] args) {
        List<Integer> a = new ArrayList<>();
        a.add(0);

        Set<Integer> used = new HashSet<>();
        used.add(0);

        Set<Integer> used1000 = new HashSet<>();
        used1000.add(0);

        boolean foundDup = false;
        int n = 1;
        while (n <= 15 || !foundDup || used1000.size() < 1001) {
            int next = a.get(n - 1) - n;
            if (next < 1 || used.contains(next)) {
                next += 2 * n;
            }
            boolean alreadyUsed = used.contains(next);
            a.add(next);
            if (!alreadyUsed) {
                used.add(next);
                if (0 <= next && next <= 1000) {
                    used1000.add(next);
                }
            }
            if (n == 14) {
                System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a);
            }
            if (!foundDup && alreadyUsed) {
                System.out.printf("The first duplicate term is a[%d] = %d\n", n, next);
                foundDup = true;
            }
            if (used1000.size() == 1001) {
                System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n);
            }
            n++;
        }
    }
}


using System;

class Program {
    static void Main(string[] args) {
        Console.WriteLine(Math.E); //E
        Console.WriteLine(Math.PI); //PI
        Console.WriteLine(Math.Sqrt(10)); //Square Root
        Console.WriteLine(Math.Log(10)); // Logarithm
        Console.WriteLine(Math.Log10(10)); // Base 10 Logarithm
        Console.WriteLine(Math.Exp(10)); // Exponential
        Console.WriteLine(Math.Abs(10)); //Absolute value
        Console.WriteLine(Math.Floor(10.0)); //Floor
        Console.WriteLine(Math.Ceiling(10.0)); //Ceiling
        Console.WriteLine(Math.Pow(2, 5)); // Exponentiation
    }
}


#include <iostream>
#include <cmath>

#ifdef M_E
static double euler_e = M_E;
#else
static double euler_e = std::exp(1); // standard fallback
#endif

#ifdef M_PI
static double pi = M_PI;
#else
static double pi = std::acos(-1);
#endif

int main()
{
  std::cout << "e = " << euler_e
            << "\npi = " << pi
            << "\nsqrt(2) = " << std::sqrt(2.0)
            << "\nln(e) = " << std::log(euler_e)
            << "\nlg(100) = " << std::log10(100.0)
            << "\nexp(3) = " << std::exp(3.0)
            << "\n|-4.5| = " << std::abs(-4.5)   // or std::fabs(-4.5); both work in C++
            << "\nfloor(4.5) = " << std::floor(4.5)
            << "\nceiling(4.5) = " << std::ceil(4.5)
            << "\npi^2 = " << std::pow(pi,2.0) << std::endl;
}


scalar s="ars longa vita brevis"

* is there a vowel?
di regexm(s,"[aeiou]")

* replace the first vowel with "?"
di regexr(s,"[aeiou]","?")


import Foundation

let str = "I am a string"
if let range = str.rangeOfString("string$", options: .RegularExpressionSearch) {
  println("Ends with 'string'")
}


set theString "I am a string"
if {[regexp -- {string$} $theString]} {
    puts "Ends with 'string'"
}

if {![regexp -- {^You} $theString]} {
    puts "Does not start with 'You'"
}


#! Include the regex library
needs regex

#! The two test strings
" This is a string" is-data test.1
" Another string" is-data test.2

#! Create a new regex named 'expression' which tries
#! to match strings beginning with 'This'.
" ^This" regex: expression

#! An array to store the results of the match
#! (Element 0 = starting offset, Element 1 = ending offset of match)
2 cells is-array match

#! Try both test strings against the expression.
#! try-regex will return a flag.  -1 is TRUE, 0 is FALSE
expression test.1 2 match try-regex .
expression test.2 2 match try-regex .


/*REXX program reads an entire file line-by-line  and  stores it as a continuous string.*/
parse arg iFID .                                 /*obtain optional argument from the CL.*/
if iFID==''  then iFID= 'a_file'                 /*Not specified?  Then use the default.*/
$=                                               /*a string of file's contents (so far).*/
             do  while lines(iFID)\==0           /*read the file's lines until finished.*/
             $=$ || linein(iFID)                 /*append a (file's) line to the string,*/
             end   /*while*/                     /*stick a fork in it,  we're all done. */


# Read the file
cStr = read("myfile.txt")
# print the file content
See cStr


# Read entire text file.
str = IO.read "foobar.txt"

# It can also read a subprocess.
str = IO.read "| grep ftp /etc/services"


open DefaultDir$ + "/public/test.txt" for binary as #f
fileLen = LOF(#f)
a$ = input$(#f, fileLen)
print a$
close #f


use std::fs::File;
use std::io::Read;

fn main() {
    let mut file = File::open("somefile.txt").unwrap();

    let mut contents: Vec<u8> = Vec::new();
    // Returns amount of bytes read and append the result to the buffer
    let result = file.read_to_end(&mut contents).unwrap();
    println!("Read {} bytes", result);

    // To print the contents of the file
    let filestr = String::from_utf8(contents).unwrap();
    println!("{}", filestr);
}


(() => {
    const main = () => {

        console.log(
            'First 15 Recaman:\n' +
            recamanUpto(i => 15 === i)
        );

        console.log(
            '\n\nFirst duplicated Recaman:\n' +
            last(recamanUpto(
                (_, set, rs) => set.size !== rs.length
            ))
        );

        const setK = new Set(enumFromTo(0, 1000));
        console.log(
            '\n\nNumber of Recaman terms needed to generate' +
            '\nall integers from [0..1000]:\n' +
            (recamanUpto(
                (_, setR) => isSubSetOf(setK, setR)
            ).length - 1)
        );
    };

    // RECAMAN --------------------------------------------

    // recamanUpto :: (Int -> Set Int > [Int] -> Bool) -> [Int]
    const recamanUpto = p => {
        let
            i = 1,
            r = 0, // First term of series
            rs = [r];
        const seen = new Set(rs);
        while (!p(i, seen, rs)) {
            r = nextR(seen, i, r);
            seen.add(r);
            rs.push(r);
            i++;
        }
        return rs;
    }

    // Next Recaman number.

    // nextR :: Set Int -> Int -> Int
    const nextR = (seen, i, n) => {
        const back = n - i;
        return (0 > back || seen.has(back)) ? (
            n + i
        ) : back;
    };

    // GENERIC --------------------------------------------

    // enumFromTo :: Int -> Int -> [Int]
    const enumFromTo = (m, n) =>
        m <= n ? iterateUntil(
            x => n <= x,
            x => 1 + x,
            m
        ) : [];

    // isSubsetOf :: Ord a => Set a -> Set a -> Bool
    const isSubSetOf = (a, b) => {
        for (let x of a) {
            if (!b.has(x)) return false;
        }
        return true;
    };

    // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]
    const iterateUntil = (p, f, x) => {
        const vs = [x];
        let h = x;
        while (!p(h))(h = f(h), vs.push(h));
        return vs;
    };

    // last :: [a] -> a
    const last = xs =>
        0 < xs.length ? xs.slice(-1)[0] : undefined;

    // MAIN ------------------------------------------------
    return main();
})();


(Math/E); //e
(Math/PI); //pi
(Math/sqrt x); //square root--cube root also available (cbrt)
(Math/log x); //natural logarithm--log base 10 also available (log10)
(Math/exp x); //exponential
(Math/abs x); //absolute value
(Math/floor x); //floor
(Math/ceil x); //ceiling
(Math/pow x y); //power


E          *> e
PI         *> Pi
SQRT(n)    *> Sqaure root
LOG(n)     *> Natural logarithm
LOG10(n)   *> Logarithm (base 10)
EXP(n)     *> e to the nth power
ABS(n)     *> Absolute value
INTEGER(n) *> While not a proper floor function, it is implemented in the same way.
*> There is no ceiling function. However, it could be implemented like so:
ADD 1 TO N
MOVE INTEGER(N) TO Result
*> There is no pow function, although the COMPUTE verb does have an exponention operator.
COMPUTE Result = N ** 2


@(collect)
@(coll :gap 0)@[email protected]{match /dog/}@(end)@suffix
@(output)
@(rep)@{mismatch}[email protected](end)@suffix
@(end)
@(end)


s="I am a string"
if [[ $s =~ str..g$ ]]; then
    echo "the string ends with 'str..g'"
fi


void main(){
    string sentence = "This is a sample sentence.";

    Regex a = new Regex("s[ai]mple"); // if using \n type expressions, use triple " for string literals as easy method to escape them

    if (a.match(sentence)){
        stdout.printf("\"%s\" is in \"%s\"!\n", a.get_pattern(), sentence);
    }

    string sentence_replacement = "cat";
    sentence = a.replace(sentence, sentence.length, 0, sentence_replacement);
    stdout.printf("Replaced sentence is: %s\n", sentence);
}


text = "I need more coffee!!!"
Set regex = New RegExp
regex.Global = True
regex.Pattern = "\s"
If regex.Test(text) Then
	WScript.StdOut.Write regex.Replace(text,vbCrLf)
Else
	WScript.StdOut.Write "No matching pattern"
End If


object TextFileSlurper extends App {
  val fileLines =
    try scala.io.Source.fromFile("my_file.txt", "UTF-8").mkString catch {
      case e: java.io.FileNotFoundException => e.getLocalizedMessage()
    }
}


(with-input-from-file "foo.txt"
  (lambda ()
    (reverse-list->string
     (let loop ((char (read-char))
                (result '()))
       (if (eof-object? char)
           result
           (loop (read-char) (cons char result)))))))


$ include "seed7_05.s7i";
  include "getf.s7i";

const proc: main is func
  local
    var string: fileContent is "";
  begin
    fileContent := getf("text.txt");
  end func;


Put file "~/Documents/myFile.txt" into  TestFile
put testFile


var file = File.new(__FILE__);
var content = file.open_r.slurp;
print content;


# Let R[n] be the Recaman sequence, n >= 0, so R[0]=0.
# Input: a number, $required, specifying the required range of integers, [1 .. $required]
#        to be covered by R[0] ... R[.n]
# $capture: the number of elements of the sequence to retain.
# Output: an object as described below.
# Note that .a|length will be equal to $capture.
#
def recaman_required($capture):
  . as $required
  | {
      n: 0,
      current: 0,                 # R[.n]
      previous: null,             # R[.n-1]
      a: [0],                     # only maintained up to a[$capture-1]
      used:  { "0": true },       # hash for checking whether a value has already occurred
      found: { "0": true },       # hash for checking how many in [0 .. $required] inclusive have been found
      nfound: 1,                  # .found|length
      foundDup: null,             # the first duplicated entry in the sequence
      foundDupAt: null            # .foundDup == R[.foundDupAt]
     }
  | until ((.n >= $capture) and .foundDup and (.nfound > $required);
      .n += 1
      | .current -= .n
      | if (.current < 1 or .used[.current|tostring]) then .current = .current + 2*.n else . end
      | (.current|tostring) as $s
      | .used[$s] as $alreadyUsed
      | if .n < $capture then .a += [.current] else . end
      | if ($alreadyUsed|not)
        then .used[$s] = true
	| if (.current >= 0 and .current <= $required)
	  then .found[$s] = true | .nfound+=1
	  else . end
        else .
	end
      | if (.foundDup|not) and $alreadyUsed
        then .foundDup = .current
	| .foundDupAt = .n
        else .
	end );

1000 as $required
| 15 as $capture
| $required | recaman_required($capture)
| "The first \($capture) terms of Recaman's sequence are: \(.a)",
  "The first duplicated term is a[\(.foundDupAt)] = \(.foundDup)",
  "Terms up to a[\(.n)] are needed to generate 0 to \($required) inclusive."


function recaman()
    a = Vector{Int}([0])
    used = Dict{Int, Bool}(0 => true)
    used1000 = Set(0)
    founddup = false
    termcount = 1
    while length(used1000) <= 1000
        nextterm = a[termcount] - termcount
        if nextterm < 1 || haskey(used, nextterm)
            nextterm += termcount + termcount
        end
        push!(a, nextterm)
        if !haskey(used, nextterm)
            used[nextterm] = true
            if 1 <= nextterm <= 1000
                push!(used1000, nextterm)
            end
        elseif !founddup
            println("The first duplicated term is a[$(termcount + 1)] = $nextterm.")
            founddup = true
        end
        if termcount == 14
            println("The first 15 terms of the Recaman sequence are $a")
        end
        termcount += 1
    end
    println("Terms up to $(termcount - 1) are needed to generate 0 to 1000.")
end

recaman()


// Version 1.2.60

fun main(args: Array<String>) {
    val a = mutableListOf(0)
    val used = mutableSetOf(0)
    val used1000 = mutableSetOf(0)
    var foundDup = false
    var n = 1
    while (n <= 15 || !foundDup || used1000.size < 1001) {
        var next = a[n - 1] - n
        if (next < 1 || used.contains(next)) next += 2 * n
        val alreadyUsed = used.contains(next)
        a.add(next)
        if (!alreadyUsed) {
            used.add(next)
            if (next in 0..1000) used1000.add(next)
        }
        if (n == 14) {
            println("The first 15 terms of the Recaman's sequence are: $a")
        }
        if (!foundDup && alreadyUsed) {
            println("The first duplicated term is a[$n] = $next")
            foundDup = true
        }
        if (used1000.size == 1001) {
            println("Terms up to a[$n] are needed to generate 0 to 1000")
        }
        n++
    }
}


(exp 1)     ; e (Euler's number)
pi          ; pi constant
(sqrt x)    ; square root: works for negative reals and complex
(log x)     ; natural logarithm: works for negative reals and complex
(log x 10)  ; logarithm base 10
(exp x)     ; exponential
(abs x)     ; absolute value: result exact if input exact: (abs -1/3) -> 1/3.
(floor x)   ; floor: restricted to real, two valued (second value gives residue)
(ceiling x) ; ceiling: restricted to real, two valued (second value gives residue)
(expt x y)  ; power


x = 3.25
y = 4

puts x.abs       # absolute value
puts x.floor     # floor
puts x.ceil      # ceiling
puts x ** y      # power
puts

include Math     # without including

puts E           # puts Math::E        -- exponential constant
puts PI          # puts Math::PI       -- Archimedes  circle constant
puts TAU         # puts Math::TAU      -- the correct circle constant, >= version 0.36
puts sqrt(x)     # puts Math.sqrt(x)   -- real square root
puts log(x)      # puts Math.log(x)    -- natural logarithm
puts log10(x)    # puts Math.log10(x)  -- base 10 logarithm
puts log(x, y)   # puts Math.log(x, y) -- logarithm x base y
puts exp(x)      # puts Math.exp(x)    -- exponential
puts E**x        # puts Math::E**x     -- same


import std.math ; // need to import this module
E        // Euler's number
PI       // pi constant
sqrt(x)  // square root
log(x)   // natural logarithm
log10(x) // logarithm base 10
log2(x)  // logarithm base 2
exp(x)   // exponential
abs(x)   // absolute value (= magnitude for complex)
floor(x) // floor
ceil(x)  // ceiling
pow(x,y) // power


if (Match(".* string$", REGEXP)==0) {
    Statline_Message("This line ends with 'string'")
}


@1Introduction.
Web 68 has access to a regular expression module
which can compile regular expressions,
use them for matching strings,
and replace strings with the matched string.

@[email protected]<Compiler [email protected]>
BEGIN
@<[email protected]>
@<Logic at the top [email protected]>
END
@<Compiler [email protected]>

@ The local compiler requires a special prelude.

@<Compiler [email protected]>=
PROGRAM rosettacode regex CONTEXT VOID
USE regex,standard

@ And a special postlude.

@<Compiler [email protected]>=
FINISH

@1Regular expressions.
Compile a regular expression and match a string using it.

@<[email protected]>=
STRING regexp="string$";
REF REGEX rx=rx compile(regexp);

@ Declare a string for the regular expression to match.

@<[email protected]>=
STRING to match = "This is a string";

@ Define a routine to print the result of matching.

@<[email protected]>=
OP MATCH = (REF REGEX rx,STRING match)STRING:
IF rx match(rx,match,LOC SUBEXP)
THEN "matches"
ELSE "doesn't match"
FI;

@ Check whether the regular expression matches the string.

@<Log[email protected]>=
print(("String """,regexp,""" ",rx MATCH to match,
       " string """,to match,"""",newline))

@ The end.
This program is processed by tang to produce Algol 68 code which has to be compiled by the a68toc compiler.
It's output is then compiled by gcc to produce a binary program. The script 'ca' provided with the Debian
package algol68toc requires the following command to process this program.
  ca -l mod rosettacoderegex.w68
That's it. The resulting binary will print
'String "string$" matches string "This is a string"'


import "/pattern" for Pattern

var s = "This is a story about R2D2 and C3P0 who are best friends."
var p = Pattern.new("/u/d/u/d")
var matches = p.findAll(s)
System.print("Original string:\n%("  %(s)")")

System.print("\nThe following matches were found:")
matches.each{ |m| System.print("  %(m.text) at index %(m.index)") }

System.print("\nAfter replacing the second match:")
System.print("  %(p.replace(s, "Luke", 2, 1))") // replace 2nd match with "Luke"

System.print("\nReformatted phone list example:")
var phoneList = [
    "Harry Potter 98951212",
    "Hermione Granger 59867125",
    "Ron Weasley 56471832"
]
var p2 = Pattern.new("[+1/a] [+1/a] [=8/d]")
for (record in phoneList) {
    var m = p2.find(record)
    var t = m.capsText
    System.print("  %(t[1]), %(t[0]) - %(t[2])")
}


(StandardFileStream oldFileNamed: 'foo.txt') contents


      input(.inbin,21,"filename.txt [-r524288]")     :f(end)
rdlp  buf = inbin                                    :s(rdlp)
*
*  now process the 'buf' containing the file
*
end


fun readFile path =
  (fn strm =>
    TextIO.inputAll strm before TextIO.closeIn strm) (TextIO.openIn path)


mata
f = fopen("somedata.txt", "r")
fseek(f, 0, 1)
n = ftell(f)
fseek(f, 0, -1)
s = fread(f, n)
fclose(f)
end


import Foundation

let path = "~/input.txt".stringByExpandingTildeInPath
if let string = String(contentsOfFile: path, encoding: NSUTF8StringEncoding) {
  println(string) // print contents of file
}


local a = {[0]=0}
local used = {[0]=true}
local used1000 = {[0]=true}
local foundDup = false
local n = 1

while n<=15 or not foundDup or #used1000<1001 do
    local nxt = a[n - 1] - n
    if nxt<1 or used[nxt] ~= nil then
        nxt = nxt + 2 * n
    end
    local alreadyUsed = used[nxt] ~= nil
    table.insert(a, nxt)
    if not alreadyUsed then
        used[nxt] = true
        if 0<=nxt and nxt<=1000 then
            used1000[nxt] = true
        end
    end
    if n==14 then
        io.write("The first 15 terms of the Recaman sequence are:")
        for k=0,#a do
            io.write(" "..a[k])
        end
        print()
    end
    if not foundDup and alreadyUsed then
        print("The first duplicated term is a["..n.."] = "..nxt)
        foundDup = true
    end
    if #used1000 == 1001 then
        print("Terms up to a["..n.."] are needed to generate 0 to 1000")
    end
    n = n + 1
end


            NORMAL MODE IS INTEGER
            VECTOR VALUES ELEMF = $2HA(,I2,4H) = ,I2*$
            DIMENSION A(100)
            A(0) = 0

            PRINT COMMENT $ FIRST 15 ELEMENTS$
            PRINT FORMAT ELEMF,0,0
            THROUGH EL, FOR I=1, 1, I.GE.15
EL          PRINT FORMAT ELEMF,I,NEXT.(I)

            PRINT COMMENT $ $
            PRINT COMMENT $ FIRST REPEATED ELEMENT$
RPT         THROUGH RPT, FOR I=I, 1, FIND.(I,NEXT.(I))
            PRINT FORMAT ELEMF,I,A(I)

            INTERNAL FUNCTION(N,TOP)
            ENTRY TO FIND.
            FI=0
SRCH        WHENEVER FI.GE.TOP, FUNCTION RETURN 0B
            WHENEVER A(FI).E.N, FUNCTION RETURN 1B
            FI=FI+1
            TRANSFER TO SRCH
            END OF FUNCTION

            INTERNAL FUNCTION(N)
            ENTRY TO NEXT.
            HI=A(N-1)+N
            LO=A(N-1)-N
            WHENEVER LO.L.0
                A(N)=HI
            OR WHENEVER FIND.(LO,N)
                A(N)=HI
            OTHERWISE
                A(N)=LO
            END OF CONDITIONAL
            FUNCTION RETURN A(N)
            END OF FUNCTION
            END OF PROGRAM


Pi;             // π (Pi)
LogN(BASE, x)   // log of x for a specified base
Log2(x)         // log of x for base 2
Log10(x)        // log of x for base 10
Floor(x);       // floor
Ceil(x);        // ceiling
Power(x, y);    // power


var re=RegExp(".*string$");
re.matches("I am a string") //-->True
var s="I am a string thing"
re=RegExp("(string)")  // () means group, ie if you see it, save it
re.search(s,True) //-->True, .search(x,True) means search for a match, ie don't need .*
p,n:=re.matched[0] //.matched-->L(L(7,6),"string")
String(s[0,p],"FOO",s[p+n,*]) //-->"I am a FOO thing"

re.search(s,True); // using .matched clears it
m:=re.matched[1];
s.replace(m,"FOO"); // -->"I am a FOO thing"


set f [open $filename]
set data [read $f]
close $f


$$ MODE TUSCRIPT
ERROR/STOP OPEN ("rosetta.txt",READ,-std-)
var=FILE ("rosetta.txt")


f=`cat foo.txt`    # f will contain the entire contents of the file
printf '%s\n' "$f"


decl string contents
decl file f
f.open "filename.txt"
set contents (f.readall)


string file_contents;
FileUtils.get_contents("foo.txt", out file_contents);


dim s
s = createobject("scripting.filesystemobject").opentextfile("slurp.vbs",1).readall
wscript.echo s


ClearAll[f]
f[s_List] := Block[{a = s[[-1]], len = [email protected]},
  Append[s, If[a > len && ! MemberQ[s, a - len], a - len, a + len]]]; g = Nest[f, {0}, 70]
g = Nest[f, {0}, 70];
Take[g, 15]
p = Select[Tally[g], Last /* EqualTo[2]][[All, 1]]
p = Flatten[Position[g, #]] & /@ p;
TakeSmallestBy[p, Last, 1][[1]]


' Recaman's sequence - smallbasic - 05/08/2015
    nn=15
    TextWindow.WriteLine("Recaman's sequence for the first " + nn + " numbers:")
    recaman()
    TextWindow.WriteLine(Text.GetSubTextToEnd(recaman,2))
    nn="firstdup"
    recaman()
    TextWindow.WriteLine("The first duplicated term is a["+n+"]="+a[n])

Sub recaman
    a=""
    b=""
    dup=""
    recaman=""
    firstdup=""
    If nn="firstdup" Then
        nn=1000
        firstdup="True"
    EndIf
    For n=0 To nn-1
        ap=a[n-1]+n
        If a[n-1]<=n Then
            a[n]=ap  'a[n]=a[n-1]+n
            b[ap]=1
        Else
            am=a[n-1]-n
            If b[am]=1 Then
                a[n]=ap  'a[n]=a[n-1]+n
                b[ap]=1
            Else
                a[n]=am  'a[n]=a[n-1]-n
                b[am]=1
            EndIf
        EndIf
        If firstdup Then
            If dup[a[n]]=1 Then
                Goto exitsub
            EndIf
            dup[a[n]]=1
        EndIf
        recaman=recaman+","+a[n]
    EndFor
    exitsub:
EndSub


import sequtils, sets, strutils

iterator recaman(num: Positive = Natural.high): tuple[n, a: int; duplicate: bool] =
  var a = 0
  yield (0, a, false)
  var known = [0].toHashSet
  for n in 1..<num:
    var next = a - n
    if next <= 0 or next in known:
      next = a + n
    a = next
    yield (n, a, a in known)
    known.incl a

echo "First 15 numbers in Recaman’s sequence: ", toSeq(recaman(15)).mapIt(it.a).join(" ")

for (n, a, dup) in recaman():
  if dup:
    echo "First duplicate found: a($1) = $2".format(n, a)
    break

var target = toSeq(0..1000).toHashSet
for (n, a, dup) in recaman():
  target.excl a
  if target.card == 0:
    echo "All numbers from 0 to 1000 generated after $1 terms.".format(n)
    break


use Collection.Generic;

class RecamanSequence {
  function : Main(args : String[]) ~ Nil {
    GenerateSequence();
  }

  function : native : GenerateSequence() ~ Nil {
    a := Vector->New()<IntHolder>;
    a->AddBack(0);

    used := Set->New()<IntHolder>;
    used->Insert(0);

    used1000 := Set->New()<IntHolder>;
    used1000->Insert(0);

    foundDup := false;
    n := 1;
    while (n <= 15 | <>foundDup | used1000->Size() < 1001) {
      next := a->Get(n - 1) - n;
      if (next < 1 | used->Has(next)) {
        next += 2 * n;
      };
      alreadyUsed := used->Has(next);
      a->AddBack(next);
      if (<>alreadyUsed) {
        used->Insert(next);
        if (0 <= next & next <= 1000) {
          used1000->Insert(next);
        };
      };
      if (n = 14) {
        str := ToString(a);
        "The first 15 terms of the Recaman sequence are : {$str}"->PrintLine();
      };
      if (<>foundDup & alreadyUsed) {
        "The first duplicate term is a[{$n}] := {$next}"->PrintLine();
        foundDup := true;
      };
      if (used1000->Size() = 1001) {
        "Terms up to a[{$n}] are needed to generate 0 to 1000"->PrintLine();
      };
      n++;
    };
  }

  function : ToString(a : Vector<IntHolder>) ~ String {
    out := "[";
    each(i : a) {
      out += a->Get(i)->Get();
      if(i + 1 < a->Size())  {
        out += ',';
      };
    };
    out += ']';

    return out;
  }
}


import system'math;
import extensions;

public program()
{
    console.printLine(E_value);       //E
    console.printLine(Pi_value);      //PI
    console.printLine(10.sqrt());     //Square Root
    console.printLine(10.ln());       //Logarithm
    console.printLine(10.log10());    // Base 10 Logarithm
    console.printLine(10.exp());      //Exponential
    console.printLine(10.Absolute); //Absolute value
    console.printLine(10.0r.floor()); //Floor
    console.printLine(10.0r.ceil());  //Ceiling
    console.printLine(2.power(5));    //Exponentiation
}


defmodule Real_constants_and_functions do
  def main do
    IO.puts :math.exp(1)                # e
    IO.puts :math.pi                    # pi
    IO.puts :math.sqrt(16)              # square root
    IO.puts :math.log(10)               # natural logarithm
    IO.puts :math.log10(10)             # base 10 logarithm
    IO.puts :math.exp(2)                # e raised to the power of x
    IO.puts abs(-2.24)                  # absolute value
    IO.puts Float.floor(3.1423)         # floor
    IO.puts Float.ceil(20.125)          # ceiling
    IO.puts :math.pow(3,2)              # exponentiation
  end
end

Real_constants_and_functions.main


e           -- e
pi          -- pi
sqrt x      -- square root
logBase 3 9 -- logarithm (any base)
e^x         -- exponential
abs x       -- absolute value
floor x     -- floor
ceiling x   -- ceiling
2 ^ 3       -- power


% Implemented by Arjun Sunel
-module(math_constants).
-export([main/0]).
main() ->
	io:format("~p~n",	[math:exp(1)]		),		% e
	io:format("~p~n",	[math:pi()]		),		% pi
	io:format("~p~n",	[math:sqrt(16)]		),		% square root
	io:format("~p~n",	[math:log(10)]		),		% natural logarithm
	io:format("~p~n",	[math:log10(10)]	),		% base 10 logarithm
	io:format("~p~n",	[math:exp(2)]		),		% e raised to the power of x
	io:format("~p~n",	[abs(-2.24)]		),		% absolute value
	io:format("~p~n",	[floor(3.1423)]		),		% floor
	io:format("~p~n",	[ceil(20.125)]		),		% ceiling
	io:format("~p~n",	[math:pow(3,2)]	        ).		% exponentiation

floor(X) when X < 0 ->
	T = trunc(X),
	case X - T == 0 of
		true -> T;
        	false -> T - 1
	end;

floor(X) ->
	trunc(X).

ceil(X) when X < 0 ->
	trunc(X);

ceil(X) ->
	T = trunc(X),
	case X - T == 0 of
		true -> T;
		false -> T + 1
	end.


Declare Function MultiByteToWideChar Lib "kernel32.dll" ( _
     ByVal CodePage As Long, _
     ByVal dwFlags As Long, _
     ByVal lpMultiByteStr As Long, _
     ByVal cchMultiByte As Long, _
     ByVal lpWideCharStr As Long, _
     ByVal cchWideChar As Long) As Long
Const CP_UTF8 As Long = 65001

Sub Main()
Dim fn As Integer
Dim i As Long
Dim b() As Byte
Dim s As String

  fn = FreeFile()
  Open "c:\test.txt" For Binary Access Read As #fn
  ReDim b(0 To (LOF(fn) - 1))
  Get #fn, 1, b()

  If b(0) = &HFF And b(1) = &HFE Then
  'UTF-16, little-endian
    ReDim b(0 To (LOF(fn) - 3))
    Get #fn, 3, b()
    s = b()
  ElseIf b(0) = &HEF And b(1) = &HBB And b(2) = &HBF Then
  'UTF-8
    i = MultiByteToWideChar(CP_UTF8, 0&, VarPtr(b(3)), LOF(fn) - 3, StrPtr(s), 0)
    s = Space$(i)
    i = MultiByteToWideChar(CP_UTF8, 0&, VarPtr(b(3)), LOF(fn) - 3, StrPtr(s), Len(s))
  Else
  'assume ANSI
    s = StrConv(b(), vbUnicode)
  End If
  Close #fn
  Debug.Print s
End Sub


Imports System.IO

Public Class Form1

  ' Read all of the lines of a file.
  ' Function assumes that the file exists.
  Private Sub ReadLines(ByVal FileName As String)

    Dim oReader As New StreamReader(FileName)
    Dim sLine As String = oReader.ReadToEnd()

    oReader.Close()

  End Sub

End Class


with infile "x"
  with outstring
    whilet line (read_line)
      prn line


import "io" for File

System.print(File.read("input.txt"))


use bignum;

$max = 1000;
$remaining += $_ for 1..$max;

my @recamans = 0;
my $previous = 0;

while ($remaining > 0) {
   $term++;
   my $this = $previous - $term;
   $this = $previous + $term unless $this > 0 and !$seen{$this};
   push @recamans, $this;
   $dup = $term if !$dup and defined $seen{$this};
   $remaining -= $this if $this <= $max and ! defined $seen{$this};
   $seen{$this}++;
   $previous = $this;
}

print "First fifteen terms of Recaman's sequence: " . join(' ', @recamans[0..14]) . "\n";
print "First duplicate at term: a[$dup]\n";
print "Range 0..1000 covered by terms up to a[$term]\n";


with javascript_semantics
bool found_duplicate = false
sequence a = {0}, used = {} -- (grows to 1,942,300 entries)
integer all_used = 0, n = 1, next, prev = 0
while n<=15 or not found_duplicate or all_used<1000 do
    next = prev - n
    if next<1 or (next<=length(used) and used[next]) then
        next = prev + n
    end if
    a &= next
    integer padlen = next-length(used)
    bool already_used = padlen<=0 and used[next]
    if not already_used then
        if padlen>0 then used &= repeat(false,padlen) end if
        used[next] = true
        while all_used<length(used) and used[all_used+1] do
            all_used += 1
        end while
    end if
    if length(a)=15 then
        printf(1,"The first 15 terms of the Recaman sequence are: %v\n",{a})
    end if
    if already_used and not found_duplicate then
        printf(1,"The first duplicated term is a[%d] = %d\n", {n, next})
        found_duplicate = true;
    end if
    if all_used>=1000 then
        printf(1,"Terms up to a[%d] are needed to generate 0 to 1000\n", {n});
    end if
    prev = next
    n += 1
end while


PROGRAM R_C_F

FUNCTION CEILING(X)
   CEILING=INT(X)-(X-INT(X)>0)
END FUNCTION

FUNCTION FLOOR(X)
   FLOOR=INT(X)
END FUNCTION

BEGIN
     PRINT(EXP(1))           ! e  not available
     PRINT(π)                ! pi is available or ....
     PRINT(4*ATN(1))         ! .... equal to

     X=12.345
     Y=1.23

     PRINT(SQR(X),X^0.5)     ! square root
     PRINT(LOG(X))           ! natural logarithm base e
     PRINT(LOG(X)/LOG(10))   ! base 10 logarithm
     PRINT(LOG(X)/LOG(Y))    ! arbitrary base logarithm (y>0)
     PRINT(EXP(X))           ! exponential
     PRINT(ABS(X))           ! absolute value
     PRINT(FLOOR(X))         ! floor
     PRINT(CEILING(X))       ! ceiling
     PRINT(X^Y)              ! power
END PROGRAM


open System

let main _ =
    Console.WriteLine(Math.E);             // e
    Console.WriteLine(Math.PI);            // Pi
    Console.WriteLine(Math.Sqrt(10.0));    // Square Root
    Console.WriteLine(Math.Log(10.0));     // Logarithm
    Console.WriteLine(Math.Log10(10.0));   // Base 10 Logarithm
    Console.WriteLine(Math.Exp(10.0));     // Exponential
    Console.WriteLine(Math.Abs(10));       // Absolute value
    Console.WriteLine(Math.Floor(10.0));   // Floor
    Console.WriteLine(Math.Ceiling(10.0)); // Ceiling
    Console.WriteLine(Math.Pow(2.0, 5.0)); // Exponentiation

    0


e          ! e
pi         ! π
sqrt       ! square root
log        ! natural logarithm
exp        ! exponentiation
abs        ! absolute value
floor      ! greatest whole number smaller than or equal
ceiling    ! smallest whole number greater than or equal
truncate   ! remove the fractional part (i.e. round towards 0)
round      ! round to next whole number
^          ! power


include c:\cxpl\codes;  \intrinsic 'code' declarations
string 0;               \use zero-terminated string convention
int  I;
char Str;
[Str:= GetHp;           \starting address of block of local "heap" memory
I:= 0;                  \ [does the exact same thing as Reserve(0)]
loop    [Str(I):= ChIn(1);
        if Str(I) = $1A\EOF\ then [Str(I):= 0;  quit];
        I:= I+1;
        ];
SetHp(Str+I+1);         \set heap pointer beyond Str (not really needed here)
Text(0, Str);           \show file as a string
]


package com.rosetta.example

import java.io.File
import java.io.PrintStream

class ReadFile {
    def static main( String ... args ) {
        val content = new String(Files.readAllBytes(Paths.get("file.txt")))
    }
}


<?php
$a = array();
array_push($a, 0);

$used = array();
array_push($used, 0);

$used1000 = array();
array_push($used1000, 0);

$foundDup = false;
$n = 1;

while($n <= 15 || !$foundDup || count($used1000) < 1001) {
	$next = $a[$n - 1] - $n;
	if ($next < 1 || in_array($next, $used)) {
		$next += 2 * $n;
	}
	$alreadyUsed = in_array($next, $used);
	array_push($a, $next);
	if (!$alreadyUsed) {
		array_push($used, $next);
		if (0 <= $next && $next <= 1000) {
			array_push($used1000, $next);
		}
	}
	if ($n == 14) {
		echo "The first 15 terms of the Recaman sequence are : [";
		foreach($a as $i => $v) {
			if ( $i == count($a) - 1)
				echo "$v";
			else
				echo "$v, ";
		}
		echo "]\n";
	}
	if (!$foundDup && $alreadyUsed) {
		printf("The first duplicate term is a[%d] = %d\n", $n, $next);
		$foundDup = true;
	}
	if (count($used1000) == 1001) {
		printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n);
	}
	$n++;
}


Float.e
Float.pi
9f.sqrt
9f.log      // natural logarithm
9f.log10    // logarithm to base 10
9f.exp      // exponentiation
(-3f).abs   // absolute value, note bracket
3.2f.floor  // nearest Int smaller than this number
3.2f.ceil   // nearest Int bigger than this number
3.2f.round  // nearest Int
3f.pow(2f)  // power


1e fexp fconstant e
0e facos 2e f* fconstant pi  \ predefined in gforth
fsqrt ( f -- f )
fln ( f -- f )   \ flog for base 10
fexp ( f -- f )
fabs ( f -- f )
floor ( f -- f )  \ round towards -inf
: ceil ( f -- f ) fnegate floor fnegate ; \ not standard, though fround is available
f** ( f e -- f^e )


 e          ! Not available. Can be calculated EXP(1.0)
 pi         ! Not available. Can be calculated 4.0*ATAN(1.0)
 SQRT(x)    ! square root
 LOG(x)     ! natural logarithm
 LOG10(x)   ! logarithm to base 10
 EXP(x)     ! exponential
 ABS(x)     ! absolute value
 FLOOR(x)   ! floor - Fortran 90 or later only
 CEILING(x) ! ceiling - Fortran 90 or later only
 x**y       ! x raised to the y power


' FB 1.05.0 Win64

#Include "crt/math.bi"

Print M_E          '' constant "e" from C runtime library
Print M_PI         '' constant "pi" from C runtime library
Print Sqr(2)       '' square root function built into FB
Print Log(M_E)     '' log to base "e" built into FB
Print log10(10)    '' log to base 10 from C runtime library
Print Exp(1)       '' exponential function built into FB
Print Abs(-1)      '' absolute value function (integers or floats) built into FB
Print Int(-2.5)    '' floor function built into FB
Print ceil(-2.5)   '' ceiling function from C runtime library
Print 2.5 ^ 3.5    '' exponentiation operator built into FB
Sleep


recaman: procedure options(main);
    declare A(0:30) fixed;

    /* is X in the first N terms of the Recaman sequence? */
    find: procedure(x, n) returns(bit);
        declare (x, n, i) fixed;
        do i=0 to n-1;
            if A(i)=x then return('1'b);
        end;
        return('0'b);
    end find;

    /* generate the N'th term of the Recaman sequence */
    generate: procedure(n) returns(fixed);
        declare n fixed;
        if n=0 then
            A(0) = 0;
        else do;
            declare (sub, add) fixed;
            sub = A(n-1) - n;
            add = A(n-1) + n;
            /* A(n-1) - n not positive? */
            if sub <= 0 then
                A(n) = add;
            /* A(n-1) - n already generated? */
            else if find(sub, n) then
                A(n) = add;
            else
                A(n) = sub;
        end;
        return(A(n));
    end generate;

    declare i fixed;
    put skip list('First 15 members:');
    do i=0 to 14;
        put edit(generate(i)) (F(3));
    end;

    put skip list('First repeated term: ');
    do i=15 repeat(i+1) while(^find(generate(i), i)); end;
    put edit('A(',i,') = ',A(i)) (A,F(2),A,F(2));
end recaman;


100H:
BDOS: PROCEDURE(F,A); DECLARE F BYTE, A ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PRINT$CH: PROCEDURE(C); DECLARE C BYTE; CALL BDOS(2,C); END PRINT$CH;
PRINT$STR: PROCEDURE(S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT$STR;

/* PRINT NUMBER */
PRINT$NUM: PROCEDURE(N);
    DECLARE (N, P) ADDRESS, C BASED P BYTE;
    DECLARE S(6) BYTE INITIAL('.....$');
    P = .S(5);
DIGIT:
    P = P-1;
    C = '0' + N MOD 10;
    N = N/10;
    IF N>0 THEN GO TO DIGIT;
    CALL PRINT$STR(P);
END PRINT$NUM;

/* IS X IN THE FIRST N TERMS OF THE SEQUENCE */
FIND: PROCEDURE(SEQ,X,N) BYTE;
    DECLARE SEQ ADDRESS, (I, X, N, A BASED SEQ) BYTE;
    DO I=0 TO N-1;
        IF A(I)=X THEN RETURN 0FFH;
    END;
    RETURN 0;
END FIND;

/* GENERATE THE N'TH TERM OF THE SEQUENCE */
GENERATE: PROCEDURE(SEQ,N) BYTE;
    DECLARE SEQ ADDRESS, (N, A BASED SEQ) BYTE;
    IF N=0 THEN
        A(N)=0;
    ELSE DO;
        DECLARE (SUB, ADD) BYTE;
        SUB = A(N-1) - N;
        ADD = A(N-1) + N;
        /* A(N-1) - N NEGATIVE? */
        IF A(N-1) <= N THEN
            A(N) = ADD;
        /* A(N-1) - N ALREADY GENERATED? */
        ELSE IF FIND(SEQ,SUB,N) THEN
            A(N) = ADD;
        ELSE
            A(N) = SUB;
    END;
    RETURN A(N);
END GENERATE;

DECLARE I BYTE, A(30) BYTE;
CALL PRINT$STR(.'FIRST 15 MEMBERS: $');
DO I=0 TO 14;
    CALL PRINT$NUM(GENERATE(.A, I));
    CALL PRINT$CH(' ');
END;
CALL PRINT$STR(.(13,10,'FIRST REPEATED TERM: A($'));

I=15;
DO WHILE NOT FIND(.A, GENERATE(.A, I), I);
    I = I+1;
END;

CALL PRINT$NUM(I);
CALL PRINT$STR(.') = $');
CALL PRINT$NUM(A(I));
CALL PRINT$STR(.(13,10,'$'));
CALL EXIT;
EOF


e
pi, π   // Unicode can also be written in ASCII programs as \u03C0
sqrt[x]
ln[x]   // Natural log
log[x]  // Log to base 10
exp[x], e^x
abs[x]
floor[x] // Except for complex numbers where there's no good interpretation.
ceil[x]  // Except for complex numbers where there's no good interpretation.
x^y


window 1

text ,,,,, 60// set tab width

print @"exp:",   exp(1)
print @"pi:",    pi
print @"sqr:",   sqr(2)
print @"log:",   log(2)
print @"log2:",  log2(2)
print @"log10",  log10(2)
print @"abs:",   abs(-2)
print @"floor:", int(1.534)
print @"ceil:",  val( using"###"; 1.534 )
print @"power:", 1.23 ^ 4

HandleEvents


package main

import (
    "fmt"
    "math"
    "math/big"
)

func main() {
    // e and pi defined as constants.
    // In Go, that means they are not of a specific data type and can be used
    // as float32 or float64.  Println takes the float64 values.
    fmt.Println("float64 values:")
    fmt.Println("e:", math.E)
    fmt.Println("π:", math.Pi)

    // The following functions all take and return the float64 data type.

    // square root.  cube root also available (math.Cbrt)
    fmt.Println("square root(1.44):", math.Sqrt(1.44))
    // natural logarithm--log base 10, 2 also available (math.Log10, math.Log2)
    // also available is log1p, the log of 1+x.  (using log1p can be more
    // accurate when x is near zero.)
    fmt.Println("ln(e):", math.Log(math.E))
    // exponential.  also available are exp base 10, 2 (math.Pow10, math.Exp2)
    fmt.Println("exponential(1):", math.Exp(1))
    fmt.Println("absolute value(-1.2):", math.Abs(-1.2))
    fmt.Println("floor(-1.2):", math.Floor(-1.2))
    fmt.Println("ceiling(-1.2):", math.Ceil(-1.2))
    fmt.Println("power(1.44, .5):", math.Pow(1.44, .5))

    // Equivalent functions for the float32 type are not in the standard
    // library.  Here are the constants e and π as float32s however.
    fmt.Println("\nfloat32 values:")
    fmt.Println("e:", float32(math.E))
    fmt.Println("π:", float32(math.Pi))

    // The standard library has an arbitrary precision floating point type but
    // provides only the most basic methods.  Also while the constants math.E
    // and math.Pi are provided to over 80 decimal places, there is no
    // convenient way of loading these numbers (with their full precision)
    // into a big.Float.  A hack is cutting and pasting into a string, but
    // of course if you're going to do that you are free to cut and paste from
    // any other source.  (The documentation cites OEIS as its source.)
    pi := "3.141592653589793238462643383279502884197169399375105820974944"
    π, _, _ := big.ParseFloat(pi, 10, 200, 0)
    fmt.Println("\nbig.Float values:")
    fmt.Println("π:", π)
    // Of functions requested by the task, only absolute value is provided.
    x := new(big.Float).Neg(π)
    y := new(big.Float)
    fmt.Println("x:", x)
    fmt.Println("abs(x):", y.Abs(x))
}


#MAX=500000
Dim a.i(#MAX)
Dim b.b(1)
Dim c.b(1000)
FillMemory(@c(),1000,1,#PB_Byte)

If OpenConsole() : Else : End 1 : EndIf
For n_Count=0 To #MAX
  If n_Count=0
    a(n_Count)=0
  ElseIf a(n_Count-1)-n_Count>0 And b(a(n_Count-1)-n_Count)=0
    a(n_Count)=a(n_Count-1)-n_Count
  Else
    a(n_Count)=a(n_Count-1)+n_Count
  EndIf
  If ArraySize(b())<a(n_Count) : ReDim b(a(n_Count)) : EndIf
  If b(a(n_Count))=1 And fitD=0 : fitD=n_Count : EndIf
  b(a(n_Count))=1
  If CompareMemory(@b(),@c(),1000) And fit1000=0 : fit1000=n_Count : Break : EndIf
Next

Print("First 15 terms: ") : For i=0 To 14 : Print(RSet(Str(a(i)),4)) : Next : PrintN("")
PrintN("First duplicate term : a("+Str(fitD)+") = "+Str(a(fitD)))
PrintN("Number of Recaman terms needed to generate all integers from [0..1000]: "+Str(fit1000))
Input()
End


from itertools import islice

class Recamans():
    "Recamán's sequence generator callable class"
    def __init__(self):
        self.a = None   # Set of results so far
        self.n = None   # n'th term (counting from zero)

    def __call__(self):
        "Recamán's sequence  generator"
        nxt = 0
        a, n = {nxt}, 0
        self.a = a
        self.n = n
        yield nxt
        while True:
            an1, n = nxt, n + 1
            nxt = an1 - n
            if nxt < 0 or nxt in a:
                nxt = an1 + n
            a.add(nxt)
            self.n = n
            yield nxt

if __name__ == '__main__':
    recamans = Recamans()
    print("First fifteen members of Recamans sequence:",
          list(islice(recamans(), 15)))

    so_far = set()
    for term in recamans():
        if term in so_far:
            print(f"First duplicate number in series is: a({recamans.n}) = {term}")
            break
        so_far.add(term)

    n = 1_000
    setn = set(range(n + 1))    # The target set of numbers to be covered
    for _ in recamans():
        if setn.issubset(recamans.a):
            print(f"Range 0 ..{n} is covered by terms up to a({recamans.n})")
            break


exp 1     -- Euler number
pi        -- pi
sqrt x    -- square root
log x     -- natural logarithm
exp x     -- exponential
abs x     -- absolute value
floor x   -- floor
ceiling x -- ceiling
x ** y    -- power (e.g. floating-point exponentiation)
x ^ y     -- power (e.g. integer exponentiation, nonnegative y only)
x ^^ y    -- power (e.g. integer exponentiation of rationals, also negative y)


e          ! Not available. Can be calculated EXP(1)
pi         ! Not available. Can be calculated 4.0*ATAN(1.0)
x^0.5      ! square root
LOG(x)     ! natural logarithm
LOG(x, 10) ! logarithm to base 10
EXP(x)     ! exponential
ABS(x)     ! absolute value
FLOOR(x)   ! floor
CEILING(x) ! ceiling
x**y       ! x raised to the y power
x^y        ! same as x**y


link numbers  # for floor and ceil

procedure main()
write("e=",&e)
write("pi=",&pi)
write("phi=",&phi)
write("sqrt(2)=",sqrt(2.0))
write("log(e)=",log(&e))
write("log(100.,10)=",log(100,10))
write("exp(1)=",exp(1.0))
write("abs(-2)=",abs(-2))
write("floor(-2.2)=",floor(-2.2))
write("ceil(-2.2)=",ceil(-2.2))
write("power: 3^3=",3^3)
end


  [ stack 0 ]              is seennumbers (     --> s   )

  [ bit seennumbers take
    | seennumbers put ]    is seen        (   n -->     )

  [ dup 0 < iff
      [ drop true ] done
    bit seennumbers share
    & 0 != ]                is seen?       (   n --> b   )

  [ 1+ bit 1 -
    seennumbers share
    over & = ]              is allseen?    (   n --> b   )

  [ stack [ ] ]             is repeats     (     --> s   )

  [ 1 seennumbers replace
    [] repeats replace
    ' [ 0 ] 1 ]             is startseq    (     --> [ n )

  [ over -1 peek
    over - dup seen? if
      [ over 2 * +
        dup seen? if
          [ repeats take
            over join
            repeats put ] ]
    dup seen
    swap dip join
    1+ ]                    is nextterm    ( [ n --> [ n )

  say "first 15 terms: "
  startseq
  14 times nextterm
  drop echo cr

  say "first duplicated term: "
  startseq
  [ repeats share [] = while
    nextterm
    again ]
  drop -1 peek echo cr

  say "terms needed to generate 0 to 1000: "
  startseq
  [ nextterm
    1000 allseen? until ]
  nip 1 - echo cr


visited <- vector('logical', 1e8)

terms <- vector('numeric')

in_a_interval <- function(v) {
	visited[[v+1]]
}

add_value <- function(v) {
	visited[[v+1]] <<- TRUE
	terms <<- append(terms, v)
}

add_value(0)
step <- 1
value <- 0

founddup <- FALSE

repeat {
	if ((value-step>0) && (!in_a_interval(value-step))) {
		value <- value - step
	} else {
		value <- value + step
	}
	if (in_a_interval(value) && !founddup) {
		cat("The first duplicated term is a[",step,"] = ",value,"\n", sep = "")
		founddup <- TRUE
	}
	add_value(value)
	if (all(visited[1:1000])) {
		cat("Terms up to a[",step,"] are needed to generate 0 to 1000\n",sep = "")
		break
	}
	step <- step + 1
	if (step == 15) {
		cat("The first 15 terms are :")
		for (aterm in terms) { cat(aterm," ", sep = "") }
		cat("\n")
	}
}


e =. 1x1   NB. Euler's number, specified as a numeric literal.
e =. ^ 1   NB. Euler's number, computed by exponentiation.
pi=. 1p1   NB. pi, specified as a numeric literal.
pi=. o.1   NB. pi, computed trigonometrically.
magnitude_of_x   =. |x
floor_of_x       =. <.x
ceiling_of_x     =. >.x
natural_log_of_x =. ^.x
base_x_log_of_y  =. x^.y
x_squared        =. *:x     NB. special form
x_squared        =. x^2     NB. exponential form
square_root_of_x =. %:x     NB. special form
square_root_of_x =. x^0.5   NB. exponential form
x_to_the_y_power =. x^y


Math.E; //e
Math.PI; //pi
Math.sqrt(x); //square root--cube root also available (cbrt)
Math.log(x); //natural logarithm--log base 10 also available (log10)
Math.exp(x); //exponential
Math.abs(x); //absolute value
Math.floor(x); //floor
Math.ceil(x); //ceiling
Math.pow(x,y); //power


Math.E
Math.PI
Math.sqrt(x)
Math.log(x)
Math.exp(x)
Math.abs(x)
Math.floor(x)
Math.ceil(x)
Math.pow(x,y)


my @recamans = 0, {
   state %seen;
   state $term;
   $term++;
   my $this = $^previous - $term;
   $this = $previous + $term unless ($this > 0) && !%seen{$this};
   %seen{$this} = True;
   $this
} … *;

put "First fifteen terms of Recaman's sequence: ", @recamans[^15];

say "First duplicate at term: a[{ @recamans.first({@recamans[^$_].Bag.values.max == 2})-1 }]";

my @seen;
my int $i = 0;
loop {
    next if (my int $this = @recamans[$i++]) > 1000 or @seen[$this];
    @seen[$this] = 1;
    say "Range 0..1000 covered by terms up to a[{$i - 1}]" and last if ++$ == 1001;
}


  if z<0  then              z= _ + #
          else if !.z  then z= _ + #


load "zerolib.ring"

recaman = Z(0:50)
duplicate = 0
dup = []
recDuplicate = []
recnum = 0

see "working..." + nl
see "the first 15 Recaman's numbers are:" + nl

for n = 1 to len(recaman) - 1
    if n = 1
       recaman[0] = 0
       add(dup,0)
       see "" + recaman[0] + " "
    ok
    recaman[n] = recaman[n-1] - n
    if recaman[n] <= 0
       recaman[n] = recaman[n-1] + n
    ok
    fnrec = find(dup,recaman[n])
    if fnrec > 0
       del(dup,fnrec)
       recaman[n] = recaman[n-1] + n
       add(dup,recaman[n])
    else
       add(dup,recaman[n])
    ok
    recnum = recnum + 1
    if recnum < 15
       see "" + recaman[n] + " "
    ok
    add(recDuplicate,recaman[n])
next
see nl

see "the first duplicated term is a["
for n = len(recDuplicate) to 2 step -1
    for m = n-1 to 1 step -1
        if recDuplicate[n] = recDuplicate[m]
           duplicate = recDuplicate[n]
           dupnr = n
        ok
    next
next

see "" + dupnr + "] = " + duplicate + nl
see "done..." + nl


require 'set'

a = [0]
used = Set[0]
used1000 = Set[0]
foundDup = false
n = 1
while n <= 15 or not foundDup or used1000.size < 1001
    nxt = a[n - 1] - n
    if nxt < 1 or used === nxt then
        nxt = nxt + 2 * n
    end
    alreadyUsed = used === nxt
    a << nxt
    if not alreadyUsed then
        used << nxt
        if nxt >= 0 and nxt <= 1000 then
            used1000 << nxt
        end
    end
    if n == 14 then
        print "The first 15 terms of the Recaman's sequence are ", a, "\n"
    end
    if not foundDup and alreadyUsed then
        print "The first duplicated term is a[", n, "] = ", nxt, "\n"
        foundDup = true
    end
    if used1000.size == 1001 then
        print "Terms up to a[", n, "] are needed to generate 0 to 1000\n"
    end
    n = n + 1
end


1 | exp                      # i.e. e
1 | atan * 4                 # i.e. π
sqrt
log                          # Naperian log
exp
length                       # absolute value if the argument is numeric
floor
ceil                         # requires jq >= 1.5
pow(x; y)                    # requires jq >= 1.5


e
π, pi
sqrt(x)
log(x)
exp(x)
abs(x)
floor(x)
ceil(x)
x^y


// version 1.0.6

fun main(args: Array<String>) {
    println(Math.E)                // e
    println(Math.PI)               // pi
    println(Math.sqrt(2.0))        // square root
    println(Math.log(Math.E))      // log to base e
    println(Math.log10(10.0))      // log to base 10
    println(Math.exp(1.0))         // exponential
    println(Math.abs(-1))          // absolute value
    println(Math.floor(-2.5))      // floor
    println(Math.ceil(-2.5))       // ceiling
    println(Math.pow(2.5, 3.5))    // power
}


import scala.collection.mutable

object RecamansSequence extends App {
  val (a, used) = (mutable.ArrayBuffer[Int](0), mutable.BitSet())
  var (foundDup, hop, nUsed1000) = (false, 1, 0)

  while (nUsed1000 < 1000) {
    val _next = a(hop - 1) - hop
    val next = if (_next < 1 || used.contains(_next)) _next + 2 * hop else _next
    val alreadyUsed = used.contains(next)

    a += next
    if (!alreadyUsed) {
      used.add(next)
      if (next <= 1000) nUsed1000 += 1
    }
    if (!foundDup && alreadyUsed) {
      println(s"The first duplicate term is a($hop) = $next")
      foundDup = true
    }
    if (nUsed1000 == 1000)
      println(s"Terms up to $hop are needed to generate 0 to 1000")

    hop += 1
  }

  println(s"The first 15 terms of the Recaman sequence are : ${a.take(15)}")

}


; Create a dynamically resizing vector (a "dynvec").
; Returns a procedure that takes a variable number of arguments:
; 0 : () --> Returns the vector from index 0 through the maximum index set.
; 1 : (inx) --> Returns the value at the given index.
; 2 : (inx val) --> Sets the given value into the given index, and returns the value.

(define make-dynvec
  (lambda (init-size extra-fact init-val)
    (let ((vec (make-vector init-size init-val)) (maxinx -1))
      (lambda args
        (if (null? args)
          (let ((retvec (make-vector (1+ maxinx))))
            (do ((index 0 (1+ index)))
                ((> index maxinx) retvec)
              (vector-set! retvec index (vector-ref vec index))))
          (let ((inx (car args)))
            (when (>= inx (vector-length vec))
              (let ((newvec (make-vector
                              (inexact->exact (ceiling (* extra-fact inx)))
                              init-val)))
                (do ((index 0 (1+ index)))
                    ((>= index (vector-length vec)))
                  (vector-set! newvec index (vector-ref vec index)))
                (set! vec newvec)))
            (when (pair? (cdr args))
              (when (> inx maxinx) (set! maxinx inx))
              (vector-set! vec inx (cadr args)))
            (vector-ref vec inx)))))))

; Generate the Recaman's sequence.
; Generate the terms of Recaman's sequence until the given "stop" procedure
; returns a true value; that returned value becomes the value of this procedure.
; The arguments to the "stop" procedure are:  n, the value of the n'th term,
; #t if that term was seen before, #t if the term was arrived at by addition,
; the Recaman's sequence so far (as a dynvec), and a dynvec of the n's at which
; a value was first seen or #f if not previously seen ("seen1st").

(define recaman-sequence
  (lambda (stop-proc)
    (let ((recaman (make-dynvec 10 2 0))
          (seen1st (make-dynvec 10 2 #f)))
      (do ((n 0 (1+ n)) (done-retval #f))
          (done-retval done-retval)
        (if (= n 0)
          (begin
            (recaman n 0)
            (seen1st 0 n)
            (set! done-retval (stop-proc n 0 #f #f recaman seen1st)))
          (let ((try-sub (- (recaman (1- n)) n)))
            (if (and (> try-sub 0) (not (seen1st try-sub)))
              (begin
                (recaman n try-sub)
                (seen1st try-sub n)
                (set! done-retval (stop-proc n try-sub #f #f recaman seen1st)))
              (let* ((val-add (+ (recaman (1- n)) n)) (seen-prev (seen1st val-add)))
                (recaman n val-add)
                (unless (seen1st val-add) (seen1st val-add n))
                (set! done-retval
                      (stop-proc n val-add seen-prev #t recaman seen1st))))))))))

; Generate and display the first 15 Recaman's numbers.

(printf "First 15 Recaman's numbers: ~a~%"
        (recaman-sequence (lambda (n val seen-prev by-add recaman seen1st)
                            (and (>= n (1- 15)) (recaman)))))

; Find and display the first duplicated Recaman's number.
; The only way to be a duplicate is if the number was arrived
; at by adding 'n' and the number has been seen before.

(let ((dup-n-val-1st
        (recaman-sequence (lambda (n val seen-prev by-add recaman seen1st)
                            (and by-add seen-prev (list n val (seen1st val)))))))
  (printf "First duplicate Recaman's number: a[~a] = a[~a] = ~a~%"
          (caddr dup-n-val-1st) (car dup-n-val-1st) (cadr dup-n-val-1st)))

; Find and display how many terms of the sequence are needed
; for all the integers 0..1000, inclusive, to be generated.

(let* ((all-first 1001)
       (terms-to-gen-all (recaman-sequence
                           (lambda (n val seen-prev by-add recaman seen1st)
                             (do ((inx 0 (1+ inx)))
                                 ((or (>= inx all-first) (not (seen1st inx)))
                                  (and (>= inx all-first) (1+ n))))))))
  (printf
    "Terms of Recaman's sequence to generate all integers 0..~a, inclusive: ~a~%"
    (1- all-first) terms-to-gen-all))


print exp( 1)            ' e  not available
print 4 *atn( 1)         ' pi not available

x =12.345: y =1.23

print sqr( x), x^0.5     ' square root- NB the unusual name
print log( x)            ' natural logarithm base e
print log( x) /2.303     ' base 10 logarithm
print log( x) /log( y)   ' arbitrary base logarithm
print exp( x)            ' exponential
print abs( x)            ' absolute value
print floor( x)          ' floor
print ceiling( x)        ' ceiling
print x^y                ' power

end

function floor( x)
    if x >0 then
        floor =int( x)
    else
        if x <>int( x) then floor =int( x) -1 else floor =int( x)
    end if
end function

function ceiling( x)
    if x <0 then
        ceiling =int( x)
    else
        ceiling =int( x) +1
    end if
end function


func recamans_generator() {

    var term = 0
    var prev = 0
    var seen = Hash()

    {
        var this = (prev - term)

        if ((this <= 0) || seen{this}) {
            this = (prev + term)
        }

        prev = this
        seen{this} = true
        term++
        this
    }
}

with (recamans_generator()) { |r|
    say ("First 15 terms of the Recaman's sequence: ", 15.of { r.run }.join(', '))
}

with (recamans_generator()) {|r|
    var seen = Hash()
    Inf.times {|i|
        var n = r.run
        if (seen{n}) {
            say "First duplicate term in the series is a(#{i}) = #{n}"
            break
        }
        seen{n} = true
    }
}

with (recamans_generator()) {|r|
    var seen = Hash()
    Inf.times {|i|
        var n = r.run
        if ((n <= 1000) && (seen{n} := true) && (seen.len == 1001)) {
            say "Terms up to a(#{i}) are needed to generate 0 to 1000"
            break
        }
    }
}


a = 0                                  ' the first one is free ;-)
Print "First 15 numbers:"

For i = 1 Step 1                       ' start loop
  If i<16 Then Print a,                ' print first 15 numbers
  b = Iif ((a-i<1) + (Func(_Peek(Max(0, a-i)))), a+i, a-i)
  If Func(_Peek(b)) Then Print "\nFirst repetition: ";b : Break
  Proc _Set(Set(a, b))                 ' set bit in bitmap
Next
End                                    ' terminate program
                                       ' bitmap functions
_Set  Param(1) : Let @([email protected]/32) = Func(_Poke([email protected]/32, [email protected]%32)) : Return
_Poke Param(2) : Return (Or(@([email protected]), Shl(1, [email protected])))
_Peek Param(1) : Return (And(@([email protected]/32), Shl(1, [email protected]%32))>0)


' Recaman's sequence - vbscript - 04/08/2015
	nx=15
	h=1000
	Wscript.StdOut.WriteLine "Recaman's sequence for the first " & nx & " numbers:"
	Wscript.StdOut.WriteLine recaman("seq",nx)
	Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0)
	Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h)
	Wscript.StdOut.Write vbCrlf&".../...": zz=Wscript.StdIn.ReadLine()

function recaman(op,nn)
	Dim b,d,h
	Set b = CreateObject("Scripting.Dictionary")
	Set d = CreateObject("Scripting.Dictionary")
    list="0" : firstdup=0
	if op="firstdup" then
		nn=1000 : firstdup=1
	end if
	if op="numterm" then
		h=nn : nn=10000000 : numterm=1
	end if
	ax=0  'a(0)=0
	b.Add 0,1  'b(0)=1
	s=0
	for n=1 to nn-1
        an=ax-n
		if an<=0 then
			an=ax+n
		elseif b.Exists(an) then
			an=ax+n
		end if
		ax=an  'a(n)=an
		if not b.Exists(an) then b.Add an,1  'b(an)=1
		if op="seq" then
			list=list&" "&an
		end if
		if firstdup then
			if d.Exists(an) then
				recaman="a("&n&")="&an
				exit function
			else
				d.Add an,1  'd(an)=1
			end if
		end if
		if numterm then
			if an<=h then
				if not d.Exists(an) then
					s=s+1
					d.Add an,1  'd(an)=1
				end if
				if s>=h then
					recaman=n
					exit function
				end if
			end if
		end if
	next 'n
	recaman=list
end function 'recaman


the floatPrecision = 8

-- e (base of the natural logarithm)
put exp(1)
-- 2.71828183

-- pi
put PI
-- 3.14159265

-- square root
put sqrt(2.0)
-- 1.41421356

-- logarithm (any base allowed)
x = 100

put log(x) -- calculate log for base e
-- 4.60517019

put log(x)/log(10) -- calculate log for base 10
-- 2.00000000

-- exponential (ex)
put exp(3)
-- 20.08553692

-- absolute value (a.k.a. "magnitude")
put abs(-1)
-- 1

-- floor (largest integer less than or equal to this number--not the same as truncate or int)
n = 23.536
put bitOr(n, 0) -- calculates floor
-- 23

-- ceiling (smallest integer not less than this number--not the same as round up)
n = 23.536
-- calculates ceil
floor = bitOr(n, 0)
if (floor >= n) then put floor
else put floor+1
-- 24

-- power
put power(2, 8)
-- 256.00000000


e: exp(1)
pi: pi
square root: sqrt(x)
logarithm: log(x)
exponential (ex): exp(x)
absolute value: abs(x)
floor: floor(x)
ceiling: ceil(x)
power: x^y


make "e exp 1
make "pi 2*(RADARCTAN 0 1)
sqrt :x
ln :x
exp :x
; there is no standard abs, floor, or ceiling; only INT and ROUND.
power :x :y


:- object(constants_and_functions).

    :- public(show/0).
    show :-
        write('e = '), E is e, write(E), nl,
        write('pi = '), PI is pi, write(PI), nl,
        write('sqrt(2) = '), SQRT is sqrt(2), write(SQRT), nl,
        % only base e logorithm is avaialable as a standard built-in function
        write('log(2) = '), LOG is log(2), write(LOG), nl,
        write('exp(2) = '), EXP is exp(2), write(EXP), nl,
        write('abs(-1) = '), ABS is abs(-1), write(ABS), nl,
        write('floor(-3.4) = '), FLOOR is floor(-3.4), write(FLOOR), nl,
        write('ceiling(-3.4) = '), CEILING is ceiling(-3.4), write(CEILING), nl,
        write('2 ** -3.4 = '), POWER is 2 ** -3.4, write(POWER), nl.

:- end_object.


Imports System
Imports System.Collections.Generic

Module Module1
    Sub Main(ByVal args As String())
        Dim a As List(Of Integer) = New List(Of Integer)() From { 0 },
            used As HashSet(Of Integer) = New HashSet(Of Integer)() From { 0 },
            used1000 As HashSet(Of Integer) = used.ToHashSet(),
            foundDup As Boolean = False
        For n As Integer = 1 to Integer.MaxValue
            Dim nv As Integer = a(n - 1) - n
            If nv < 1 OrElse used.Contains(nv) Then nv += 2 * n
            Dim alreadyUsed As Boolean = used.Contains(nv) : a.Add(nv)
            If Not alreadyUsed Then used.Add(nv) : If nv > 0 AndAlso nv <= 1000 Then used1000.Add(nv)
            If Not foundDup Then
                If a.Count = 15 Then _
                    Console.WriteLine("The first 15 terms of the Recamán sequence are: ({0})", String.Join(", ", a))
                If alreadyUsed Then _
                    Console.WriteLine("The first duplicated term is a({0}) = {1}", n, nv) : foundDup = True
            End If
            If used1000.Count = 1001 Then _
                Console.WriteLine("Terms up to a({0}) are needed to generate 0 to 1000", n) : Exit For
        Next
    End Sub
End Module


var a = [0]
var used = { 0: true }
var used1000 = { 0: true }
var foundDup = false
var n = 1
while (n <= 15 || !foundDup || used1000.count < 1001) {
    var next = a[n-1] - n
    if (next < 1 || used[next]) next = next + 2*n
    var alreadyUsed = used[next]
    a.add(next)
    if (!alreadyUsed) {
        used[next] = true
        if (next >= 0 && next <= 1000) used1000[next] = true
    }
    if (n == 14) System.print("The first 15 terms of the Recaman's sequence are:\n%(a)")
    if (!foundDup && alreadyUsed) {
        System.print("The first duplicated term is a[%(n)] = %(next)")
        foundDup = true
    }
    if (used1000.count == 1001) {
        System.print("Terms up to a[%(n)] are needed to generate 0 to 1000")
    }
    n = n + 1
}


math.exp(1)
math.pi
math.sqrt(x)
math.log(x)
math.log10(x)
math.exp(x)
math.abs(x)
math.floor(x)
math.ceil(x)
x^y


Module Checkit {
      Def exp(x)= 2.71828182845905^x
      Print Ln(exp(1))==1
      Print Log(10^5)==5
      Print Sgn(-5)=-1
      Print Abs(-2.10#)=2.1#
      Def exptype$(x)=type$(x)
      Print exptype$(Abs(-2.1#))="Currency"
      Print exptype$(Abs(-2.1~))="Single"
      Print exptype$(Abs([email protected]))="Decimal"
      Print exptype$(Abs(-2&))="Long"
      Print exptype$(Abs(-2%))="Integer"
      Print exptype$(Abs(-2.212e34))="Double"

      Print exptype$(Sgn(-2.1#))="Integer"
      \\ Sgn return integer type
      Print exptype$(Sgn(-2.212e34))="Integer"
      \\ Log, Len return double
      Print exptype$(Log(1000))="Double"
      Print exptype$(exp(1%))="Double"
      Print exptype$(Ln(1212%))="Double"
      \\ power return type Double
      Print exptype$(2&^2&)="Double"
      Print exptype$(2&**2&)="Double"
      Print exptype$(2&*2&)="Long"
      Print 2**2=4, 2^2=4, 2^2^2=16, 2**2**2=16
      \\ floor() and Int() is the same
      Print Int(-2.7)=-3, Int(2.7)=2
      Print Floor(-2.7)=-3, Floor(2.7)=2
      Print Ceil(-2.7)=-2, Ceil(2.7)=3

      Print round(-2.7, 0)=-3, round(2.7, 0)=3
      Print round(-2.2, 0)=-2, round(2.2, 0)=2

      Print Sqrt(4)=2
}
Checkit


> abs(ceil(floor(ln(exp(1)^sqrt(exp(Pi*I)+1)))));
                                   0


E
Pi
Sqrt[x]
Log[x]
Log[b,x]
Exp[x]
Abs[x]
Floor[x]
Ceiling[x]
Power[x, y]


fcn recamanW{  // -->iterator -->(n,a,True if a is a dup)
   Walker.tweak(fcn(rn,rp,d){
      n,p,a := rn.value, rp.value, p - n;
      if(a<=0 or d.find(a)) a+=2*n;
      d.incV(a); rp.set(a);
      return(rn.inc(),a,d[a]>1);
   }.fp(Ref(0),Ref(0),Dictionary()) )
}


F ToReducedRowEchelonForm(&M)
   V lead = 0
   V rowCount = M.len
   V columnCount = M[0].len
   L(r) 0 .< rowCount
      I lead >= columnCount
         R
      V i = r
      L M[i][lead] == 0
         i++
         I i == rowCount
            i = r
            lead++
            I columnCount == lead
               R
      swap(&M[i], &M[r])
      V lv = M[r][lead]
      M[r] = M[r].map(mrx -> mrx / Float(@lv))
      L(i) 0 .< rowCount
         I i != r
            lv = M[i][lead]
            M[i] = zip(M[r], M[i]).map((rv, iv) -> iv - @lv * rv)
      lead++

V mtx = [[ 1.0, 2.0, -1.0,  -4.0],
         [ 2.0, 3.0, -1.0, -11.0],
         [-2.0, 0.0, -3.0,  22.0]]

ToReducedRowEchelonForm(&mtx)

L(rw) mtx
   print(rw.join(‘, ’))


exp(1)    % e
pi        % pi
sqrt(x)   % square root
log(x)    % natural logarithm
log2(x)   % logarithm base 2
log10(x)  % logarithm base 10
exp(x)    % exponential
abs(-x)   % absolute value
floor(x)  % floor
ceil(x)   % ceiling
x^y       % power


e       -- Euler's number
pi      -- pi
log x   -- natural logarithm
log10 x -- log base 10
exp x   -- exponantial
abs x   -- absolute value
floor x -- floor
ceil x  -- ceiling
pow x y -- power


math.pi         % Pi.
math.e          % Euler's number.
math.sqrt(X)    % Square root of X.
math.ln(X)      % Natural logarithm of X.
math.log10(X)   % Logarithm to the base 10 of X.
math.log2(X)    % Logarithm to the base 2 of X.
math.log(B, X)  % Logarithm to the base B of X.
math.exp(X)     % e raised to the power of X.
float.abs(X)    % Absolute value of X.
math.floor(X)   % Floor of X.
math.ceiling(X) % Ceiling of X.
math.pow(X, Y)  % X raised to the power of Y.


show mexp(256);   % outputs e; since MF uses mexp(x) = exp(x/256)
show 3.14159;     % no pi constant built in; of course we can define it
                  % in several ways... even computing
                  % C/2r (which would be funny since MF handles paths,
                  % and a circle is a path...)
show sqrt2;       % 1.41422, or in general sqrt(a)
show mexp(256*x); % see e.
show abs(x);      % returns |x| (the absolute value of the number x, or
                  % the length of the vector x); it is the same as
                  % length(x); plain Metafont in fact says:
                  % let abs = length;
show floor(x);    % floor
show ceiling(x);  % ceiling
show x**y;        % ** is not a built in: it is defined in the basic macros
                  % set for Metafont (plain Metafont) as a primarydef


*        reduced row echelon form  27/08/2015
RREF     CSECT
         USING  RREF,R12
         LR     R12,R15
         LA     R10,1              lead=1
         LA     R7,1
LOOPR    CH     R7,NROWS           do r=1 to nrows
         BH     ELOOPR
         CH     R10,NCOLS          if lead>=ncols
         BNL    ELOOPR
         LR     R8,R7              i=r
WHILE    LR     R1,R8              do while m(i,lead)=0
         BCTR   R1,0
         MH     R1,NCOLS
         LR     R6,R10             lead
         BCTR   R6,0
         AR     R1,R6
         SLA    R1,2
         L      R6,M(R1)           m(i,lead)
         LTR    R6,R6
         BNZ    EWHILE             m(i,lead)<>0
         LA     R8,1(R8)           i=i+1
         CH     R8,NROWS           if i=nrows
         BNE    EIF
         LR     R8,R7              i=r
         LA     R10,1(R10)         lead=lead+1
         CH     R10,NCOLS          if lead=ncols
         BE     ELOOPR
EIF      B      WHILE
EWHILE   LA     R9,1
LOOPJ1   CH     R9,NCOLS           do j=1 to ncols
         BH     ELOOPJ1
         LR     R1,R7              r
         BCTR   R1,0
         MH     R1,NCOLS
         LR     R6,R9              j
         BCTR   R6,0
         AR     R1,R6
         SLA    R1,2
         LA     R3,M(R1)           [email protected](r,j)
         LR     R1,R8              i
         BCTR   R1,0
         MH     R1,NCOLS
         LR     R6,R9              j
         BCTR   R6,0
         AR     R1,R6
         SLA    R1,2
         LA     R4,M(R1)           [email protected](i,j)
         L      R2,0(R3)
         MVC    0(2,R3),0(R4)      swap m(i,j),m(r,j)
         ST     R2,0(R4)
         LA     R9,1(R9)           j=j+1
         B      LOOPJ1
ELOOPJ1  LR     R1,R7              r
         BCTR   R1,0
         MH     R1,NCOLS
         LR     R6,R10             lead
         BCTR   R6,0
         AR     R1,R6
         SLA    R1,2
         L      R11,M(R1)          n=m(r,lead)
         CH     R11,=H'1'          if n^=1
         BE     ELOOPJ2
         LA     R9,1
LOOPJ2   CH     R9,NCOLS           do j=1 to ncols
         BH     ELOOPJ2
         LR     R1,R7              r
         BCTR   R1,0
         MH     R1,NCOLS
         LR     R6,R9              j
         BCTR   R6,0
         AR     R1,R6
         SLA    R1,2
         LA     R5,M(R1)           [email protected](i,j)
         L      R2,0(R5)           m(r,j)
         LR     R1,R11             n
         SRDA   R2,32
         DR     R2,R1              m(r,j)/n
         ST     R3,0(R5)           m(r,j)=m(r,j)/n
         LA     R9,1(R9)           j=j+1
         B      LOOPJ2
ELOOPJ2  LA     R8,1
LOOPI3   CH     R8,NROWS           do i=1 to nrows
         BH     ELOOPI3
         CR     R8,R7              if i^=r
         BE     ELOOPJ3
         LR     R1,R8              i
         BCTR   R1,0
         MH     R1,NCOLS
         LR     R6,R10             lead
         BCTR   R6,0
         AR     R1,R6
         SLA    R1,2
         L      R11,M(R1)          n=m(i,lead)
         LA     R9,1
LOOPJ3   CH     R9,NCOLS           do j=1 to ncols
         BH     ELOOPJ3
         LR     R1,R8              i
         BCTR   R1,0
         MH     R1,NCOLS
         LR     R6,R9              j
         BCTR   R6,0
         AR     R1,R6
         SLA    R1,2
         LA     R4,M(R1)           [email protected](i,j)
         L      R5,0(R4)           m(i,j)
         LR     R1,R7              r
         BCTR   R1,0
         MH     R1,NCOLS
         LR     R6,R9              j
         BCTR   R6,0
         AR     R1,R6
         SLA    R1,2
         L      R3,M(R1)           m(r,j)
         MR     R2,R11             m(r,j)*n
         SR     R5,R3              m(i,j)-m(r,j)*n
         ST     R5,0(R4)           m(i,j)=m(i,j)-m(r,j)*n
         LA     R9,1(R9)           j=j+1
         B      LOOPJ3
ELOOPJ3  LA     R8,1(R8)           i=i+1
         B      LOOPI3
ELOOPI3  LA     R10,1(R10)         lead=lead+1
         LA     R7,1(R7)           r=r+1
         B      LOOPR
ELOOPR   LA     R8,1
LOOPI4   CH     R8,NROWS           do i=1 to nrows
         BH     ELOOPI4
         SR     R10,R10            pgi=0
         LA     R9,1
LOOPJ4   CH     R9,NCOLS           do j=1 to ncols
         BH     ELOOPJ4
         LR     R1,R8              i
         BCTR   R1,0
         MH     R1,NCOLS
         LR     R6,R9              j
         BCTR   R6,0
         AR     R1,R6
         SLA    R1,2
         L      R6,M(R1)           m(i,j)
         LA     R3,PG
         AR     R3,R10
         XDECO  R6,0(R3)           edit m(i,j)
         LA     R10,12(10)         pgi=pgi+12
         LA     R9,1(R9)           j=j+1
         B      LOOPJ4
ELOOPJ4  XPRNT  PG,48              print m(i,j)
         LA     R8,1(R8)           i=i+1
         B      LOOPI4
ELOOPI4  XR     R15,R15
         BR     R14
NROWS    DC     H'3'
NCOLS    DC     H'4'
M        DC     F'1',F'2',F'-1',F'-4'
         DC     F'2',F'3',F'-1',F'-11'
         DC     F'-2',F'0',F'-3',F'22'
PG       DC     CL48' '
         YREGS
         END    RREF


public function RREF():Matrix {
   var lead:uint, i:uint, j:uint, r:uint = 0;

   for(r = 0; r < rows; r++) {
      if(columns <= lead)
         break;
      i = r;

      while(_m[i][lead] == 0) {
         i++;

         if(rows == i) {
            i = r;
            lead++;

            if(columns == lead)
               return this;
         }
      }
      rowSwitch(i, r);
      var val:Number = _m[r][lead];

      for(j = 0; j < columns; j++)
         _m[r][j] /= val;

      for(i = 0; i < rows; i++) {
         if(i == r)
            continue;
         val = _m[i][lead];

         for(j = 0; j < columns; j++)
            _m[i][j] -= val * _m[r][j];
      }
      lead++;
   }
   return this;
}


e       ; e
pi      ; π
sqrt    ; square root
log10   ; common logarithm
log2    ; binary logarithm
        ; no exponential
        ; no absolute value
floor   ; greatest whole number smaller than or equal
ceil    ; smallest whole number greater than or equal
trunc   ; remove the fractional part (i.e. round towards 0)
round   ; round number to nth decimal place
pow     ; power


1	e^x	С/П

пи	С/П

КвКор	С/П

lg	С/П

e^x	С/П

|x|	С/П

П0	^	[x]	П1	-	x=0	09	ИП0	С/П	ЗН
x>=0	14	ИП1	С/П	ИП1	1	-	С/П

П0	^	[x]	П1	-	x=0	09	ИП0	С/П	ЗН
x<0	14	ИП1	С/П	ИП1	1	+	С/П

x^y	С/П


Math.E;
Math.Pi;
Math.sqrt(x);
Math.log(x);
Math.exp(x);
ABS(x); (* Built in function. *)
FLOOR(x); (* Built in function. *)
CEILING(x); (* Built in function. *)
Math.pow(x, y);


/**
 Real constants and functions, in Neko
 Tectonics:
   nekoc real-constants.neko
   neko real-constants
*/

var euler = $loader.loadprim("[email protected]_exp", 1)(1)
var pi = $loader.loadprim("[email protected]_pi", 0)()

var math_sqrt = $loader.loadprim("[email protected]_sqrt", 1)
var math_log = $loader.loadprim("[email protected]_log", 1)
var math_exp = $loader.loadprim("[email protected]_exp", 1)
var math_abs = $loader.loadprim("[email protected]_abs", 1)
var math_floor = $loader.loadprim("[email protected]_floor", 1)
var math_ceil = $loader.loadprim("[email protected]_ceil", 1)
var math_pow = $loader.loadprim("[email protected]_pow", 2)

$print("Euler      : ", euler, "\n")
$print("Pi         : ", pi, "\n")

$print("Sqrt(2)    : ", math_sqrt(2), "\n")
$print("Log(10)    : ", math_log(10), "\n")
$print("Exp(1)     : ", math_pow(euler, 1), "\n")
$print("Abs(-2.2)  : ", math_abs(-2.2), "\n")
$print("Floor(-2.2): ", math_floor(-2.2), "\n")
$print("Ceil(-2.2) : ", math_ceil(-2.2), "\n")
$print("Pow(2, 8)  : ", math_pow(2, 8), "\n")


generic
   type Element_Type is private;
   Zero : Element_Type;
   with function "-" (Left, Right : in Element_Type) return Element_Type is <>;
   with function "*" (Left, Right : in Element_Type) return Element_Type is <>;
   with function "/" (Left, Right : in Element_Type) return Element_Type is <>;
package Matrices is
   type Matrix is
     array (Positive range <>, Positive range <>) of Element_Type;
   function Reduced_Row_Echelon_form (Source : Matrix) return Matrix;
end Matrices;


rref(list l, integer rows, columns)
{
    integer e, f, i, j, lead, r;
    list u, v;

    lead = r = 0;
    while (r < rows && lead < columns) {
        i = r;
        while (!l.q_list(i)[lead]) {
            i += 1;
            if (i == rows) {
                i = r;
                lead += 1;
                if (lead == columns) {
                    break;
                }
            }
        }
        if (lead == columns) {
            break;
        }

        u = l[i];

        l.spin(i, r);
        e = u[lead];
        if (e) {
            for (j, f in u) {
                u[j] = f / e;
            }
        }

        for (i, v in l) {
            if (i != r) {
                e = v[lead];
                for (j, f in v) {
                    v[j] = f - u[j] * e;
                }
            }
        }

        lead += 1;

        r += 1;
    }
}

display_2(list l)
{
    for (, list u in l) {
        u.ucall(o_winteger, -1, 4);
        o_byte('\n');
    }
}

main(void)
{
    list l;

    l = list(list(1, 2, -1, -4),
             list(2, 3, -1, -11),
             list(-2, 0, -3, 22));
    rref(l, 3, 4);
    display_2(l);

    0;
}