fun main() {
    println("First 10 terms of Van Eck's sequence:")
    vanEck(1, 10)
    println("")
    println("Terms 991 to 1000 of Van Eck's sequence:")
    vanEck(991, 1000)
}

private fun vanEck(firstIndex: Int, lastIndex: Int) {
    val vanEckMap = mutableMapOf<Int, Int>()
    var last = 0
    if (firstIndex == 1) {
        println("VanEck[1] = 0")
    }
    for (n in 2..lastIndex) {
        val vanEck = if (vanEckMap.containsKey(last)) n - vanEckMap[last]!! else 0
        vanEckMap[last] = n
        last = vanEck
        if (n >= firstIndex) {
            println("VanEck[$n] = $vanEck")
        }
    }
}


// Both of the following declarations can be seen as a tree,
// var -> <varname>
var/x
var y

// They can also be defined like this.
// This is once again a tree structure, but this time the "var" only appears once, and the x and y are children.
var
    x
    y
// And like this, still a tree structure.
var/x, y


add_var(v1);
dim(v1);
add_var(v1, v2, v3, v4);
dim(v1, v2, v3, v4);
add_var(isRaining)_datatype(boolean);
dim(isRaining)_datatype(boolean);
add_var(greeting)_dt(string);
dim(greeting)_dt(string);
add_var({date}, birthdate);
dim({date}, birthdate);


var i := 123;             // inferred type of i is Integer
var s := 'abc';           // inferred type of s is String
var o := TObject.Create;  // inferred type of o is TObject
var s2 := o.ClassName;    // inferred type of s2 is String as that's the type returned by ClassName


#!/usr/bin/awk -f
BEGIN {
     a[1] = 3; a[2]= 4; a[3] = 5;
     b[1] = 4; b[2]= 3; b[3] = 5;
     c[1] = -5; c[2]= -12; c[3] = -13;

     print "a = ",printVec(a);
     print "b = ",printVec(b);
     print "c = ",printVec(c);
     print "a.b = ",dot(a,b);
     ## upper case variables are used as temporary or intermediate results
     cross(a,b,D);print "a.b = ",printVec(D);
     cross(b,c,D);print "a.(b x c) = ",dot(a,D);
     cross(b,c,D);cross(a,D,E); print "a x (b x c) = ",printVec(E);
}

function dot(A,B) {
     return A[1]*B[1]+A[2]*B[2]+A[3]*B[3];
}

function cross(A,B,C) {
     C[1] = A[2]*B[3]-A[3]*B[2];
     C[2] = A[3]*B[1]-A[1]*B[3];
     C[3] = A[1]*B[2]-A[2]*B[1];
}

function printVec(C) {
    return "[ "C[1]" "C[2]" "C[3]" ]";
}


-- Return a table of the first n values of the Van Eck sequence
function vanEck (n)
  local seq, foundAt = {0}
  while #seq < n do
    foundAt = nil
    for pos = #seq - 1, 1, -1 do
      if seq[pos] == seq[#seq] then
        foundAt = pos
        break
      end
    end
    if foundAt then
      table.insert(seq, #seq - foundAt)
    else
      table.insert(seq, 0)
    end
  end
  return seq
end

-- Show the set of values in table t from key numbers lo to hi
function showValues (t, lo, hi)
  for i = lo, hi do
    io.write(t[i] .. " ")
  end
  print()
end

-- Main procedure
local sequence = vanEck(1000)
showValues(sequence, 1, 10)
showValues(sequence, 991, 1000)


            NORMAL MODE IS INTEGER
            DIMENSION E(1000)
            E(0)=0
            THROUGH L1, FOR I=0, 1, I.GE.1000
            THROUGH L2, FOR J=I-1, -1, J.L.0
            WHENEVER E(J).E.E(I)
                E(I+1) = I-J
                TRANSFER TO L1
            END OF CONDITIONAL
L2          CONTINUE
            E(I+1)=0
L1          CONTINUE
            THROUGH S, FOR I=0, 1, I.GE.10
S           PRINT FORMAT FMT, I, E(I), I+990, E(I+990)
            VECTOR VALUES FMT = $2HE(,I3,2H)=,I3,S5,2HE(,I3,2H)=,I3*$
            END OF PROGRAM


//A constant declaration
let pi = 3.14

private {
    //private constant, not visible outside of a module
    let privateConst = 3.3
}

//Variable declaration
var x = 42

//Assignment
x = 42.42

//Dyalect is a dynamic language, so types are attached
//to values, not to the names
var foo = (x: 2, y: 4) //foo is of type Tuple
var bar = "Hello!" //bar is of type String

//Global variable
var g = 1.1

{
    //local variable (not visible outside of { } brackets)
    var loc = 2.2
}

func fun() {
    //Local variables, not visible outside of function
    var x = 1
    var y = 2
}

func parent() {
    //A local variable inside a parent function
    var x = 1
    func child() {
        //A local variable inside a nested function
        //It shadows a parent's variable
        var x = 2

        //But this is how we can reference a variable from
        //a parent function
        base.x
    }
}


# it is statically typed
#
# global number variable
n = 99
print n
# global array of numbers
a[] = [ 2.1 3.14 3 ]
#
func f . .
  # i is local, because it is first used in the function
  for i range len a[]
    print a[i]
  .
.
call f
#
# string
domain$ = "easylang.online"
print domain$
#
# array of strings
fruits$[] = [ "apple" "banana" "orange" ]
print fruits$[]


 a={3,4,5}:b={4,3,5}:c={-5,-12,-13}

print "A.B = "+dot_product(ref(a),ref(b))
call cross_product(ref(a),ref(b),ref(y))
Print "AxB = ("+y[0]+","+y[1]+","+y[2]+")"
print "A.(BxC) = "+s_tri(ref(a),ref(b),ref(c))
call v_tri(ref(a),ref(b),ref(c),ref(x),ref(y))
Print "A x (BxC) = ("+y[0]+","+y[1]+","+y[2]+")"

function dot_product(ref(x1),ref(x2))
    dot_product= 0
   for t = 0 to 2
      dot_product += x1[t]*x2[t]
   next t
end function

subroutine cross_product(ref(x1),ref(x2),ref(y1))
   y1={0,0,0}
   y1[0]=x1[1]*x2[2]-x1[2]*x2[1]
   y1[1]=x1[2]*x2[0]-x1[0]*x2[2]
   y1[2]=x1[0]*x2[1]-x1[1]*x2[0]
end subroutine

function s_tri(ref(x1),ref(x2),ref(x3))
   call cross_product(ref(x2),ref(x3),ref(y1))
   s_tri=dot_product(ref(x1),ref(y1))
end function

subroutine v_tri(ref(x1),ref(x2),ref(x3),ref(y1),ref(y2))
  call cross_product(ref(x2),ref(x3),ref(y1))
  call cross_product(ref(x1),ref(y1),ref(y2))
end subroutine


TakeList[Nest[If[MemberQ[#//Most, #//Last], Join[#, Length[#] - [email protected][#//Most, #//Last]], Append[#, 0]]&, {0}, 999], {10, -10}] // Column


MODULE VanEck;
FROM InOut IMPORT WriteCard, WriteLn;

VAR i, j: CARDINAL;
    eck: ARRAY [1..1000] OF CARDINAL;

BEGIN
    FOR i := 1 TO 1000 DO
        eck[i] := 0;
    END;
    FOR i := 1 TO 999 DO
        j := i-1;
        WHILE (j > 0) AND (eck[i] <> eck[j]) DO
            DEC(j);
        END;
        IF j <> 0 THEN
            eck[i+1] := i-j;
        END;
    END;

    FOR i := 1 TO 10 DO
        WriteCard(eck[i], 4);
    END;
    WriteLn();

    FOR i := 991 TO 1000 DO
        WriteCard(eck[i], 4);
    END;
    WriteLn();
END VanEck.


const max = 1000
var a: array[max, int]
for n in countup(0, max - 2):
  for m in countdown(n - 1, 0):
    if a[m] == a[n]:
      a[n + 1] = n - m
      break

echo "The first ten terms of the Van Eck sequence are:"
echo a[..9]
echo "\nTerms 991 to 1000 of the sequence are:"
echo a[990..^1]


class
	APPLICATION
inherit
	ARGUMENTS
create
	make

feature {NONE} -- Initialization

	make
			-- Run application.
		local
			i: INTEGER
			s: STRING
		do
			i := 100
			s := "Some string"
			create a.make_empty
		end

feature {NONE} -- Class Features

a: ARRAY[INTEGER]


import system'collections;

public program()
{
   var c := nil;                  // declaring variable.
   var a := 3;                    // declaring and initializing variables
   var b := "my string".Length;
   long l := 200l;                // declaring strongly typed variable
   auto lst := new List<int>();

   c := b + a;                    // assigning variable
}


Dot     ← +´∘×
Cross   ← 1⊸⌽⊸×{1⌽𝔽˜-𝔽}
Triple  ← {𝕊a‿b‿c: a Dot b Cross c}
VTriple ← Cross´

a←3‿4‿5
b←4‿3‿5
c←¯5‿¯12‿¯13


#include<stdio.h>

typedef struct{
	float i,j,k;
	}Vector;

Vector a = {3, 4, 5},b = {4, 3, 5},c = {-5, -12, -13};

float dotProduct(Vector a, Vector b)
{
	return a.i*b.i+a.j*b.j+a.k*b.k;
}

Vector crossProduct(Vector a,Vector b)
{
	Vector c = {a.j*b.k - a.k*b.j, a.k*b.i - a.i*b.k, a.i*b.j - a.j*b.i};

	return c;
}

float scalarTripleProduct(Vector a,Vector b,Vector c)
{
	return dotProduct(a,crossProduct(b,c));
}

Vector vectorTripleProduct(Vector a,Vector b,Vector c)
{
	return crossProduct(a,crossProduct(b,c));
}

void printVector(Vector a)
{
	printf("( %f, %f, %f)",a.i,a.j,a.k);
}

int main()
{
	printf("\n a = "); printVector(a);
	printf("\n b = "); printVector(b);
	printf("\n c = "); printVector(c);
	printf("\n a . b = %f",dotProduct(a,b));
	printf("\n a x b = "); printVector(crossProduct(a,b));
	printf("\n a . (b x c) = %f",scalarTripleProduct(a,b,c));
	printf("\n a x (b x c) = "); printVector(vectorTripleProduct(a,b,c));

	return 0;
}


program VanEck;
{
* A:  The first term is zero.
    Repeatedly apply:
        If the last term is *new* to the sequence so far then:
B:          The next term is zero.
        Otherwise:
C:          The next term is how far back this last term occured previousely.}
uses
  sysutils;
const
  MAXNUM = 32381775;//1000*1000*1000;
  MAXSEENIDX = (1 shl 7)-1;
var
  PosBefore : array of UInt32;
  LastSeen  : array[0..MAXSEENIDX]of UInt32;// circular buffer
  SeenIdx,HaveSeen : Uint32;

procedure OutSeen(Cnt:NativeInt);
var
  I,S_Idx : NativeInt;
Begin
  IF Cnt > MAXSEENIDX then
    Cnt := MAXSEENIDX;
  If  Cnt > HaveSeen  then
    Cnt := HaveSeen;
  S_Idx := SeenIdx;
  S_Idx := (S_Idx-Cnt);
  IF S_Idx < 0 then
    inc(S_Idx,MAXSEENIDX);
  For i := 1 to Cnt do
  Begin
    write(' ',LastSeen[S_Idx]);
    S_Idx:= (S_Idx+1) AND MAXSEENIDX;
  end;
  writeln;
end;

procedure Test(MaxTestCnt: Uint32);
var
  i, actnum, Posi, S_Idx: Uint32;
  {$IFDEF FPC}
  pPosBef, pSeen: pUint32;
  {$ELSE}
  pPosBef, pSeen: array of UInt32;
  {$ENDIF}
begin
  HaveSeen := 0;
  if MaxTestCnt > MAXNUM then
    EXIT;

  Fillchar(LastSeen, SizeOf(LastSeen), #0);
  //setlength and clear
  setlength(PosBefore, 0);
  setlength(PosBefore, MaxTestCnt);

 {$IFDEF FPC}
  pPosBef := @PosBefore[0];
  pSeen := @LastSeen[0];
 {$ELSE}
  SetLength(pSeen, SizeOf(LastSeen));
  setlength(pPosBef, MaxTestCnt);
  move(PosBefore[0], pPosBef[0], length(pPosBef));
  move(LastSeen[0], pSeen[0], length(pSeen));
 {$ENDIF}

  S_Idx := 0;
  i := 1;
  actnum := 0;
  repeat
    // save value
    pSeen[S_Idx] := actnum;
    S_Idx := (S_Idx + 1) and MAXSEENIDX;
    //examine new value often out of cache
    Posi := pPosBef[actnum];
    pPosBef[actnum] := i;
//  if Posi=0 ? actnum = 0:actnum = i-Posi
    if Posi = 0 then
      actnum := 0
    else
      actnum := i - Posi;
    inc(i);
  until i > MaxTestCnt;
  HaveSeen := i - 1;
  SeenIdx := S_Idx;

  {$IFNDEF FPC}

  move(pPosBef[0], PosBefore[0], length(pPosBef));
  move(pSeen[0], LastSeen[0], length(pSeen));
  {$ENDIF}
end;

Begin
  Test(10)  ; OutSeen(10000);
  Test(1000); OutSeen(10);
  Test(MAXNUM); OutSeen(28);
  setlength(PosBefore,0);
end.


two() ->
	A_variable = 1,
	A_variable + 1.


let x = 5                              // Int
let mutable y = "mutable"              // Mutable string
let recordType = { foo : 6;  bar : 6 } // Record
let intWidget = new Widget<int>()      // Generic class
let add2 x = 2 + x                     // Function value


SYMBOL: foo

: use-foo ( -- )
    1 foo set
    foo get 2 + foo set ! foo now = 3
    foo get number>string print ;

:: named-param-example ( a b -- )
    a b + number>string print ;

: local-example ( -- str ) [let "a" :> b "c" :> a a " " b 3append ] ;


using System;
using System.Windows.Media.Media3D;

class VectorProducts
{
    static double ScalarTripleProduct(Vector3D a, Vector3D b, Vector3D c)
    {
        return Vector3D.DotProduct(a, Vector3D.CrossProduct(b, c));
    }

    static Vector3D VectorTripleProduct(Vector3D a, Vector3D b, Vector3D c)
    {
        return Vector3D.CrossProduct(a, Vector3D.CrossProduct(b, c));
    }

    static void Main()
    {
        var a = new Vector3D(3, 4, 5);
        var b = new Vector3D(4, 3, 5);
        var c = new Vector3D(-5, -12, -13);

        Console.WriteLine(Vector3D.DotProduct(a, b));
        Console.WriteLine(Vector3D.CrossProduct(a, b));
        Console.WriteLine(ScalarTripleProduct(a, b, c));
        Console.WriteLine(VectorTripleProduct(a, b, c));
    }
}


#include <iostream>

template< class T >
class D3Vector {

template< class U >
friend std::ostream & operator<<( std::ostream & , const D3Vector<U> & ) ;

public :
   D3Vector( T a , T b , T c ) {
      x = a ;
      y = b ;
      z = c ;
   }

   T dotproduct ( const D3Vector & rhs ) {
      T scalar = x * rhs.x + y * rhs.y + z * rhs.z ;
      return scalar ;
   }

   D3Vector crossproduct ( const D3Vector & rhs ) {
      T a = y * rhs.z - z * rhs.y ;
      T b = z * rhs.x - x * rhs.z ;
      T c = x * rhs.y - y * rhs.x ;
      D3Vector product( a , b , c ) ;
      return product ;
   }

   D3Vector triplevec( D3Vector & a , D3Vector & b ) {
      return crossproduct ( a.crossproduct( b ) ) ;
   }

   T triplescal( D3Vector & a, D3Vector & b ) {
      return dotproduct( a.crossproduct( b ) ) ;
   }

private :
   T x , y , z ;
} ;

template< class T >
std::ostream & operator<< ( std::ostream & os , const D3Vector<T> & vec ) {
   os << "( "  << vec.x << " ,  " << vec.y << " ,  " << vec.z << " )" ;
   return os ;
}

int main( ) {
   D3Vector<int> a( 3 , 4 , 5 ) , b ( 4 , 3 , 5 ) , c( -5 , -12 , -13 ) ;
   std::cout << "a . b : " << a.dotproduct( b ) << "\n" ;
   std::cout << "a x b : " << a.crossproduct( b ) << "\n" ;
   std::cout << "a . b x c : " << a.triplescal( b , c ) << "\n" ;
   std::cout << "a x b x c : " << a.triplevec( b , c ) << "\n" ;
   return 0 ;
}


constant lim = 1000
sequence van_eck = repeat(0,lim),
         pos_before = repeat(0,lim)
for n=1 to lim-1 do
    integer vn = van_eck[n]+1,
            prev = pos_before[vn]
    if prev!=0 then
        van_eck[n+1] = n - prev
    end if
    pos_before[vn] = n
end for
printf(1,"The first ten terms of the Van Eck sequence are:%v\n",{van_eck[1..10]})
printf(1,"Terms 991 to 1000 of the sequence are:%V\n",{van_eck[991..1000]})


/* partially created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */

/* global and local scrope
   from the Falcon survival
   guide book */
// global scope
sqr = 1.41

function square( x )
	// local scope
   sqr = x * x
   return sqr
end

number = square( 8 ) * sqr

a = [1, 2, 3] 	// array
b = 1			// variable declaration
e = 1.0  		// float
f = "string"	// string

/* There are plenty more
data types in Falcon */


: hypot ( a b -- a^2 + b^2 )
  LOCALS| b a |            \ note: reverse order from the conventional stack comment
  b b * a a * + ;


 program test
 implicit none

 integer :: i  !scalar integer
 integer,dimension(10) :: ivec !integer vector
 real :: r !scalar real
 real,dimension(10) :: rvec !real vector
 character(len=:),allocatable :: char1, char2  !fortran 2003 allocatable strings

!assignments:

!-- scalars:
 i = 1
 r = 3.14

!-- vectors:
 ivec = 1 !(all elements set to 1)
 ivec(1:5) = 2

 rvec(1:9) = 0.0
 rvec(10) = 1.0

!-- strings:
 char1 = 'hello world!'
 char2 = char1   !copy from one string to another
 char2(1:1) = 'H'  !change first character

end program test


shared void run() {

	alias Vector => Float[3];

	function dot(Vector a, Vector b) =>
			a[0] * b[0] + a[1] * b[1] + a[2] * b[2];

	function cross(Vector a, Vector b) => [
		a[1] * b[2] - a[2] * b[1],
		a[2] * b[0] - a[0] * b[2],
		a[0] * b[1] - a[1] * b[0]
	];

	function scalarTriple(Vector a, Vector b, Vector c) =>
			dot(a, cross(b, c));

	function vectorTriple(Vector a, Vector b, Vector c) =>
			cross(a, cross(b, c));

	value a = [ 3.0,    4.0,    5.0 ];
	value b = [ 4.0,    3.0,    5.0 ];
	value c = [-5.0,  -12.0,  -13.0 ];

	print("``a`` . ``b`` = ``dot(a, b)``");
	print("``a`` X ``b`` = ``cross(a, b)``");
	print("``a`` . ``b`` X ``c`` = ``scalarTriple(a, b, c)``");
	print("``a`` X ``b`` X ``c`` = ``vectorTriple(a, b, c)``");
}


(defrecord Vector [x y z])

(defn dot
  [U V]
  (+ (* (:x U) (:x V))
     (* (:y U) (:y V))
     (* (:z U) (:z V))))

(defn cross
  [U V]
  (new Vector
       (- (* (:y U) (:z V)) (* (:z U) (:y V)))
       (- (* (:z U) (:x V)) (* (:x U) (:z V)))
       (- (* (:x U) (:y V)) (* (:y U) (:x V)))))

(let [a (new Vector 3 4 5)
      b (new Vector 4 3 5)
      c (new Vector -5 -12 -13)]
  (doseq
    [prod (list
            (dot a b)
            (cross a b)
            (dot a (cross b c))
            (cross a (cross b c)))]
    (println prod)))


main =>
  Limit = 1000,
  A = new_array(Limit+1),
  bind_vars(A,0),
  foreach(N in 1..Limit-1)
    M = find_last_of(A[1..N],A[N+1]),
    if M > 0 then
       A[N+2] := N-M+1
    end
  end,
  println(A[1..10]),
  println(A[991..1000]),
  nl.


100H:
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;

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

PRINT$SLICE: PROCEDURE (LIST, N);
    DECLARE (I, N, LIST, L BASED LIST) ADDRESS;
    DO I=0 TO N-1;
        CALL PRINT$NUMBER(L(I));
    END;
    CALL PRINT(.(13,10,'$'));
END PRINT$SLICE;

DECLARE ECK (1000) ADDRESS;
DECLARE (I, J) ADDRESS;

ECK(0) = 0;
DO I=0 TO LAST(ECK)-1;
    J = I - 1;
    DO WHILE J <> 0FFFFH; /* WHAT IS SIGNED MATH */
        IF ECK(I) = ECK(J) THEN DO;
            ECK(I+1) = I-J;
            GO TO NEXT;
        END;
        J = J - 1;
    END;
    ECK(I+1) = 0;
NEXT:
END;

CALL PRINT$SLICE(.ECK(0), 10);
CALL PRINT$SLICE(.ECK(990), 10);
CALL EXIT;
EOF


van_eck_init(v(0, 0, _assoc)):-
    empty_assoc(_assoc).

van_eck_next(v(Index, Last_term, Last_pos), v(Index1, Next_term, Last_pos1)):-
    (get_assoc(Last_term, Last_pos, V) ->
        Next_term is Index - V
        ;
        Next_term = 0
    ),
    Index1 is Index + 1,
    put_assoc(Last_term, Last_pos, Index, Last_pos1).

van_eck_sequence(N, Seq):-
    van_eck_init(V),
    van_eck_sequence(N, V, Seq).

van_eck_sequence(0, _, []):-!.
van_eck_sequence(N, V, [Term|Rest]):-
    V = v(_, Term, _),
    van_eck_next(V, V1),
    N1 is N - 1,
    van_eck_sequence(N1, V1, Rest).

write_list(From, To, _, _):-
    To < From,
    !.
write_list(_, _, _, []):-!.
write_list(From, To, N, [_|Rest]):-
    From > N,
    !,
    N1 is N + 1,
    write_list(From, To, N1, Rest).
write_list(From, To, N, [E|Rest]):-
    writef('%t ', [E]),
    F1 is From + 1,
    N1 is N + 1,
    write_list(F1, To, N1, Rest).

write_list(From, To, List):-
    write_list(From, To, 1, List),
    nl.

main:-
    van_eck_sequence(1000, Seq),
    writeln('First 10 terms of the Van Eck sequence:'),
    write_list(1, 10, Seq),
    writeln('Terms 991 to 1000 of the Van Eck sequence:'),
    write_list(991, 1000, Seq).


Dim [Shared] As DataType vble1 [, vble2, ...]


# At top level, global variables are declared when they are assigned, so one only writes
global_var := 1;

# In a function, local variables are declared like this
func := function(n)
    local a;
    a := n*n;
    return n + a;
end;

# One can test whether a variable is assigned
IsBound(global_var);
# true;

# And destroy a variable
Unbind(global_var);

# This works with list elements too
u := [11, 12, , 14];
IsBound(u[4]);
# true
IsBound(u[3]);
# false
Unbind(u[4]);


if var.end=0 then // Without the code being in this if statement, the code would keep executing until it were to stop.
var.end=1
// These variables, respectively, refer to an integer, a boolean, and a string.
var.variable1=3
var.variable2=True
var.variable3="Hi!"
// var.example1 now refers to a string object instead.
var.variable1="Bye!"
endif


vector = cluster [T: type] is make, dot_product, cross_product,
                              equal, power, mul, unparse
         where T has add: proctype (T,T) returns (T) signals (overflow),
                     sub: proctype (T,T) returns (T) signals (overflow),
                     mul: proctype (T,T) returns (T) signals (overflow),
                     equal: proctype (T,T) returns (bool),
                     unparse: proctype (T) returns (string)

    rep = struct[x, y, z: T]

    make = proc (x, y, z: T) returns (cvt)
        return(rep${x:x, y:y, z:z})
    end make

    dot_product = proc (a, b: cvt) returns (T) signals (overflow)
        return (a.x*b.x + a.y*b.y + a.z*b.z) resignal overflow
    end dot_product

    cross_product = proc (a, b: cvt) returns (cvt) signals (overflow)
        begin
            x: T := a.y * b.z - a.z * b.y
            y: T := a.z * b.x - a.x * b.z
            z: T := a.x * b.y - a.y * b.x
            return(down(make(x,y,z)))
        end resignal overflow
    end cross_product

    equal = proc (a, b: cvt) returns (bool)
        return (a.x = b.x & a.y = b.y & a.z = b.z)
    end equal

    % Allow cross_product to be written as ** and dot_product to be written as *
    power = proc (a, b: cvt) returns (cvt) signals (overflow)
        return(down(cross_product(up(a),up(b)))) resignal overflow
    end power

    mul = proc (a, b: cvt) returns (T) signals (overflow)
        return(dot_product(up(a),up(b))) resignal overflow
    end mul

    % Standard to_string routine. Properly, `parse' should also be defined,
    % and x = parse(unparse(x)) forall x; but I'm not bothering here.
    unparse = proc (v: cvt) returns (string)
        return( "(" || T$unparse(v.x)
            || ", " || T$unparse(v.y)
            || ", " || T$unparse(v.z) || ")" )
    end unparse
end vector

start_up = proc ()
    vi = vector[int] % integer math is good enough for the examples

    po: stream := stream$primary_output()

    a, b, c: vi
    a := vi$make(3, 4, 5)
    b := vi$make(4, 3, 5)
    c := vi$make(-5, -12, -13)

    stream$putl(po, "          a = " || vi$unparse(a))
    stream$putl(po, "          b = " || vi$unparse(b))
    stream$putl(po, "          c = " || vi$unparse(c))
    stream$putl(po, "      a . b = " || int$unparse(a * b))
    stream$putl(po, "      a x b = " || vi$unparse(a ** b))
    stream$putl(po, "a . (b x c) = " || int$unparse(a * b ** c))
    stream$putl(po, "a x (b x c) = " || vi$unparse(a ** b ** c))
end start_up


(defclass 3d-vector ()
  ((x :type number :initarg :x)
   (y :type number :initarg :y)
   (z :type number :initarg :z)))

(defmethod print-object ((object 3d-vector) stream)
  (print-unreadable-object (object stream :type t)
    (with-slots (x y z) object
      (format stream "~a ~a ~a" x y z))))

(defun make-3d-vector (x y z)
  (make-instance '3d-vector :x x :y y :z z))

(defmethod dot-product ((a 3d-vector) (b 3d-vector))
  (with-slots ((a1 x) (a2 y) (a3 z)) a
    (with-slots ((b1 x) (b2 y) (b3 z)) b
      (+ (* a1 b1) (* a2 b2) (* a3 b3)))))

(defmethod cross-product ((a 3d-vector)
                                 (b 3d-vector))
  (with-slots ((a1 x) (a2 y) (a3 z)) a
    (with-slots ((b1 x) (b2 y) (b3 z)) b
      (make-instance '3d-vector
                     :x (- (* a2 b3) (* a3 b2))
                     :y (- (* a3 b1) (* a1 b3))
                     :z (- (* a1 b2) (* a2 b1))))))

(defmethod scalar-triple-product ((a 3d-vector)
                                  (b 3d-vector)
                                  (c 3d-vector))
  (dot-product a (cross-product b c)))

(defmethod vector-triple-product ((a 3d-vector)
                                  (b 3d-vector)
                                  (c 3d-vector))
  (cross-product a (cross-product b c)))

(defun vector-products-example ()
  (let ((a (make-3d-vector 3 4 5))
        (b (make-3d-vector 4 3 5))
        (c (make-3d-vector -5 -12 -13)))
    (values (dot-product a b)
            (cross-product a b)
            (scalar-triple-product a b c)
            (vector-triple-product a b c))))


def van_eck():
    n, seen, val = 0, {}, 0
    while True:
        yield val
        last = {val: n}
        val = n - seen.get(val, n)
        seen.update(last)
        n += 1
#%%
if __name__ == '__main__':
    print("Van Eck: first 10 terms:  ", list(islice(van_eck(), 10)))
    print("Van Eck: terms 991 - 1000:", list(islice(van_eck(), 1000))[-10:])


  [ ' [ 0 ]
    swap 1 - times
      [ dup behead swap find
        1+ 2dup swap found *
        swap join ]
    reverse ]                is van-eck ( n --> [ )

    10 van-eck echo cr
  1000 van-eck -10 split echo drop


#lang racket
(require racket/stream)

(define (van-eck)
  (define (next val n seen)
    (define val1 (- n (hash-ref seen val n)))
    (stream-cons val (next val1 (+ n 1) (hash-set seen val n))))
  (next 0 0 (hash)))

(define (get m n s)
  (stream->list
   (stream-take (stream-tail s m)
                (- n m))))

"First 10 terms:"          (get 0     10 (van-eck))
"Terms 991 to 1000 terms:" (get 990 1000 (van-eck)) ; counting from 0


foobar = 15

f x = x + foobar
  where foobar = 15

f x = let foobar = 15
      in  x + foobar

f x = do
    let foobar = 15
    return $ x + foobar


! Strings and arrays must be declared.
! Everything else is 8-byte float, READ/WRITE converts
  CHARACTER str="abcdef", str2*345, str3*1E6/"xyz"/
  REAL, PARAMETER :: named_constant = 3.1415
  REAL :: n=2, cols=4, vec(cols), mtx(n, cols)
  DATA vec/2,3,4,5/, mtx/1,2,3.1415,4,  5,6,7,8/

  named = ALIAS(alpha, beta, gamma) ! gamma == named(3)
  ALIAS(vec,n, subvec,2) ! share subvec and vec(n...n+1)
  ALIAS(str,3, substr,n) ! share substr and str(3:3+n-1)

  a = EXP(b + c)     ! assign/initialze a=1, b=0, c=0
  str = "blahblah"   ! truncate/expand if needed
  beta = "blahblah"  ! illegal

  CALL noArguments_noUSE   ! global scope SUBROUTINE
  CALL Arguments_or_USE(a) ! local scope SUBROUTINE
  t = func()               ! local scope FUNCTION

SUBROUTINE noArguments_noUSE() ! all global
  vec2 = $ ! 1,2,3,...
END

SUBROUTINE Arguments_or_USE(var) ! all local
  USE : vec                      ! use global object
  var = SUM(vec)
  t = TIME()         ! local, static, USEd by func()
END

FUNCTION func()                  ! all local
  USE Arguments_or_USE : t       ! use local object
  func = t
END


include "cowgol.coh";

record Vector is
    x: int32;   # Cowgol does not have floating point types,
    y: int32;   # but for the examples it does not matter.
    z: int32;
end record;

sub print_signed(n: int32) is
    if n < 0 then
        print_char('-');
        n := -n;
    end if;
    print_i32(n as uint32);
end sub;

sub print_vector(v: [Vector]) is
    print_char('(');
    print_signed(v.x);
    print(", ");
    print_signed(v.y);
    print(", ");
    print_signed(v.z);
    print_char(')');
    print_nl();
end sub;

sub dot(a: [Vector], b: [Vector]): (r: int32) is
    r := a.x * b.x + a.y * b.y + a.z * b.z;
end sub;

# Unfortunately it is impossible to return a complex type
# from a function. We have to have the caller pass in a pointer
# and have this function set its fields.
sub cross(a: [Vector], b: [Vector], r: [Vector]) is
    r.x := a.y * b.z - a.z * b.y;
    r.y := a.z * b.x - a.x * b.z;
    r.z := a.x * b.y - a.y * b.x;
end sub;

sub scalarTriple(a: [Vector], b: [Vector], c: [Vector]): (r: int32) is
    var v: Vector;
    cross(b, c, &v);
    r := dot(a, &v);
end sub;

sub vectorTriple(a: [Vector], b: [Vector], c: [Vector], r: [Vector]) is
    var v: Vector;
    cross(b, c, &v);
    cross(a, &v, r);
end sub;

var a: Vector := {3, 4, 5};
var b: Vector := {4, 3, 5};
var c: Vector := {-5, -12, -13};
var scratch: Vector;

print("        a = "); print_vector(&a);
print("        b = "); print_vector(&b);
print("        c = "); print_vector(&c);
print("    a . b = "); print_signed(dot(&a, &b)); print_nl();
print("    a x b = "); cross(&a, &b, &scratch); print_vector(&scratch);
print("a . b x c = "); print_signed(scalarTriple(&a, &b, &c)); print_nl();
print("a x b x c = "); vectorTriple(&a, &b, &c, &scratch);
                       print_vector(&scratch);


class Vector
  property x, y, z

  def initialize(@x : Int64, @y : Int64, @z : Int64) end

  def dot_product(other : Vector)
    (self.x * other.x) + (self.y * other.y) + (self.z * other.z)
  end

  def cross_product(other : Vector)
    Vector.new(self.y * other.z - self.z * other.y,
               self.z * other.x - self.x * other.z,
               self.x * other.y - self.y * other.x)
  end

  def scalar_triple_product(b : Vector, c : Vector)
    self.dot_product(b.cross_product(c))
  end

  def vector_triple_product(b : Vector, c : Vector)
    self.cross_product(b.cross_product(c))
  end

  def to_s
    "(#{self.x}, #{self.y}, #{self.z})\n"
  end
end

a = Vector.new(3, 4, 5)
b = Vector.new(4, 3, 5)
c = Vector.new(-5, -12, -13)

puts "a = #{a.to_s}"
puts "b = #{b.to_s}"
puts "c = #{c.to_s}"
puts "a dot b = #{a.dot_product b}"
puts "a cross b = #{a.cross_product(b).to_s}"
puts "a dot (b cross c) = #{a.scalar_triple_product b, c}"
puts "a cross (b cross c) = #{a.vector_triple_product(b, c).to_s}"


sub n-van-ecks ($init) {
    $init, -> $i, {
        state %v;
        state $k;
        $k++;
        my $t  = %v{$i}.defined ?? $k - %v{$i} !! 0;
        %v{$i} = $k;
        $t
    } ... *
}

for <
    A181391 0
    A171911 1
    A171912 2
    A171913 3
    A171914 4
    A171915 5
    A171916 6
    A171917 7
    A171918 8
> -> $seq, $start {

    my @seq = n-van-ecks($start);

    # The task
    put qq:to/END/

    Van Eck sequence OEIS:$seq; with the first term: $start
            First 10 terms: {@seq[^10]}
    Terms 991 through 1000: {@seq[990..999]}
    END
}


/*REXX pgm generates/displays the   'start ──► end'    elements of the Van Eck sequence.*/
parse arg LO HI $ .                              /*obtain optional arguments from the CL*/
if LO=='' | LO==","  then LO=   1                /*Not specified?  Then use the default.*/
if HI=='' | HI==","  then HI=  10                /* "      "         "   "   "     "    */
if  $=='' |  $==","  then  $=   0                /* "      "         "   "   "     "    */
$$=;               z= $                          /*$$: old seq:  $: initial value of seq*/
     do HI-1;      z= wordpos( reverse(z), reverse($$) );          $$= $;          $= $ z
     end   /*HI-1*/                              /*REVERSE allows backwards search in $.*/
                                                 /*stick a fork in it,  we're all done. */
say 'terms '  LO  " through "  HI  ' of the Van Eck sequence are: '  subword($,LO,HI-LO+1)


import std.stdio, std.conv, std.numeric;

struct V3 {
    union {
        immutable struct { double x, y, z; }
        immutable double[3] v;
    }

    double dot(in V3 rhs) const pure nothrow /*@safe*/ @nogc {
        return dotProduct(v, rhs.v);
    }

    V3 cross(in V3 rhs) const pure nothrow @safe @nogc {
        return V3(y * rhs.z - z * rhs.y,
                  z * rhs.x - x * rhs.z,
                  x * rhs.y - y * rhs.x);
    }

    string toString() const { return v.text; }
}

double scalarTriple(in V3 a, in V3 b, in V3 c) /*@safe*/ pure nothrow {
    return a.dot(b.cross(c));
    // function vector_products.V3.cross (const(V3) rhs) immutable
    // is not callable using argument types (const(V3)) const
}

V3 vectorTriple(in V3 a, in V3 b, in V3 c) @safe pure nothrow @nogc {
    return a.cross(b.cross(c));
}

void main() {
    immutable V3 a = {3, 4, 5},
                 b = {4, 3, 5},
                 c = {-5, -12, -13};

    writeln("a = ", a);
    writeln("b = ", b);
    writeln("c = ", c);
    writeln("a . b = ", a.dot(b));
    writeln("a x b = ", a.cross(b));
    writeln("a . (b x c) = ", scalarTriple(a, b, c));
    writeln("a x (b x c) = ", vectorTriple(a, b, c));
}


van_eck = Enumerator.new do |y|
  ar = [0]
  loop do
    y << (term = ar.last)  # yield
    ar << (ar.count(term)==1 ? 0 : ar.size - 1 - ar[0..-2].rindex(term))
  end
end

ve = van_eck.take(1000)
p ve.first(10), ve.last(10)


fn van_eck_sequence() -> impl std::iter::Iterator<Item = i32> {
    let mut index = 0;
    let mut last_term = 0;
    let mut last_pos = std::collections::HashMap::new();
    std::iter::from_fn(move || {
        let result = last_term;
        let mut next_term = 0;
        if let Some(v) = last_pos.get_mut(&last_term) {
            next_term = index - *v;
            *v = index;
        } else {
            last_pos.insert(last_term, index);
        }
        last_term = next_term;
        index += 1;
        Some(result)
    })
}

fn main() {
    let mut v = van_eck_sequence().take(1000);
    println!("First 10 terms of the Van Eck sequence:");
    for n in v.by_ref().take(10) {
        print!("{} ", n);
    }
    println!("\nTerms 991 to 1000 of the Van Eck sequence:");
    for n in v.skip(980) {
        print!("{} ", n);
    }
    println!();
}


object VanEck extends App {

  def vanEck(n: Int): List[Int] = {

    def vanEck(values: List[Int]): List[Int] =
      if (values.size < n)
        vanEck(math.max(0, values.indexOf(values.head, 1)) :: values)
      else
        values

    vanEck(List(0)).reverse
  }

  val vanEck1000 = vanEck(1000)
  println(s"The first 10 terms are ${vanEck1000.take(10)}.")
  println(s"Terms 991 to 1000 are ${vanEck1000.drop(990)}.")
}


global gvar          # a global

procedure main(arglist)         # arglist is a parameter of main
local a,b,i,x                   # a, b, i, x are locals withing main
static y                        # a static (silly in main)

x := arglist[1]
a := 1.0
i := 10
b := [x,a,i,b]

# ... rest of program
end


(lib 'math)

(define (scalar-triple-product a b c)
  (dot-product a (cross-product b c)))

(define (vector-triple-product a b c)
  (cross-product a (cross-product b c)))

(define a #(3 4 5))
(define b #(4 3 5))
(define c #(-5 -12 -13))

(cross-product a b)
    → #( 5 5 -7)
(dot-product a b)
    → 49
(scalar-triple-product a b c)
    → 6
(vector-triple-product a b c)
    → #( -267 204 -3)


        define('eck(n)i,j')                     :(eck_end)
eck     eck = array(n,0)
        i = 0
eouter  i = lt(i,n - 1) i + 1                   :f(return)
        j = i
einner  j = gt(j,0) j - 1                       :f(eouter)
        eck<i + 1> = eq(eck<i>,eck<j>) i - j    :s(eouter)f(einner)
eck_end

        define('list(arr,start,stop)')          :(list_end)
list    list = list arr<start> ' '
        start = lt(start,stop) start + 1        :s(list)f(return)
list_end

        ecks = eck(1000)
        output = list(ecks, 1, 10)
        output = list(ecks, 991, 1000)
end


func van_eck(n) {

    var seen = Hash()
    var seq  = [0]
    var prev = seq[-1]

    for k in (1 ..^ n) {
        seq << (seen.has(prev) ? (k - seen{prev}) : 0)
        seen{prev} = k
        prev = seq[-1]
    }

    seq
}

say van_eck(10)
say van_eck(1000).slice(991-1, 1000-1)


struct VanEckSequence: Sequence, IteratorProtocol {
    private var index = 0
    private var lastTerm = 0
    private var lastPos = Dictionary<Int, Int>()

    mutating func next() -> Int? {
        let result = lastTerm
        var nextTerm = 0
        if let v = lastPos[lastTerm] {
            nextTerm = index - v
        }
        lastPos[lastTerm] = index
        lastTerm = nextTerm
        index += 1
        return result
    }
}

let seq = VanEckSequence().prefix(1000)

print("First 10 terms of the Van Eck sequence:")
for n in seq.prefix(10) {
    print(n, terminator: " ")
}
print("\nTerms 991 to 1000 of the Van Eck sequence:")
for n in seq.dropFirst(990) {
    print(n, terminator: " ")
}
print()


## Mathematically, the first term has index "0", not "1".  We do that, also.

set ::vE 0

proc vanEck {n} {
    global vE vEocc
    while {$n >= [set k [expr {[llength $vE] - 1}]]} {
        set kv [lindex $vE $k]
        ## value $kv @ $k is not yet stuffed into vEocc()
        lappend vE [expr {[info exists vEocc($kv)] ? $k - $vEocc($kv) : 0}]
        set vEocc($kv) $k
    }
    return [lindex $vE $n]
}

proc show {func from to} {
    for {set n $from} {$n <= $to} {incr n} {
        append r " " [$func $n]
    }
    puts "${func}($from..$to) =$r"
}

show vanEck 0 9
show vanEck 990 999


#declaration/assignment, declaration is optional
x::Int32 = 1
#datatypes are inferred dynamically, but can also be set thru convert functions and datatype literals
x = 1 #x is inferred as Int, which is Int32 for 32-bit machines, Int64 for 64-bit machines
#variable reference
julia>x
1

x = int8(1) #x is of type Int8
x = 1.0 #x is Float64
x = y = 1 #assign both x and y to 1
global x = 1 #assigns 1 to global variable x (used inside scope blocks)
local x = 1 #assigns 1 to local variable x (used inside scope blocks)
x = 'a' #x is a 'Char' type, designated by single quotes
x = "a" #x is a 1-element string, designated by double quotes


defmodule Vector do
  def dot_product({a1,a2,a3}, {b1,b2,b3}), do: a1*b1 + a2*b2 + a3*b3

  def cross_product({a1,a2,a3}, {b1,b2,b3}), do: {a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1}

  def scalar_triple_product(a, b, c), do: dot_product(a, cross_product(b, c))

  def vector_triple_product(a, b, c), do: cross_product(a, cross_product(b, c))
end

a = {3, 4, 5}
b = {4, 3, 5}
c = {-5, -12, -13}

IO.puts "a = #{inspect a}"
IO.puts "b = #{inspect b}"
IO.puts "c = #{inspect c}"
IO.puts "a . b = #{inspect Vector.dot_product(a, b)}"
IO.puts "a x b = #{inspect Vector.cross_product(a, b)}"
IO.puts "a . (b x c) = #{inspect Vector.scalar_triple_product(a, b, c)}"
IO.puts "a x (b x c) = #{inspect Vector.vector_triple_product(a, b, c)}"


-module(vector).
-export([main/0]).
vector_product(X,Y)->
[X1,X2,X3]=X,
[Y1,Y2,Y3]=Y,
Ans=[X2*Y3-X3*Y2,X3*Y1-X1*Y3,X1*Y2-X2*Y1],
Ans.
dot_product(X,Y)->
[X1,X2,X3]=X,
[Y1,Y2,Y3]=Y,
Ans=X1*Y1+X2*Y2+X3*Y3,
io:fwrite("~p~n",[Ans]).
main()->
{ok, A} = io:fread("Enter vector A : ", "~d ~d ~d"),
{ok, B} = io:fread("Enter vector B : ", "~d ~d ~d"),
{ok, C} = io:fread("Enter vector C : ", "~d ~d ~d"),
dot_product(A,B),
Ans=vector_product(A,B),
io:fwrite("~p,~p,~p~n",Ans),
dot_product(C,vector_product(A,B)),
io:fwrite("~p,~p,~p~n",vector_product(C,vector_product(A,B))).


Imports System.Linq
Module Module1
    Dim h() As Integer
    Sub sho(i As Integer)
        Console.WriteLine(String.Join(" ", h.Skip(i).Take(10)))
    End Sub
    Sub Main()
        Dim a, b, c, d, f, g As Integer : g = 1000
        h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g
            f = h(b) : For d = a To 0 Step -1
                If f = h(d) Then h(c) = b - d: Exit For
            Next : a = b : b = c : Next : sho(0) : sho(990)
    End Sub
End Module


fn main() {
    max := 1000
    mut a := []int{len: max} // all zero by default
    for n in 0..max-1 {
        for m := n - 1;  m >= 0; m-- {
            if a[m] == a[n] {
                a[n+1] = n - m
                break
            }
        }
    }
    println("The first ten terms of the Van Eck sequence are:")
    println(a[..10])
    println("\nTerms 991 to 1000 of the sequence are:")
    println(a[990..])
}


var max = 1000
var a = List.filled(max, 0)
var seen = {}
for (n in 0...max-1) {
    var m = seen[a[n]]
    if (m != null) a[n+1] = n - m
    seen[a[n]] = n
}
System.print("The first ten terms of the Van Eck sequence are:")
System.print(a[0...10])
System.print("\nTerms 991 to 1000 of the sequence are:")
System.print(a[990..-1])


// version 1.0.6

fun main(args: Array<String>) {
    /* read-only variables */
    val i = 3          // type inferred to be Int
    val d = 2.4        // type inferred to be double
    val sh: Short = 2  // type specified as Short
    val ch = 'A'       // type inferred to be Char
    val bt: Byte = 1   // type specified as Byte

    /* mutable variables */
    var s = "Hey"      // type inferred to be String
    var l =  4L        // type inferred to be Long
    var b: Boolean     // type specified as Boolean, not initialized immediately
    var f =  4.4f      // type inferred to be Float

    b = true           // now initialized
    println("$i, $d, $sh, $ch, $bt, $s, $l, $b, $f")

    s = "Bye"          // OK as mutable
    l = 5L             // OK as mutable
    b = false          // OK as mutable
    f = 5.6f           // OK as mutable

    println("$i, $d, $sh, $ch, $bt, $s, $l, $b, $f")
}


1) working in a global scope

{def A 3}
-> A                                 // A   is in the global scope
{def B 4}
-> B                                 // B   is in the global scopel
{def MUL {lambda {:x :y} {* :x :y}}}
-> MUL                               // MUL is a global function
{MUL {A} {B}}                        // using global variables
-> 12

2) working in a local scope

{let                                 // open local scope
 {                                     // begin defining and assigning local variables
   {:a 3}                                // :a is local
   {:b 4}                                // :b is local
   {:mul {lambda {:x :y} {* :x :y}}}     // :mul is a local function
 }                                     // end defining and assigning local variables
   {:mul :a :b}                        // computing with local variables
}                                    // closing local scope
-> 12


PROGRAM VECTORPRODUCT

!$DOUBLE

TYPE TVECTOR=(X,Y,Z)

DIM A:TVECTOR,B:TVECTOR,C:TVECTOR

DIM AA:TVECTOR,BB:TVECTOR,CC:TVECTOR
DIM DD:TVECTOR,EE:TVECTOR,FF:TVECTOR

PROCEDURE DOTPRODUCT(DD.,EE.->DOTP)
    DOTP=DD.X*EE.X+DD.Y*EE.Y+DD.Z*EE.Z
END PROCEDURE

PROCEDURE CROSSPRODUCT(DD.,EE.->FF.)
  FF.X=DD.Y*EE.Z-DD.Z*EE.Y
  FF.Y=DD.Z*EE.X-DD.X*EE.Z
  FF.Z=DD.X*EE.Y-DD.Y*EE.X
END PROCEDURE

PROCEDURE SCALARTRIPLEPRODUCT(AA.,BB.,CC.->SCALARTP)
  CROSSPRODUCT(BB.,CC.->FF.)
  DOTPRODUCT(AA.,FF.->SCALARTP)
END PROCEDURE

PROCEDURE VECTORTRIPLEPRODUCT(AA.,BB.,CC.->FF.)
  CROSSPRODUCT(BB.,CC.->FF.)
  CROSSPRODUCT(AA.,FF.->FF.)
END PROCEDURE

PROCEDURE PRINTVECTOR(AA.)
  PRINT("(";AA.X;",";AA.Y;",";AA.Z;")")
END PROCEDURE

BEGIN
  A.X=3  A.Y=4    A.Z=5
  B.X=4  B.Y=3    B.Z=5
  C.X=-5 C.Y=-12  C.Z=-13

  PRINT("A: ";) PRINTVECTOR(A.)
  PRINT("B: ";) PRINTVECTOR(B.)
  PRINT("C: ";) PRINTVECTOR(C.)

  PRINT
  DOTPRODUCT(A.,B.->DOTP)
  PRINT("A.B    =";DOTP)

  CROSSPRODUCT(A.,B.->FF.)
  PRINT("AxB    =";) PRINTVECTOR(FF.)

  SCALARTRIPLEPRODUCT(A.,B.,C.->SCALARTP)
  PRINT("A.(BxC)=";SCALARTP)

  VECTORTRIPLEPRODUCT(A.,B.,C.->FF.)
  PRINT("Ax(BxC)=";) PRINTVECTOR(FF.)
END PROGRAM


constant X = 1, Y = 2, Z = 3

function dot_product(sequence a, sequence b)
    return a[X]*b[X] + a[Y]*b[Y] + a[Z]*b[Z]
end function

function cross_product(sequence a, sequence b)
    return { a[Y]*b[Z] - a[Z]*b[Y],
             a[Z]*b[X] - a[X]*b[Z],
             a[X]*b[Y] - a[Y]*b[X] }
end function

function scalar_triple(sequence a, sequence b, sequence c)
    return dot_product( a, cross_product( b, c ) )
end function

function vector_triple( sequence a, sequence b, sequence c)
    return cross_product( a, cross_product( b, c ) )
end function

constant a = { 3, 4, 5 }, b = { 4, 3, 5 }, c = { -5, -12, -13 }

puts(1,"a = ")
? a
puts(1,"b = ")
? b
puts(1,"c = ")
? c
puts(1,"a dot b = ")
? dot_product( a, b )
puts(1,"a x b = ")
? cross_product( a, b )
puts(1,"a dot (b x c) = ")
? scalar_triple( a, b, c )
puts(1,"a x (b x c) = ")
? vector_triple( a, b, c )


int Seq(1001), Back, N, M, Term;

func New;       \Return 'true' if last term is new to sequence
[for Back:= N-2 downto 1 do
        if Seq(Back) = Seq(N-1) then return false;
return true;
];

func VanEck;    \Return term of Van Eck sequence
[Seq(N):= if New then 0 else N-Back-1;
N:= N+1;
return Seq(N-1);
];

[N:= 1;
for M:= 1 to 1000 do
    [Term:= VanEck;
    if M<=10 or M>=991 then
        [IntOut(0, Term);
        if M=10 or M=1000 then Crlf(0) else Text(0, ", ");
        ];
    ];
]


fcn vanEck(startAt=0){	// --> iterator
   (startAt).walker(*).tweak(fcn(n,seen,rprev){
      prev,t := rprev.value, n - seen.find(prev,n);
      seen[prev] = n;
      rprev.set(t);
      t
   }.fp1(Dictionary(),Ref(startAt))).push(startAt)
}


// declare thread variable, default type null
var(x)
$x->type // null

// declare local variable, default type null
local(x)
#x->type // null

// declare thread variable, initialize with a type, in this case integer
var(x = integer)

// declare local variable, initialize with a type, in this case integer
local(x = integer)

// assign a value to the thread var x
$x = 12

// assign a value to the local var x
$x = 177

// a var always has a data type, even if not declared - then it's null
// a var can either be assigned a type using the name of the type, or a value that is by itself the type
local(y = string)
local(y = 'hello')

'\r'
// demonstrating asCopyDeep and relationship between variables:
local(original) = array('radish', 'carrot', 'cucumber', 'olive')
local(originalaswell) = #original
local(copy)     = #original->asCopyDeep
iterate(#original) => {
    loop_value->uppercase
}
#original		// modified
//array(RADISH, CARROT, CUCUMBER, OLIVE)
'\r'
#originalaswell // modified as well as it was not a deep copy
//array(RADISH, CARROT, CUCUMBER, OLIVE)
'\r'
#copy			// unmodified as it used ascopydeep
//array(RADISH, CARROT, CUCUMBER, OLIVE)


'In Liberty BASIC variables are either string or numeric.
'A variable name can start with any letter and it can contain both letters and numerals, as well as dots (for example: user.firstname).
'There is no practical limit to the length of a variable name... up to ~2M characters.
'The variable names are case sensitive.

'assignments:   -numeric variables. LB assumes integers unless assigned or calculated otherwise.
'Because of its Smalltalk heritage, LB integers are of arbitrarily long precision.
'They lose this if a calculation yields a non-integer, switching to floating point.
    i = 1
    r = 3.14

'assignments    -string variables. Any string-length, from zero to ~2M.
    t$    ="21:12:45"
    flag$ ="TRUE"

'assignments    -1D or 2D arrays
'A default array size of 10 is available. Larger arrays need pre-'DIM'ming.
    height( 3)          =1.87
    dim height( 50)
    height( 23)         =123.5
    potential( 3, 5)    =4.5
    name$( 4)           ="John"

'There are no Boolean /bit variables as such.

'Arrays in a main program are global.
'However variables used in the main program code are not visible inside functions and subroutines.
'They can be declared 'global' if such visibility is desired.
'Functions can receive variables by name or by reference.


x = 23
y = "Hello world!"
z = TRUE -- same effect as z = 1


let dot (ax, ay, az) (bx, by, bz) =
    ax * bx + ay * by + az * bz

let cross (ax, ay, az) (bx, by, bz) =
    (ay*bz - az*by, az*bx - ax*bz, ax*by - ay*bx)

let scalTrip a b c =
    dot a (cross b c)

let vecTrip a b c =
    cross a (cross b c)

[<EntryPoint>]
let main _ =
    let a = (3.0, 4.0, 5.0)
    let b = (4.0, 3.0, 5.0)
    let c = (-5.0, -12.0, -13.0)
    printfn "%A" (dot a b)
    printfn "%A" (cross a b)
    printfn "%A" (scalTrip a b c)
    printfn "%A" (vecTrip a b c)
    0 // return an integer exit code


USING: arrays io locals math prettyprint sequences ;

: dot-product ( a b -- dp ) [ * ] 2map sum ;

:: cross-product ( a b -- cp )
    a first :> a1 a second :> a2 a third :> a3
    b first :> b1 b second :> b2 b third :> b3
    a2 b3 * a3 b2 * - ! X
    a3 b1 * a1 b3 * - ! Y
    a1 b2 * a2 b1 * - ! Z
    3array ;

: scalar-triple-product ( a b c -- stp )
    cross-product dot-product ;

: vector-triple-product ( a b c -- vtp )
    cross-product cross-product ;

[let
    { 3 4 5 }      :> a
    { 4 3 5 }      :> b
    { -5 -12 -13 } :> c
    "a: " write a .
    "b: " write b .
    "c: " write c . nl
    "a . b: " write a b dot-product .
    "a x b: " write a b cross-product .
    "a . (b x c): " write a b c scalar-triple-product .
    "a x (b x c): " write a b c vector-triple-product .
]


make "g1 0
name 2 "g2    ; same as make with parameters reversed
global "g3     ; no initial value
to func :x
  make "g4 4   ; still global
  localmake "L1 6
  local ["L2 "L3]    ; local variables, collection syntax
  func2 :g4
  print :L2      ; 9,  modified by func2
  print :L3      ; L3 has no value, was not modified by func2
end
to func2 :y
  make "g3 :y
  make "L2 :L1 + 3     ; dynamic scope: can see variables of callers
  localmake "L3 5       ; locally override L3 from caller
  (print :y :L1 :L2 :L3)      ; 4 6 9 5
end
print :g4   ; 4
print :L1   ; L1 has no value
print name? "L1    ; false, L1 is not bound in the current scope


Sub Click()
'a few declarations as example
Dim s as New NotesSession ' declaring a New NotesSession actually returns the current, active NotesSession
Dim i as Integer ' i = 0
Dim s as String ' s= ""
Dim v as Variant ' v is nothing
Dim l as Long ' l = 0
Dim doc as NotesDocument 'doc is EMTPY

'...

End Sub


a = 1    -- Here we declare a numeric variable
fruit = "banana"    -- Here we declare a string datatype
needspeeling = True    -- This is a boolean
local b = 2    -- This variable declaration is prefixed with a scope modifier


-V Pow10 = (0..18).map(n -> Int64(10) ^ n)

F isOdd(n)
   R (n [&] 1) != 0

F fangs(n)
   [(Int64, Int64)] r

   V nDigits = sorted(String(n))
   I isOdd(nDigits.len)
      R r

   V fangLen = nDigits.len I/ 2
   V inf = Pow10[fangLen - 1]
   L(d) inf .< inf * 10
      I n % d != 0
         L.continue
      V q = n I/ d
      I q < d
         R r
      V dDigits = String(d)
      V qDigits = String(q)
      I qDigits.len > fangLen
         L.continue
      I qDigits.len < fangLen
         R r
      I nDigits != sorted(dDigits‘’qDigits)
         L.continue
      I dDigits.last != ‘0’ | qDigits.last != ‘0’
         r.append((d, q))

   R r

print(‘First 25 vampire numbers with their fangs:’)
V count = 0
V n = 10
V limit = 100
L count != 25
   V fangList = fangs(n)
   I !fangList.empty
      count++
      print((‘#2: #6 =’.format(count, n))‘ ’fangList.map(it -> ‘#3 x #3’.format(it[0], it[1])).join(‘ = ’))
   n++
   I n == limit
      n *= 10
      limit *= 10

print()
L(n) [16'758'243'290'880, 24'959'017'348'650, 14'593'825'548'650]
   V fangList = fangs(n)
   I fangList.empty
      print(n‘ is not vampiric.’)
   E
      print(n‘ = ’fangList.map(it -> ‘#. x #.’.format(it[0], it[1])).join(‘ = ’))


class Main
{
  Int dot_product (Int[] a, Int[] b)
  {
    a[0]*b[0] + a[1]*b[1] + a[2]*b[2]
  }

  Int[] cross_product (Int[] a, Int[] b)
  {
    [a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1]-a[1]*b[0]]
  }

  Int scalar_triple_product (Int[] a, Int[] b, Int[] c)
  {
    dot_product (a, cross_product (b, c))
  }

  Int[] vector_triple_product (Int[] a, Int[] b, Int[] c)
  {
    cross_product (a, cross_product (b, c))
  }

  Void main ()
  {
    a := [3, 4, 5]
    b := [4, 3, 5]
    c := [-5, -12, -13]

    echo ("a . b = " + dot_product (a, b))
    echo ("a x b = [" + cross_product(a, b).join (", ") + "]")
    echo ("a . (b x c) = " + scalar_triple_product (a, b, c))
    echo ("a x (b x c) = [" + vector_triple_product(a, b, c).join (", ") + "]")
  }
}


: 3f!    ( &v - ) ( f: x y z - ) dup float+ dup float+ f! f! f! ;

: Vector \ Compiletime: ( f: x y z - ) ( <name> - )
   create here [ 3 floats ] literal allot 3f! ; \ Runtime: ( - &v )

: >[email protected]    ( &v - ) ( f: - n ) postpone [email protected] ; immediate
: >[email protected]    ( &v - ) ( f: - n ) float+ [email protected] ;
: >[email protected]    ( &v - ) ( f: - n ) float+ float+ [email protected] ;
: .Vector ( &v - ) dup >[email protected] dup >[email protected] >[email protected] f. f. f. ;

: Dot*    ( &v1 &v2 - ) ( f - DotPrd )
   2dup >[email protected]  >[email protected] f*
   2dup >[email protected]  >[email protected] f* f+
        >[email protected]  >[email protected] f* f+ ;

: Cross*  ( &v1 &v2 &vResult - )
   >r 2dup >[email protected]  >[email protected] f*
      2dup >[email protected]  >[email protected] f* f-
      2dup >[email protected]  >[email protected] f*
      2dup >[email protected]  >[email protected] f* f-
      2dup >[email protected]  >[email protected] f*
           >[email protected]  >[email protected] f* f-
   r> 3f! ;

: ScalarTriple* ( &v1 &v2 &v3 - ) ( f: - ScalarTriple* )
   >r pad Cross* pad r> Dot* ;

: VectorTriple* ( &v1 &v2 &v3 &vDest - )
   >r swap [email protected] Cross* r> tuck Cross* ;

 3e   4e   5e Vector A
 4e   3e   5e Vector B
-5e -12e -13e Vector C

cr
cr .( a . b = ) A B Dot* f.
cr .( a x b = ) A B pad Cross* pad .Vector
cr .( a . [b x c] = ) A B C ScalarTriple* f.
cr .( a x [b x c] = ) A B C pad VectorTriple* pad .Vector


\\ M2000 use inference to state the type of a new variable, at run time
\\ We can use literals of a numeric type
\\ @ for Decimal
\\ # for Currency
\\ ~ for Single
\\ & for Long (32bit)
\\ % for Integer (16bit)
\\ Double and Boolean have no symboles
Module TopA {
      Module Alfa {
                  Print A=10000, Type$(A)="Double"
                  \\ A is local, we use =
                  [email protected]
                  Print A=10, Type$(A)
                  \\ Or we can state the type before
                  Def Currency K, Z=500, M
                  K=1000
                  \\ Currency Currency Currency
                  Print Type$(K), Type$(Z), Type$(M)
                  Def Double K1, K2 as Integer=10, K3=1
                  \\ double integer double
                  Print Type$(K1), Type$(K2), Type$(K3)
                  Mb=1=1
                  \\ We get a boolean
                  Print Type$(Mb)
                  Def boolean Mb1=True
                  Print Type$(Mb1)
                  \\ True and False are Double -1 and 0 not Boolean
                  Mb3=True
                  Print Type$(Mb3)="Double"
                  \\ For strings we have to use $ (like in old Basic)
                  A$="This is a String"
                  Global G1 as boolean = True
                  \\ To change a global variable we have to use <=
                  G1<=1=0
                  \\ If we do this: G1=1=0 we make a local variable, and shadow global
                  \\ In a For Object {} we can make temporary variables
                  For This {
                        Local G1=122.1212
                        Print G1, Type$(G1)="Double"
                  }
                  Print G1, Type$(G1)="Boolean"
      }
      \\ shadow A for this module only
      A=100
      \\ Now we call Alfa
      Alfa
      Print (A=100)=True
}
Global A=10000
TopA
Print A=10000
Module CheckStatic {
      \\ clear static variables and variables (for this module)
      Clear
      Module K {
            \\ if no A exist created with value [email protected]
            \\ Static variables can't be referenced
            Static [email protected]
            Print A, Type$(A)="Decimal"
            A++
      }
      For i=1 to 10 : K : Next i
      Print A=10000
}
CheckStatic
Print A=10000

\\ reference and use of stack of values
C=100&
Module ChangeC {
      \\ we leave arguments in stack of values
      Module HereChangeC (&f) {
            \\ interpreter execute a Read &f
            f++
      }
      \\ now we call HereChangeC passing current stack of values
      HereChangeC
}
\\ Calling a module done without checking for what parameters a module take
ChangeC &C
Print C, Type$(C)="Long"
[email protected]
ChangeC &K
Print K, Type$(K)="Decimal"
Module TypeRef (&x as Double) {
     Print x
     x++
}
D=100
TypeRef  &D
Try ok {
      TypeRef &K
}
If Error or Not Ok then Print Error$ ' we get wrong data type


a := 1:
print ("a is "||a);
                            "a is 1"


x=value	assign a value to the variable x
x=y=value	assign a value to both x and y
x=. or Clear[x]	remove any value assigned to x

lhs=rhs (immediate assignment)	rhs is evaluated when the assignment is made
lhs:=rhs (delayed assignment)	rhs is evaluated each time the value of lhs is requested


	a = 4; % declare variable and initialize double value,
        s = 'abc'; % string
        i8 = int8(5);	% signed byte
        u8 = uint8(5);	% unsigned byte
        i16 = int16(5);	% signed 2 byte
        u16 = uint16(5); % unsigned 2 byte integer
        i32 = int32(5);	% signed 4 byte integer
        u32 = uint32(5);% unsigned 4 byte integers
        i64 = int64(5);	% signed 8 byte integer
        u64 = uint64(5);% unsigned 8 byte integer
	f32 = float32(5); % single precision floating point number
	f64 = float64(5); % double precision floating point number , float 64 is the default data type.

	c = 4+5i; %	complex number
        colvec = [1;2;4];   % column vector
        crowvec = [1,2,4];   % row vector
        m = [1,2,3;4,5,6];  % matrix with size 2x3


SetBatchLines -1 ; used to improve performance
; (you can make it much faster by removing the informative tooltips)

;********************
; CONFIG
;********************
StartingNumber := 10
NumberLimit := 126030
CounterLimit := 25 ; calculations stop when one of these limits is reached
AdditionalNumbers := "16758243290880,24959017348650,14593825548650"
;********************

CurrentCounter := 0, CurrentNumber := StartingNumber

Loop  {
    if !Mod(A_Index,75) ; informative tooltip (every 75 calculations, to avoid slowing down)
        ToolTip, % "Checking numbers...`nNumber: " CurrentNumber
            . "/" NumberLimit "`nFound: " CurrentCounter "/" CounterLimit
    if ( CurrentCounter >= CounterLimit ) || ( CurrentNumber >= NumberLimit )
        Break
    if Mod(StrLen(CurrentNumber),2)
        CurrentNumber *= 10
    else if ( ( CurrentResult := GetFangs(CurrentNumber) ) <> "" )
        Output .= "`n" CurrentNumber ":`t" CurrentResult, CurrentCounter++
    CurrentNumber++
}
ToolTip ; hide informative tooltip

MsgBox % SubStr(Output,2) ; show output (first part)

Output := ""
Loop, Parse, AdditionalNumbers, % ","
{
    ToolTip, % "Getting fangs for " A_LoopField " ..." ; informative tooltip
    Output .= "`n" A_LoopField ":`n`t" GetFangs(A_LoopField) "`n"
}
ToolTip ; hide informative tooltip

MsgBox % SubStr(Output,2) ; show output (second part - additional numbers)
ExitApp

;----------------------------------------------------------------------------------

CharSorter(Input) { ; required by GetFangs()
    Loop, Parse, Input
        Output .= A_LoopField "`n"
    Sort, Output
    StringReplace, Output, Output, % "`n",, All
    Return Output
}

;----------------------------------------------------------------------------------

GetFangs(CurrentNumber) { ; requires CharSorter()
    ResultIndex := 1
    Length := StrLen(CurrentNumber)
    Power := (Length//2)-1
    if Mod(Length,2) OR !Power
        Return ""
    NumberLimit := Floor(Sqrt(CurrentNumber))
    Lower := 10 ** Power
    Loop, % NumberLimit - Lower {
        if !Mod(CurrentNumber,Lower) {
            FactorTwo := CurrentNumber//Lower
            if ( !Mod(Lower,10) && !Mod(FactorTwo,10) )
                Return ""
            Check := CharSorter( Lower . FactorTwo )
            if (CharSorter(CurrentNumber) = Check) && (StrLen(Lower) = StrLen(FactorTwo))
                Output .= "`n`t[" Lower "," FactorTwo "]"
        }
        Lower++
    }
    Return SubStr(Output,3) ; 3 = 1 + length of "`n`t"
}


program VectorProducts

  real, dimension(3)  :: a, b, c

  a = (/ 3, 4, 5 /)
  b = (/ 4, 3, 5 /)
  c = (/ -5, -12, -13 /)

  print *, dot_product(a, b)
  print *, cross_product(a, b)
  print *, s3_product(a, b, c)
  print *, v3_product(a, b, c)

contains

  function cross_product(a, b)
    real, dimension(3) :: cross_product
    real, dimension(3), intent(in) :: a, b

    cross_product(1) = a(2)*b(3) - a(3)*b(2)
    cross_product(2) = a(3)*b(1) - a(1)*b(3)
    cross_product(3) = a(1)*b(2) - b(1)*a(2)
  end function cross_product

  function s3_product(a, b, c)
    real :: s3_product
    real, dimension(3), intent(in) :: a, b, c

    s3_product = dot_product(a, cross_product(b, c))
  end function s3_product

  function v3_product(a, b, c)
    real, dimension(3) :: v3_product
    real, dimension(3), intent(in) :: a, b, c

    v3_product = cross_product(a, cross_product(b, c))
  end function v3_product

end program VectorProducts


:- func name = string.
name = Name :-
    Name = Title ++ " " ++ Given,
    Title = "Dr.",
    Given = "Bob".


MODULE Foo EXPORTS Main;

IMPORT IO, Fmt;

VAR foo: INTEGER := 5; (* foo is global (to the module). *)

PROCEDURE Foo() =
  VAR bar: INTEGER := 10; (* bar is local to the procedure Foo. *)
  BEGIN
    IO.Put("foo + bar = " & Fmt.Int(foo + bar) & "\n");
  END Foo;

BEGIN
  Foo();
END Foo.


// variable definition and initialization/assignment
//
// variables are initialized when they are defined
a = 1
b = 2
c = null

// datatypes
//
// variables may contain any datatype, and this can be
// changed at any time by assigning a new value. they may
// also contain native java types
var = "a string"
var = 123
var = new(Nanoquery.Util.Random)
var = new(java.lang.Object)

// scope
//
// all classes, functions, and control blocks have their
// own scope
x = 5
for i in range(1, 2)
        // we can reference 'x' within this loop without issue
        println x

        // we can also define variables that have this loop as their
        // scope
        y = 5
end
// trying to reference the variable 'y' outside of its scope would result
// in a null reference exception
println y
//%null reference exception: variable object 'y' has not been defined
//   at <global>:33

// referencing
//
// as already demonstrated, variables are referenced by using their
// name
part1 = "this is "
part2 = "a test sentence"
println part1 + part2

// other facilities
//
// variables may be marked for garbage collection in their current
// scope using the 'delete' command
test_var = "pretend this is a really large object we want to free up"
delete test_var


var x: int = 3                  # Declaration with type specification and initialization.

var y = 3                       # Declaration with type inferred to "int".

var z: int                      # Variable is initialized to 0.

let a = 13                      # Immutable variable.

# Using a var block to initialize.
var
  b, c: int = 10                # Two variables initialized to 10
  s* = "foobar"                 # This one is exported.

type Obj = ref object
  i: int
  s: string

var obj = Obj(i: 3, s: "abc")   # Initialization with an implicit allocation by "new".
echo obj.a, " ", obj.s          # Equivalent to obj[].a and obj[].s.

proc p =
  var xloc = 3
  echo x                        # Referencing a global variable.

  proc q =
    echo xloc                   # Referencing a variable in the enclosing scope.


( ( vampire
  =   N len R fangsList
    .   !arg:@(?N:? [?len)
      & 1/2*!len:~/:?len
      & ( R
        =     len numpart left right allowed fangs rdigits
            , tried digit untried head tail found
          .   !arg:(?len.?left.?numpart.?allowed)
            & :?found
            & (   !len:>0
                & ( @( !numpart
                     :   ?tried
                         ( #%@?digit
                         & !allowed:?head !digit ?tail
                         & !head !tail:?allowed
                         )
                         ( ?untried
                         &     R
                             $ ( !len+-1
                               . 10*!left+!digit
                               . str$(!tried !untried)
                               . 0 1 2 3 4 5 6 7 8 9
                               )
                           : ?fangs
                         & !found !fangs:?found
                         & ~
                         )
                     )
                  | !found
                  )
              |   !N*!left^-1:~/?right:~<!left:?rdigits
                & (!left*1/10:/|!right*1/10:/)
                & ( @( !numpart
                     :   ?
                         ( #%@?digit ?
                         & @(!rdigits:?head !digit ?tail)
                         & str$(!head !tail):?rdigits
                         & ~
                         )
                     )
                  | !rdigits:&(!left,!right)
                  )
              )
        )
      &   R$(!len.0.!N.1 2 3 4 5 6 7 8 9)
        : (
          |   ?fangsList
            & out$(!N !fangsList)
            & 1+!count:?count
          )
  )
& 0:?count
& 10:?i
& 16758243290880 24959017348650 14593825548650:?bignums
&   whl
  ' ( ( vampire$!i&1+!i:?i
      | !i*10:?i
      )
    & (!count:<25|!bignums:%?i ?bignums)
    )
);


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

typedef uint64_t xint;
typedef unsigned long long ull;

xint tens[20];

inline xint max(xint a, xint b) { return a > b ? a : b; }
inline xint min(xint a, xint b) { return a < b ? a : b; }
inline int ndigits(xint x)
{
	int n = 0;
	while (x) n++, x /= 10;
	return n;
}

inline xint dtally(xint x)
{
	xint t = 0;
	while (x) t += 1<<((x%10) * 6), x /= 10;

	return t;
}

int fangs(xint x, xint *f)
{
	int n = 0;
	int nd = ndigits(x);
	if (nd & 1) return 0;
	nd /= 2;

	xint lo, hi;
	lo = max(tens[nd-1], (x + tens[nd] - 2)/ (tens[nd] - 1));
	hi = min(x / lo, sqrt(x));

	xint a, b, t = dtally(x);
	for (a = lo; a <= hi; a++) {
		b = x / a;
		if (a * b == x && ((a%10) || (b%10)) && t == dtally(a) + dtally(b))
			f[n++] = a;
	}

	return n;
}

void show_fangs(xint x, xint *f, xint cnt)
{
	printf("%llu", (ull)x);
	int i;
	for (i = 0; i < cnt; i++)
		printf(" = %llu x %llu", (ull)f[i], (ull)(x / f[i]));
	putchar('\n');
}

int main(void)
{
	int i, j, n;
	xint x, f[16], bigs[] = {16758243290880ULL, 24959017348650ULL, 14593825548650ULL, 0};

	tens[0] = 1;
	for (i = 1; i < 20; i++)
		tens[i] = tens[i-1] * 10;

	for (x = 1, n = 0; n < 25; x++) {
		if (!(j = fangs(x, f))) continue;
		printf("%2d: ", ++n);
		show_fangs(x, f, j);
	}

	putchar('\n');
	for (i = 0; bigs[i]; i++) {
		if ((j = fangs(bigs[i], f)))
			show_fangs(bigs[i], f, j);
		else
			printf("%llu is not vampiric\n", (ull)bigs[i]);
	}

	return 0;
}


  'Construct only required operators for this.
Type V3
    As double x,y,z
    declare operator cast() as string
End Type
#define dot *
#define cross ^
#define Show(t1,t) ? #t1;tab(22);t

operator V3.cast() as string
return "("+str(x)+","+str(y)+","+str(z)+")"
end operator

Operator dot(v1 As v3,v2 As v3) As double
Return v1.x*v2.x+v1.y*v2.y+v1.z*v2.z
End Operator

Operator cross(v1 As v3,v2 As v3) As v3
Return type<v3>(v1.y*v2.z-v2.y*v1.z,-(v1.x*v2.z-v2.x*v1.z),v1.x*v2.y-v2.x*v1.y)
End Operator

dim as V3 a = (3, 4, 5), b = (4, 3, 5), c = (-5, -12, -13)

Show(a,a)
Show(b,b)
Show(c,c)
?
Show(a . b,a dot b)
Show(a X b,a cross b)
Show(a . b X c,a dot b cross c)
Show(a X (b X c),a cross (b cross c))
sleep


A = (3, 4, 5)
B = (4, 3, 5)
C = (-5, -12, -13)

def dot( u, v ) = sum( u(i)v(i) | i <- 0:u.>length() )
def cross( u, v ) = (u(1)v(2) - u(2)v(1), u(2)v(0) - u(0)v(2), u(0)v(1) - u(1)v(0) )
def scalarTriple( u, v, w ) = dot( u, cross(v, w) )
def vectorTriple( u, v, w ) = cross( u, cross(v, w) )

println( "A\u00b7B = ${dot(A, B)}" )
println( "A\u00d7B = ${cross(A, B)}" )
println( "A\u00b7(B\u00d7C) = ${scalarTriple(A, B, C)}" )
println( "A\u00d7(B\u00d7C) = ${vectorTriple(A, B, C)}" )


import: date

: testVariable
| a b c |
   Date now ->a
   a println ;


using System;

namespace RosettaVampireNumber
{
    class Program
    {
        static void Main(string[] args)
        {
            int i, j, n;
            ulong x;
            var f = new ulong[16];
            var bigs = new ulong[] { 16758243290880UL, 24959017348650UL, 14593825548650UL, 0 };
            ulong[] tens = new ulong[20];
            tens[0] = 1;
            for (i = 1; i < 20; i++)
                tens[i] = tens[i - 1] * 10;

            for (x = 1, n = 0; n < 25; x++)
            {
                if ((j = fangs(x, f, tens)) == 0) continue;
                Console.Write(++n + ": ");
                show_fangs(x, f, j);
            }

            Console.WriteLine();
            for (i = 0; bigs[i] > 0 ; i++)
            {
                if ((j = fangs(bigs[i], f, tens)) > 0)
                    show_fangs(bigs[i], f, j);
                else
                    Console.WriteLine(bigs[i] + " is not vampiric.");
            }
            Console.ReadLine();
        }

        private static void show_fangs(ulong x, ulong[] f, int cnt)
        {
            Console.Write(x);
            int i;
            for (i = 0; i < cnt; i++)
                Console.Write(" = " + f[i] + " * " + (x / f[i]));
            Console.WriteLine();
        }

        private static int fangs(ulong x, ulong[] f, ulong[] tens)
        {
            int n = 0;
            int nd = ndigits(x);
            if ((nd & 1) > 0) return 0;
            nd /= 2;

            ulong lo, hi;
            lo = Math.Max(tens[nd - 1], (x + tens[nd] - 2) / (tens[nd] - 1));
            hi = Math.Min(x / lo, (ulong) Math.Sqrt(x));

            ulong a, b, t = dtally(x);
            for (a = lo; a <= hi; a++)
            {
                b = x / a;
                if (a * b == x && ((a % 10) > 0 || (b % 10) > 0) && t == dtally(a) + dtally(b))
                    f[n++] = a;
            }

            return n;
        }

        private static ulong dtally(ulong x)
        {
            ulong t = 0;
            while (x > 0)
            {
                t += 1UL << (int)((x % 10) * 6);
                x /= 10;
            }

            return t;
        }

        private static int ndigits(ulong x)
        {
            int n = 0;
            while (x > 0)
            {
                n++;
                x /= 10;
            }
            return n;
        }
    }
}


DotProduct := function(u, v)
	return u*v;
end;

CrossProduct := function(u, v)
	return [
		u[2]*v[3] - u[3]*v[2],
		u[3]*v[1] - u[1]*v[3],
		u[1]*v[2] - u[2]*v[1] ];
end;

ScalarTripleProduct := function(u, v, w)
	return DotProduct(u, CrossProduct(v, w));
end;

VectorTripleProduct := function(u, v, w)
	return CrossProduct(u, CrossProduct(v, w));
end;

a := [3, 4, 5];
b := [4, 3, 5];
c := [-5, -12, -13];

DotProduct(a, b);
# 49

CrossProduct(a, b);
# [ 5, 5, -7 ]

ScalarTripleProduct(a, b, c);
# 6

# Another way to get it
Determinant([a, b, c]);
# 6

VectorTripleProduct(a, b, c);
# [ -267, 204, -3 ]


vec3 a = vec3(3, 4, 5),b = vec3(4, 3, 5),c = vec3(-5, -12, -13);

float dotProduct(vec3 a, vec3 b)
{
	return a.x*b.x+a.y*b.y+a.z*b.z;
}

vec3 crossProduct(vec3 a,vec3 b)
{
	vec3 c = vec3(a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y- a.y*b.x);

	return c;
}

float scalarTripleProduct(vec3 a,vec3 b,vec3 c)
{
	return dotProduct(a,crossProduct(b,c));
}

vec3 vectorTripleProduct(vec3 a,vec3 b,vec3 c)
{
	return crossProduct(a,crossProduct(b,c));
}


a.=4711
Say 'before sub a.3='a.3
Call sub a.
Say ' after sub a.3='a.3
Exit
sub: Procedure
use Arg a.
a.3=3
Return


; Declare the symbol 'var1' and associate number 123 with it.
(define var1 123)
(print var1)
; ==> 123

; Reassociate number 321 with var1.
(define var1 321)
(print var1)

; Create function that prints value of var1 ...
(define (show)
   (print var1))
; ... and eassociate number 42 with var1.
(define var1 42)

(print var1)
; ==> 42
; var1 prints as 42, but...
(show)
; ==> 321
; ... function 'show' still print old associated value


mynumber=5+4; // This gives a value of nine


'WAYS OF DECLARING VARIABLES
'AND ASSIGNING VALUES
var int a,b,c,d
int a=1,b=2,c=3,d=4
dim int a=1,b=2, c=3, d=4
dim as int a=1,b=2, c=3, d=4
dim a=1,b=2, c=3, d=4 as int
print c '3

'CREATING ARRAY VARIABLES
int array[100]
dim int a={10,20,30,40} 'implicit array
print a[3] '30

'COMMONLY USED TYPES:
'byte word int sys float char string

'LIMITING SCOPE
dim int a=10
scope
  dim int a=100
  dim int b=1000
  print a '100
end scope
print a 'prior a: 10
print b 'error b is out of scope

'REFERENCING VARIABLES
dim int*p 'p is a pointer variable
dim int a={2,4,6,8}
@[email protected][3] 'address of p is assigned address of a[3]
print @p 'the address
print p '6
print p[1] '6
print p[2] '8


#include <vector>
#include <utility>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <cmath>

bool isVampireNumber( long number, std::vector<std::pair<long, long> > & solution ) {
   std::ostringstream numberstream ;
   numberstream << number ;
   std::string numberstring( numberstream.str( ) ) ;
   std::sort ( numberstring.begin( ) , numberstring.end( ) ) ;
   int fanglength = numberstring.length( ) / 2 ;
   long start = static_cast<long>( std::pow( 10 , fanglength - 1 ) ) ;
   long end = sqrt(number) ;
   for ( long i = start ; i <= end ; i++ ) {
      if ( number % i == 0 ) {
	 long quotient = number / i ;
	 if ( ( i % 10 == 0 ) && ( quotient % 10 == 0 ) )
	    continue ;
	 numberstream.str( "" ) ; //clear the number stream
	 numberstream << i << quotient ;
	 std::string divisorstring ( numberstream.str( ) ) ;
         std::sort ( divisorstring.begin( ) , divisorstring.end( ) ) ;
	 if ( divisorstring == numberstring ) {
	    std::pair<long , long> divisors = std::make_pair( i, quotient ) ;
	    solution.push_back( divisors ) ;
	 }
      }
   }
   return !solution.empty( ) ;
}

void printOut( const std::pair<long, long> & solution ) {
   std::cout << "[ " << solution.first << " , " << solution.second << " ]" ;
}

int main( ) {
   int vampireNumbersFound = 0 ;
   std::vector<std::pair<long , long> > solutions ;
   double i = 1.0 ;
   while ( vampireNumbersFound < 25 ) {
      long start = static_cast<long>( std::pow( 10 , i ) ) ;
      long end = start * 10 ;
      for ( long num = start ; num < end ; num++ ) {
	 if ( isVampireNumber( num , solutions ) ) {
            vampireNumbersFound++ ;
	    std::cout << vampireNumbersFound << " :" << num << " is a vampire number! These are the fangs:\n" ;
	    std::for_each( solutions.begin( ) , solutions.end( ) , printOut ) ;
	    std::cout << "\n_______________" << std::endl ;
	    solutions.clear( ) ;
	    if ( vampireNumbersFound == 25 )
	       break ;
	 }
      }
      i += 2.0 ;
   }
   std::vector<long> testnumbers ;
   testnumbers.push_back( 16758243290880 ) ;
   testnumbers.push_back( 24959017348650 ) ;
   testnumbers.push_back( 14593825548650 ) ;
   for ( std::vector<long>::const_iterator svl = testnumbers.begin( ) ;
	 svl != testnumbers.end( ) ; svl++ ) {
      if ( isVampireNumber( *svl , solutions ) ) {
	 std::cout << *svl << " is a vampire number! The fangs:\n" ;
	 std::for_each( solutions.begin( ) , solutions.end( ) , printOut ) ;
	 std::cout << std::endl ;
	 solutions.clear( ) ;
      } else {
	 std::cout << *svl << " is not a vampire number!" << std::endl ;
      }
   }
   return 0 ;
}


package main

import "fmt"

type vector struct {
    x, y, z float64
}

var (
    a = vector{3, 4, 5}
    b = vector{4, 3, 5}
    c = vector{-5, -12, -13}
)

func dot(a, b vector) float64 {
    return a.x*b.x + a.y*b.y + a.z*b.z
}

func cross(a, b vector) vector {
    return vector{a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x}
}

func s3(a, b, c vector) float64 {
    return dot(a, cross(b, c))
}

func v3(a, b, c vector) vector {
    return cross(a, cross(b, c))
}

func main() {
    fmt.Println(dot(a, b))
    fmt.Println(cross(a, b))
    fmt.Println(s3(a, b, c))
    fmt.Println(v3(a, b, c))
}


def pairwiseOperation = { x, y, Closure binaryOp ->
    assert x && y && x.size() == y.size()
    [x, y].transpose().collect(binaryOp)
}

def pwMult =  pairwiseOperation.rcurry { it[0] * it[1] }

def dotProduct = { x, y ->
    assert x && y && x.size() == y.size()
    pwMult(x, y).sum()
}


declare
Var         %% new variable Var, initially free
{Show Var}
Var = 42    %% now Var has the value 42
{Show Var}
Var = 42    %% the same value is assigned again: ok
Var = 43    %% a different value is assigned: exception


sub dofruit {
  $fruit='apple';
}

dofruit;
print "The fruit is $fruit";


(defn factor-pairs [n]
  (for [x (range 2 (Math/sqrt n))
        :when (zero? (mod n x))]
    [x (quot n x)]))

(defn fangs [n]
  (let [dlen (comp count str)
        half (/ (dlen n) 2)
        halves? #(apply = (cons half (map dlen %)))
        digits  #(sort (apply str %))]
    (filter #(and (halves? %)
                  (= (sort (str n)) (digits %)))
            (factor-pairs n))))

(defn vampiric? [n]
  (let [fangs (fangs n)]
    (if (empty? fangs) nil [n fangs])))

(doseq [n (take 25 (keep vampiric? (range)))]
  (prn n))

(doseq [n [16758243290880, 24959017348650, 14593825548650]]
  (println (or (vampiric? n) (str n " is not vampiric."))))


(defun trailing-zerop (number)
  "Is the lowest digit of `number' a 0"
  (zerop (rem number 10)))

(defun integer-digits (integer)
  "Return the number of digits of the `integer'"
  (assert (integerp integer))
  (length (write-to-string integer)))

(defun paired-factors (number)
  "Return a list of pairs that are factors of `number'"
  (loop
    :for candidate :from 2 :upto (sqrt number)
    :when (zerop (mod number candidate))
      :collect (list candidate (/ number candidate))))

(defun vampirep (candidate &aux
                             (digits-of-candidate (integer-digits candidate))
                             (half-the-digits-of-candidate (/ digits-of-candidate
                                                              2)))
  "Is the `candidate' a vampire number?"
  (remove-if #'(lambda (pair)
                 (> (length (remove-if #'null (mapcar #'trailing-zerop pair)))
                     1))
             (remove-if-not #'(lambda (pair)
                                (string= (sort (copy-seq (write-to-string candidate))
                                               #'char<)
                                         (sort (copy-seq (format nil "~A~A" (first pair) (second pair)))
                                               #'char<)))
                            (remove-if-not #'(lambda (pair)
                                               (and (eql (integer-digits (first pair))
                                                         half-the-digits-of-candidate)
                                                    (eql (integer-digits (second pair))
                                                         half-the-digits-of-candidate)))
                                           (paired-factors candidate)))))

(defun print-vampire (candidate fangs &optional (stream t))
  (format stream
          "The number ~A is a vampire number with fangs: ~{ ~{~A~^, ~}~^; ~}~%"
          candidate
          fangs))

;; Print the first 25 vampire numbers

(loop
  :with count := 0
  :for candidate :from 0
  :until (eql count 25)
  :for fangs := (vampirep candidate)
  :do
     (when fangs
       (print-vampire candidate fangs)
       (incf count)))

;; Check if 16758243290880, 24959017348650, 14593825548650 are vampire numbers

(dolist (candidate '(16758243290880 24959017348650 14593825548650))
  (let ((fangs (vampirep candidate)))
    (when fangs
      (print-vampire candidate fangs))))


import Data.Monoid ((<>))

type Vector a = [a]

type Scalar a = a

a, b, c, d :: Vector Int
a = [3, 4, 5]

b = [4, 3, 5]

c = [-5, -12, -13]

d = [3, 4, 5, 6]

dot
  :: (Num t)
  => Vector t -> Vector t -> Scalar t
dot u v
  | length u == length v = sum $ zipWith (*) u v
  | otherwise = error "Dotted Vectors must be of equal dimension."

cross
  :: (Num t)
  => Vector t -> Vector t -> Vector t
cross u v
  | length u == 3 && length v == 3 =
    [ u !! 1 * v !! 2 - u !! 2 * v !! 1
    , u !! 2 * head v - head u * v !! 2
    , head u * v !! 1 - u !! 1 * head v
    ]
  | otherwise = error "Crossed Vectors must both be three dimensional."

scalarTriple
  :: (Num t)
  => Vector t -> Vector t -> Vector t -> Scalar t
scalarTriple q r s = dot q $ cross r s

vectorTriple
  :: (Num t)
  => Vector t -> Vector t -> Vector t -> Vector t
vectorTriple q r s = cross q $ cross r s

main :: IO ()
main =
  mapM_
    putStrLn
    [ "a . b     = " <> show (dot a b)
    , "a x b     = " <> show (cross a b)
    , "a . b x c = " <> show (scalarTriple a b c)
    , "a x b x c = " <> show (vectorTriple a b c)
    , "a . d     = " <> show (dot a d)
    ]


        <-------- object --------->
        |                |
        +-atom           +-sequence
          |                |
          +-integer        +-string


<?php
/**
 * @author Elad Yosifon
 */

/*
 * PHP is a weak typed language,
 * no separation between variable declaration, initialization and assignment.
 *
 * variable type is defined by the value that is assigned to it.
 * a variable name must start with a "$" sign (called "sigil", not a dollar sign).
 * variable naming rules:
 *     + case-sensitive.
 *     + first character after $ must not be a number.
 *     + after the first character all alphanumeric chars and  _(underscore) sign is allowed, e.g. $i_am_a_new_var_with_the_number_0
 *
 */

# NULL typed variable
$null = NULL;				var_dump($null);	// output: null

# defining a boolean
$boolean = true;			var_dump($boolean);	// output: boolean true
$boolean = false;			var_dump($boolean);	// output: boolean false

/*
 * casting is made using (TYPE) as a prefix
 */
# bool and boolean is the same
$boolean = (bool)1;			var_dump($boolean);	// output: boolean true
$boolean = (boolean)1;			var_dump($boolean);	// output: boolean true

$boolean = (bool)0;			var_dump($boolean);	// output: boolean false
$boolean = (boolean)0;			var_dump($boolean);	// output: boolean false

# defining an integer
$int = 0;				var_dump($int);		// output: int 0

# defining a float,
$float = 0.01;				var_dump($float);	// output: float 0.01

# which is also identical to "real" and "double"
var_dump((double)$float);					// output: float 0.01
var_dump((real)$float);						// output: float 0.01

# casting back to int (auto flooring the value)
var_dump((int)$float);						// output: int 0
var_dump((int)($float+1));					// output: int 1
var_dump((int)($float+1.9));					// output: int 1

# defining a string
$string = 'string';
var_dump($string);						// output: string 'string' (length=6)

# referencing a variable (there are no pointers in PHP).
$another_string = &$string;
var_dump($another_string);
								// output: string 'string' (length=6)

$string = "I'm the same string!";
var_dump($another_string);
								// output: string 'I'm the same string!' (length=20)
# "deleting" a variable from memory
unset($another_string);

$string = 'string';
/*
 * a string can also be defined with double-quotes, HEREDOC and NOWDOC operators.
 * content inside double-quotes is being parsed before assignment.
 * concatenation operator is .=
 */
$parsed_string = "This is a $string";
var_dump($parsed_string);
								// output: string 'This is a string' (length=16)
$parsed_string .= " with another {$string}";
var_dump($parsed_string);
								// output: string 'This is a string with another string' (length=36)

# with string parsing
$heredoc = <<<HEREDOC
This is the content of \$string: {$string}
HEREDOC;
var_dump($heredoc);
								// output: string 'This is the content of $string: string' (length=38)

# without string parsing (notice the single quotes surrounding NOWDOC)
$nowdoc = <<<'NOWDOC'
This is the content of \$string: {$string}
NOWDOC;
var_dump($nowdoc);
								// output: string 'This is the content of \$string: {$string}' (length=42)

# as of PHP5, defining an object typed stdClass => standard class
$stdObject = new stdClass();	var_dump($stdObject);
								// output: object(stdClass)[1]
# defining an object typed Foo
class Foo {}
$foo = new Foo();		var_dump($foo);
								// output: object(Foo)[2]
# defining an empty array
$array = array();		var_dump($array);
								// output: array {empty}

/*
 * an array with non-integer key is also considered as an associative array(i.e. hash table)
 * can contain mixed variable types, can contain integer based keys and non-integer keys
 */
$assoc = array(
	0 => $int,
	'integer' => $int,
	1 => $float,
	'float' => $float,
	2 => $string,
	'string' => $string,
	3 => NULL, // <=== key 3 is NULL
	3, // <=== this is a value, not a key (key is 4)
	5 => $stdObject,
	'Foo' => $foo,
);
var_dump($assoc);

// output:
// =======
//	array
//	    0 => int 0
//	    'integer' => int 0
//	    1 => float 0.01
//	    'float' => float 0.01
//	    2 => string 'string' (length=6)
//	    'string' => string 'string' (length=6)
//	    3 => null
//	    4 => int 3
//	    5 =>
//	    	object(stdClass)[1]
//	    'Foo' =>
//		    object(Foo)[2]

/*
 * all variables are "global" but not reachable inside functions(unless specifically "globalized" inside)
 */

function a_function()
{
	# not reachable
	var_dump(isset($foo));				// output: boolean false

	global $foo;
	# "global" (reachable) inside a_function()'s scope
	var_dump(isset($foo));				// output: boolean true
}

a_function();

/**
 * there is another special type of variable called (Resource).
 * for more info regarding Resources:
 * @url http://php.net/manual/en/language.types.resource.php
 * @url http://php.net/manual/en/resource.php
 */


import std.stdio, std.range, std.algorithm, std.typecons, std.conv;

auto fangs(in long n) pure nothrow @safe {
    auto pairs = iota(2, cast(int)(n ^^ 0.5)) // n.isqrt
                 .filter!(x => !(n % x)).map!(x => [x, n / x]);
    enum dLen = (in long x) => x.text.length;
    immutable half = dLen(n) / 2;
    enum halvesQ = (long[] p) => p.all!(u => dLen(u) == half);
    enum digits = (long[] p) => dtext(p[0], p[1]).dup.sort();
    const dn = n.to!(dchar[]).sort();
    return tuple(n, pairs.filter!(p => halvesQ(p) && dn == digits(p)));
}

void main() {
    foreach (v; int.max.iota.map!fangs.filter!q{ !a[1].empty }
                .take(25).chain([16758243290880, 24959017348650,
                                 14593825548650].map!fangs))
        writefln("%d: (%(%(%s %)) (%))", v[]);
}


# record type to store a 3D vector
record Vector3D(x, y, z)

# procedure to display vector as a string
procedure toString (vector)
  return "(" || vector.x || ", " || vector.y || ", " || vector.z || ")"
end

procedure dotProduct (a, b)
  return a.x * b.x + a.y * b.y + a.z * b.z
end

procedure crossProduct (a, b)
  x := a.y * b.z - a.z * b.y
  y := a.z * b.x - a.x * b.z
  z := a.x * b.y - a.y * b.x
  return Vector3D(x, y, z)
end

procedure scalarTriple (a, b, c)
  return dotProduct (a, crossProduct (b, c))
end

procedure vectorTriple (a, b, c)
  return crossProduct (a, crossProduct (b, c))
end

# main procedure, to run given test
procedure main ()
  a := Vector3D(3, 4, 5)
  b := Vector3D(4, 3, 5)
  c := Vector3D(-5, -12, -13)

  writes ("A.B : " || toString(a) || "." || toString(b) || " = ")
  write (dotProduct (a, b))
  writes ("AxB : " || toString(a) || "x" || toString(b) || " = ")
  write (toString(crossProduct (a, b)))
  writes ("A.(BxC) : " || toString(a) || ".(" || toString(b) || "x" || toString(c) || ") = ")
  write (scalarTriple (a, b, c))
  writes ("Ax(BxC) : " || toString(a) || "x(" || toString(b) || "x" || toString(c) || ") = ")
  write (toString(vectorTriple (a, b, c)))
end


(use (A B C)
   (setq A 1  B 2  C 3)
   ... )


/* The PROCEDURE block and BEGIN block are used to delimit scopes. */

declare i float; /* external, global variable, excluded from the */
                 /* local area (BEGIN block) below.              */
begin;
   declare (i, j) fixed binary; /* local variable */
   get list (i, j);
   put list (i,j);
end;

/* Examples of initialization. */

declare p fixed initial (25);
declare q(7) fixed initial (9, 3, 5, 1, 2, 8, 15);
   /* sets all elements of array Q at run time, on block entry. */
declare r(7) fixed initial (9, 3, 5, 1, 2, 8, 15);
   /* sets all elements of array R at compile time. */

p = 44; /* run-time assignment. */
q = 0; /* run-time initialization of all elements of Q to zero. */
q = r; /* run-time assignment of all elements of array R to     */
       /* corresponding elemets of S.                           */


var counter: I32 = 10 // mutable variable 'counter' with value 10
let temp: F64 = 36.6  // immutable variable 'temp'
let str: String       // immutable variable 'str' with no initial value
str = "i am a string" // variables must be initialized before use
let another_str = "i am another string" // type of variable 'another_str' infered from assigned value

let b  = true
let b' = false // variable names can contain ' to make a distinct variable with almost the same name


class
	APPLICATION

create
	make

feature

	fang_check (original, fang1, fang2: INTEGER_64): BOOLEAN
			-- Are 'fang1' and 'fang2' correct fangs of the 'original' number?
		require
			original_positive: original > 0
			fangs_positive: fang1 > 0 and fang2 > 0
		local
			original_length: INTEGER
			fang, ori: STRING
			sort_ori, sort_fang: SORTED_TWO_WAY_LIST [CHARACTER]
		do
			create sort_ori.make
			create sort_fang.make
			create ori.make_empty
			create fang.make_empty
			original_length := original.out.count // 2
			if fang1.out.count /= original_length or fang2.out.count /= (original_length) then
				Result := False
			elseif fang1.out.ends_with ("0") and fang2.out.ends_with ("0") then
				Result := False
			else
				across
					1 |..| original.out.count as c
				loop
					sort_ori.extend (original.out [c.item])
				end
				across
					sort_ori as o
				loop
					ori.extend (o.item)
				end
				across
					1 |..| fang1.out.count as c
				loop
					sort_fang.extend (fang1.out [c.item])
					sort_fang.extend (fang2.out [c.item])
				end
				across
					sort_fang as f
				loop
					fang.extend (f.item)
				end
				Result := fang.same_string (ori)
			end
		ensure
			fangs_right_length: Result implies original.out.count = fang1.out.count + fang2.out.count
		end

	make
                -- Uses fang_check to find vampire nubmers.
		local
			i, numbers: INTEGER
			fang1, fang2: INTEGER_64
			num: ARRAY [INTEGER_64]
			math: DOUBLE_MATH
		do
			create math
			from
				i := 1000
			until
				numbers > 25
			loop
				if i.out.count \\ 2 = 0 then
					from
						fang1 := 10
					until
						fang1 >= math.sqrt (i)
					loop
						if (i \\ fang1 = 0) then
							fang2 := i // fang1
							if i \\ 9 = (fang1 + fang2) \\ 9 then
								if fang1 * fang2 = i and fang1 <= fang2 and then fang_check (i, fang1, fang2) then
									numbers := numbers + 1
									io.put_string (i.out + ": " + fang1.out + " " + fang2.out)
									io.new_line
								end
							end
						end
						fang1 := fang1 + 1
					end
				end
				i := i + 1
			end
			num := <<16758243290880, 24959017348650, 14593825548650>>
			across
				num as n
			loop
				from
					fang1 := 1000000
				until
					fang1 >= math.sqrt (n.item) + 1
				loop
					if (n.item \\ fang1 = 0) then
						fang2 := (n.item // fang1)
						if fang1 * fang2 = n.item and fang1 <= fang2 and then fang_check (n.item, fang1, fang2) then
							io.put_string (n.item.out + ": " + fang1.out + " " + fang2.out + "%N")
						end
					end
					fang1 := fang1 + 1
				end
			end
		end

end


cross=: (1&|[email protected][ * 2&|[email protected]]) - 2&|[email protected][ * 1&|[email protected]]


public class VectorProds{
    public static class Vector3D<T extends Number>{
        private T a, b, c;

        public Vector3D(T a, T b, T c){
            this.a = a;
            this.b = b;
            this.c = c;
        }

        public double dot(Vector3D<?> vec){
            return (a.doubleValue() * vec.a.doubleValue() +
                    b.doubleValue() * vec.b.doubleValue() +
                    c.doubleValue() * vec.c.doubleValue());
        }

        public Vector3D<Double> cross(Vector3D<?> vec){
            Double newA = b.doubleValue()*vec.c.doubleValue() - c.doubleValue()*vec.b.doubleValue();
            Double newB = c.doubleValue()*vec.a.doubleValue() - a.doubleValue()*vec.c.doubleValue();
            Double newC = a.doubleValue()*vec.b.doubleValue() - b.doubleValue()*vec.a.doubleValue();
            return new Vector3D<Double>(newA, newB, newC);
        }

        public double scalTrip(Vector3D<?> vecB, Vector3D<?> vecC){
            return this.dot(vecB.cross(vecC));
        }

        public Vector3D<Double> vecTrip(Vector3D<?> vecB, Vector3D<?> vecC){
            return this.cross(vecB.cross(vecC));
        }

        @Override
        public String toString(){
            return "<" + a.toString() + ", " + b.toString() + ", " + c.toString() + ">";
        }
    }

    public static void main(String[] args){
        Vector3D<Integer> a = new Vector3D<Integer>(3, 4, 5);
        Vector3D<Integer> b = new Vector3D<Integer>(4, 3, 5);
        Vector3D<Integer> c = new Vector3D<Integer>(-5, -12, -13);

        System.out.println(a.dot(b));
        System.out.println(a.cross(b));
        System.out.println(a.scalTrip(b, c));
        System.out.println(a.vecTrip(b, c));
    }
}


; Variables are initialized when they appear in sourcecode with default value of 0 and type int
Debug a
; or value "" for a string, they are not case sensitive
Debug b$
; This initializes a double precision float, if type is following the dot
Debug c.d
; They can be initialized with define (double precision float, string, integer)
Define d.d = 3.5, e$ = "Test", f.i = a + 2
; Define can have a default type (all bytes except j which is long):
Define.b g, h, j.l
; Define without following variables sets default type. In this case to single precision float
Define.f
; So this will be an single precision float and no integer
Debug k
; EnableExplicit forces declaration of used variables with define
EnableExplicit
; Will throw an error because L isn't initialized
Debug L
DisableExplicit
; Global Variables are available in Procedures and Threads too
Global M = 3, N = 2
Procedure Dummy(parameter1, parameter2 = 20)
  ; Parameter contain values which where used when calling the function,
  ; their types have to be specified in the above Procedure header.
  ; The last ones can have default values which get applied if this parameter is not given.

  ; Variables in Procedures are separate from those outside,
  ; so d can be initialized again with another type
  ; which would otherwise lead to an error
  d.i
  ; Protected makes a variable local even if another one with same name is declared as global (see above)
  Protected M = 2
  ; Shares a variable with main program like it was declared by global
  Shared a
  ; prevents a variable to be initialized with default value again when procedure is called a second time,
  ; could be used for example as a counter, which contains the number of times a function was called
  Static a
  ; N here also would have a value of 2, while for example
  ; f would, when named, initialize a new variable, and so have a value of 0
EndProcedure
; finally there are constants which are prefixed by an #:
#Test = 1
; Their value cannot be changed while program is running
#String_Constant = "blubb"
; In constrast  to variables, a constant has no types except an (optional) $ sign to mark  it as string constant
#Float_Constant = 2.3
; Maps, LinkedLists , Arrays and Structures are not handled here, because they are no elemental variables


defmodule Vampire do
  def factor_pairs(n) do
    first = trunc(n / :math.pow(10, div(char_len(n), 2)))
    last  = :math.sqrt(n) |> round
    for i <- first .. last, rem(n, i) == 0, do: {i, div(n, i)}
  end

  def vampire_factors(n) do
    if rem(char_len(n), 2) == 1 do
      []
    else
      half = div(length(to_char_list(n)), 2)
      sorted = Enum.sort(String.codepoints("#{n}"))
      Enum.filter(factor_pairs(n), fn {a, b} ->
        char_len(a) == half && char_len(b) == half &&
        Enum.count([a, b], fn x -> rem(x, 10) == 0 end) != 2 &&
        Enum.sort(String.codepoints("#{a}#{b}")) == sorted
      end)
    end
  end

  defp char_len(n), do: length(to_char_list(n))

  def task do
    Enum.reduce_while(Stream.iterate(1, &(&1+1)), 1, fn n, acc ->
      case vampire_factors(n) do
        [] -> {:cont, acc}
        vf -> IO.puts "#{n}:\t#{inspect vf}"
              if acc < 25, do: {:cont, acc+1}, else: {:halt, acc+1}
      end
    end)
    IO.puts ""
    Enum.each([16758243290880, 24959017348650, 14593825548650], fn n ->
      case vampire_factors(n) do
        [] -> IO.puts "#{n} is not a vampire number!"
        vf -> IO.puts "#{n}:\t#{inspect vf}"
      end
    end)
  end
end

Vampire.task


USING: combinators.short-circuit fry io kernel lists lists.lazy math
math.combinatorics math.functions math.primes.factors math.statistics
math.text.utils prettyprint sequences sets ;
IN: rosetta-code.vampire-number

: digits ( n -- m )
    log10 floor >integer 1 + ;

: same-digits? ( n n1 n2 -- ? )
    [ 1 digit-groups ] [email protected] append [ histogram ] [email protected] = ;

: half-len-factors ( n -- seq )
    [ divisors ] [ digits ] bi 2/ '[ digits _ = ] filter ;

: same-digit-factors ( n -- seq )
    dup half-len-factors 2 <combinations> [ first2 same-digits? ] with filter ;

: under-two-trailing-zeros? ( seq -- ? )
    [ 10 mod ] map [ 0 = ] count 2 < ;

: tentative-fangs ( n -- seq )
    same-digit-factors [ under-two-trailing-zeros? ] filter ;

: fangs ( n -- seq )
    [ tentative-fangs ] [ ] bi '[ product _ = ] filter ;

: vampire? ( n -- ? )
    { [ digits even? ] [ fangs empty? not ] } 1&& ;

: first25 ( -- seq )
    25 0 lfrom [ vampire? ] lfilter ltake list>array ;

: .vamp-with-fangs ( n -- )
    [ pprint bl ] [ fangs [ pprint bl ] each ] bi nl ;

: part1 ( -- )
    first25 [ .vamp-with-fangs ] each ;

: part2 ( -- ) { 16758243290880 24959017348650 14593825548650 }
    [ dup vampire? [ .vamp-with-fangs ] [ drop ] if ] each ;

: main ( -- ) part1 part2 ;

MAIN: main


'Vampire numbers.
'FreeBASIC version 24. Windows
'Vampire.bas
Function WithinString(n As Ulongint,f As Ulongint) As Integer
    var m=Str(n),p=Str(f)
    For z As Integer=0 To Len(p)-1
        var i=Instr(m,Chr(p[z]))
        If i Then
            m=Mid(m,1,i-1)+Mid(m,i+1)
        Else
            Return 0
        End If
    Next z
    Return -1
End Function

Sub AllFactors(N As Ulongint,factors() As Ulongint)
    Dim As String Sn=Str(n)
    Dim As Integer half=Len(sn)\2
    Redim factors(1 To 1)
    #macro bsort(array)
    For p1 As Integer  = 1 To Ubound(array) - 1
        For p2 As Integer  = p1 + 1 To Ubound(array)
            If array(p1)>array(p2) Then Swap array(p1),array(p2)
        Next p2
    Next p1
    #endmacro

    Dim As Ulongint c
    For i As Ulongint = 1 To Sqr(N)
        If N Mod i=0 Then
            If Len(Str(i))=half Then
                If WithinString(N,i) Then
                    c=c+1
                    Redim Preserve factors(1 To c)
                    factors(c)=i
                End If
            End If
            If N <> i*i Then
                If Len(Str(n\i))=half Then
                    If WithinString(N,n\i) Then
                        c=c+1
                        Redim Preserve factors(1 To c)
                        factors(c)=n\i
                    End If
                End If
            End If
        End If
    Next i
    bsort(factors)
End Sub

Function VampireNumbers(N As Ulongint) As Integer
    Dim As Integer flag
    Dim As Ulongint LastFactor
    Redim As Ulongint Factor()
    AllFactors(N,Factor())
    For p1 As Integer = 1 To Ubound(Factor)
        For p2 As Integer=1 To Ubound(Factor)
            If Factor(p1)*Factor(p2)=n Then
                If Factor(p1) Mod 10<>0 Or Factor(p2) Mod 10 <>0 Then
                    If WithinString(n,valulng(Str(Factor(p1))+Str(Factor(p2)))) Then
                        If LastFactor=Factor(p2) Then Exit For,For
                        flag=1
                        Print n;": [";Factor(p1);",";Factor(p2);"]"
                        LastFactor=Factor(p1)
                    End If
                End If
            End If
        Next p2
    Next p1
    If flag Then Return -1
End Function

'============== IMPLEMENT ==============================
print "First 28 Vampire numbers"
print
Print "Number: [fangs]"
Print
Dim As Ulongint n=1000
Dim As Integer count
Dim As Double t1,t2
t1=Timer
Do
    n=n+1
    Var s=Str(n)
    If Len(s) Mod 2<>0 Then n=n*10
    If vampireNumbers(n) Then count=count+1
Loop Until count=27
Print
print "Individual tests:"
print
'individual tests
n=16758243290880ull
If Not vampirenumbers(n) Then Print n;": [returns no fangs]"
Print
n=24959017348650ull
If Not vampirenumbers(n) Then Print n;": [returns no fangs]"
print
n=14593825548650ull
If Not vampirenumbers(n) then print n;": [returns no fangs]"
t2=Timer
print
Print "Completed in ";
Print t2-t1;" Seconds"
Sleep