with Ada.Text_IO;

procedure Sum_Of_Powers is

   type Base is range 0 .. 250; -- A, B, C, D and Y are in that range
   type Num is range 0 .. 4*(250**5); -- (A**5 + ... + D**5) is in that range
   subtype Fit is Num range 0 .. 250**5; -- Y**5 is in that range

   Modulus: constant Num := 254;
   type Modular is mod Modulus;

   type Result_Type is array(1..5) of Base; -- this will hold A,B,C,D and Y

   type Y_Type is array(Modular) of Base;
   type Y_Sum_Type is array(Modular) of Fit;

   Y_Sum: Y_Sum_Type := (others => 0);
   Y: Y_Type := (others => 0);
      -- for I in 0 .. 250, we set Y_Sum(I**5 mod Modulus) := I**5
      --                       and Y(I**5 mod Modulus) := I
      -- Modulus has been chosen to avoid collisions on (I**5 mod Modulus)
      -- later we will compute Sum_ABCD := A**5 + B**5 + C**5 + D**5
      -- and check if Y_Sum(Sum_ABCD mod modulus) = Sum_ABCD

   function Compute_Coefficients return Result_Type is

      Sum_A: Fit;
      Sum_AB, Sum_ABC, Sum_ABCD: Num;
      Short: Modular;

   begin
      for A in Base(0) .. 246 loop
         Sum_A := Num(A) ** 5;
         for B in A .. 247 loop
            Sum_AB := Sum_A + (Num(B) ** 5);
            for C in Base'Max(B,1) .. 248 loop -- if A=B=0 then skip C=0
               Sum_ABC := Sum_AB + (Num(C) ** 5);
               for D in C .. 249 loop
                  Sum_ABCD := Sum_ABC + (Num(D) ** 5);
                  Short    := Modular(Sum_ABCD mod Modulus);
                  if Y_Sum(Short) = Sum_ABCD then
                     return A & B & C & D & Y(Short);
                  end if;
               end loop;
            end loop;
         end loop;
      end loop;
      return 0 & 0 & 0 & 0 & 0;
   end Compute_Coefficients;

   Tmp: Fit;
   ABCD_Y: Result_Type;

begin -- main program

   -- initialize Y_Sum and Y
   for I in Base(0) .. 250 loop
      Tmp := Num(I)**5;
      if Y_Sum(Modular(Tmp mod Modulus)) /= 0 then
         raise Program_Error with "Collision: Change Modulus and recompile!";
      else
         Y_Sum(Modular(Tmp mod Modulus)) := Tmp;
         Y(Modular(Tmp mod Modulus)) := I;
      end if;
   end loop;

   -- search for a solution (A, B, C, D, Y)
   ABCD_Y := Compute_Coefficients;

   -- output result
   for Number of ABCD_Y loop
      Ada.Text_IO.Put(Base'Image(Number));
   end loop;
   Ada.Text_IO.New_Line;

end Sum_Of_Powers;


200 Constant new: C
  5 Constant new: RATE

: randChar  // -- c
   27 rand dup 27 == ifTrue: [ drop ' ' ] else: [ 'A' + 1- ] ;

: fitness(a b -- n)
   a b zipWith(#==) sum ;

: mutate(s -- s')
   s map(#[ 100 rand RATE <= ifTrue: [ drop randChar ] ]) charsAsString ;

 : evolve(target)
| parent |
   ListBuffer init(target size, #randChar) charsAsString ->parent

   1 while ( parent target <> ) [
      ListBuffer init(C, #[ parent mutate ]) dup add(parent)
      maxFor(#[ target fitness ]) dup ->parent . dup println 1+
      ] drop ;


/* Weasel.rex - Me thinks thou art a weasel. - G,M.D. - 2/25/2011 */
arg C M
/* C is the number of children parent produces each generation. */
/* M is the mutation rate of each gene (character) */

call initialize
generation = 0
do until parent = target
   most_fitness = fitness(parent)
   most_fit     = parent
   do C
      child = mutate(parent, M)
      child_fitness = fitness(child)
      if child_fitness > most_fitness then
      do
         most_fitness = child_fitness
         most_fit = child
         say "Generation" generation": most fit='"most_fit"', fitness="left(most_fitness,4)
      end
   end
   parent = most_fit
   generation = generation + 1
end
exit

initialize:
   target   = "METHINKS IT IS LIKE A WEASEL"
   alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
   c_length_target = length(target)
   parent  = mutate(copies(" ", c_length_target), 1.0)
   do i = 1 to c_length_target
      target_ch.i = substr(target,i,1)
   end
return

fitness: procedure expose target_ch. c_length_target
   arg parm_string
   fitness = 0
   do i_target = 1 to c_length_target
      if substr(parm_string,i_target,1) = target_ch.i_target then
         fitness = fitness + 1
   end
return fitness

mutate:procedure expose alphabet
arg string, parm_mutation_rate
   result = ""
   do istr = 1 to length(string)
      if random(1,1000)/1000 <= parm_mutation_rate then
         result = result || substr(alphabet,random(1,length(alphabet)),1)
      else
         result = result || substr(string,istr,1)
   end
return result


{def is_odd {lambda {:i} {= {% :i 2} 1}}}
-> is_odd

{def is_even {lambda {:i} {= {% :i 2} 0}}}
-> is_even

{is_odd 2}
-> false

{is_even 2}
-> true


(defn bool isEven (int x) (return (% x 2)))


#!/bin/sh
n=5;
k=3;
calculate_factorial(){
partial_factorial=1;
for (( i=1; i<="$1"; i++ ))
do
    factorial=$(expr $i \* $partial_factorial)
    partial_factorial=$factorial

done
echo $factorial
}

n_factorial=$(calculate_factorial $n)
k_factorial=$(calculate_factorial $k)
n_minus_k_factorial=$(calculate_factorial `expr $n - $k`)
binomial_coefficient=$(expr $n_factorial \/ $k_factorial \* 1 \/ $n_minus_k_factorial )

echo "Binomial Coefficient ($n,$k) = $binomial_coefficient"


#import nat

choose = ~&ar^?\1! quotient^\~&ar product^/~&al ^|R/~& predecessor~~


Function binomial(n,k)
	binomial = factorial(n)/(factorial(n-k)*factorial(k))
End Function

Function factorial(n)
	If n = 0 Then
		factorial = 1
	Else
		For i = n To 1 Step -1
			If i = n Then
				factorial = n
			Else
				factorial = factorial * i
			End If
		Next
	End If
End Function

'calling the function
WScript.StdOut.Write "the binomial coefficient of 5 and 3 = " & binomial(5,3)
WScript.StdOut.WriteLine


import "/fmt" for Fmt
import "/math" for Int

var binomial = Fn.new { |n, k|
    if (n < 0 || k < 0) Fiber.abort("Arguments must be non-negative integers")
    if (n < k) Fiber.abort("The second argument cannot be more than the first.")
    if (n == k) return 1
    var prod = 1
    var i = n - k + 1
    while (i <= n) {
        prod = prod * i
        i = i + 1
    }
    return prod / Int.factorial(k)
}

var limit = 14
System.write("n/k |")
for (k in 0..limit) System.write(Fmt.d(5, k))
System.print()
System.write("----+" + "-----" * (limit + 1))
System.print()
for (n in 0..limit) {
    System.write("%(Fmt.d(3, n)) |")
    for (k in 0..n) System.write(Fmt.d(5, binomial.call(n, k)))
    System.print()
}


import java.io.IOException;

public class Interpreter {

    public final static int MEMORY_SIZE = 65536;

    private final char[] memory = new char[MEMORY_SIZE];
    private int dp;
    private int ip;
    private int border;

    private void reset() {

        for (int i = 0; i < MEMORY_SIZE; i++) {
            memory[i] = 0;
        }
        ip = 0;
        dp = 0;
    }

    private void load(String program) {

        if (program.length() > MEMORY_SIZE - 2) {
            throw new RuntimeException("Not enough memory.");
        }

        reset();

        for (; dp < program.length(); dp++) {
            memory[dp] = program.charAt(dp);
        }

        // memory[border] = 0 marks the end of instructions. dp (data pointer) cannot move lower than the
        // border into the program area.
        border = dp;

        dp += 1;
    }

    public void execute(String program) {

        load(program);
        char instruction = memory[ip];

        while (instruction != 0) {

            switch (instruction) {
                case '>':
                    dp++;
                    if (dp == MEMORY_SIZE) {
                        throw new RuntimeException("Out of memory.");
                    }
                    break;
                case '<':
                    dp--;
                    if (dp == border) {
                        throw new RuntimeException("Invalid data pointer.");
                    }
                    break;
                case '+':
                    memory[dp]++;
                    break;
                case '-':
                    memory[dp]--;
                    break;
                case '.':
                    System.out.print(memory[dp]);
                    break;
                case ',':
                    try {
                        // Only works for one byte characters.
                        memory[dp] = (char) System.in.read();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    break;
                case '[':
                    if (memory[dp] == 0) {
                        skipLoop();
                    }
                    break;
                case ']':
                    if (memory[dp] != 0) {
                        loop();
                    }
                    break;
                default:
                    throw new RuntimeException("Unknown instruction.");
            }

            instruction = memory[++ip];
        }
    }

    private void skipLoop() {

        int loopCount = 0;

        while (memory[ip] != 0) {
            if (memory[ip] == '[') {
                loopCount++;
            } else if (memory[ip] == ']') {
                loopCount--;
                if (loopCount == 0) {
                    return;
                }
            }
            ip++;
        }

        if (memory[ip] == 0) {
            throw new RuntimeException("Unable to find a matching ']'.");
        }
    }

    private void loop() {

        int loopCount = 0;

        while (ip >= 0) {
            if (memory[ip] == ']') {
                loopCount++;
            } else if (memory[ip] == '[') {
                loopCount--;
                if (loopCount == 0) {
                    return;
                }
            }
            ip--;
        }

        if (ip == -1) {
            throw new RuntimeException("Unable to find a matching '['.");
        }
    }

    public static void main(String[] args) {

        Interpreter interpreter = new Interpreter();
        interpreter.execute(">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.");
    }
}


/fact {
  dup 0 eq     % check for the argument being 0
  {
    pop 1      % if so, the result is 1
  }
  {
    dup
    1 sub
    fact       % call recursively with n - 1
    mul        % multiply the result with n
  } ifelse
} def


function fact1#(n%)
local i%,r#
r#=1
for i%=1 to n%
r#=r#*i%
next
fact1#=r#
end function

function fact2#(n%)
if n%<=2 then fact2#=n% else fact2#=fact2#(n%-1)*n%
end function

for i%=1 to 20
print i%,fact1#(i%),fact2#(i%)
next


(* Euler integration by recurrence relation.
 * Given a function, and stepsize, provides a function of (t,y) which
 * returns the next step: (t',y'). *)
let euler f ~step (t,y) = ( t+.step, y +. step *. f t y )

(* newton_cooling doesn't use time parameter, so _ is a placeholder *)
let newton_cooling ~k ~tr _ y = -.k *. (y -. tr)

(* analytic solution for Newton cooling *)
let analytic_solution ~k ~tr ~t0 t = tr +. (t0 -. tr) *. exp (-.k *. t)


: euler(f, y, a, b, h)
| t |
   a b h step: t [
      System.Out t <<wjp(6, JUSTIFY_RIGHT, 3) " : " << y << cr
      t y f perform h * y + ->y
      ] ;


{$mode delphi}
PROGRAM Euler;

TYPE TNewtonCooling = FUNCTION (t: REAL) : REAL;

CONST	T0	: REAL = 100.0;
CONST	TR	: REAL = 20.0;
CONST	k 	: REAL = 0.07;
CONST	time    : INTEGER = 100;
CONST	step    : INTEGER = 10;
CONST	dt	: ARRAY[0..3] of REAL = (1.0,2.0,5.0,10.0);

VAR	i	: INTEGER;

FUNCTION NewtonCooling(t: REAL) : REAL;
	BEGIN
		NewtonCooling := -k * (t-TR);
	END;

PROCEDURE Euler(F: TNewtonCooling; y, h : REAL; n: INTEGER);
	VAR i: INTEGER = 0;
	BEGIN
		WRITE('dt=',trunc(h):2,':');
		REPEAT
			IF (i mod 10 = 0) THEN WRITE(' ',y:2:3);
			INC(i,trunc(h));
			y := y + h * F(y);
		UNTIL (i >= n);
		WRITELN;
	END;

PROCEDURE Sigma;
	VAR t: INTEGER = 0;
	BEGIN
		WRITE('Sigma:');
		REPEAT
			WRITE(' ',(20 + 80 * exp(-0.07 * t)):2:3);
			INC(t,step);
		UNTIL (t>=time);
		WRITELN;
	END;

BEGIN
	WRITELN('Newton cooling function: Analytic solution (Sigma) with 3 Euler approximations.');
	WRITELN('Time: ',0:7,10:7,20:7,30:7,40:7,50:7,60:7,70:7,80:7,90:7);
	Sigma;
	FOR i := 1 to 3 DO
		Euler(NewtonCooling,T0,dt[i],time);
END.


# max number will be the highest integer we will consider                    #
INT max number = 250;

# Construct a table of the fifth powers of 1 : max number                    #
[ max number ]LONG INT fifth;
FOR i TO max number DO
    LONG INT i2 =  i * i;
    fifth[ i ] := i2 * i2 * i
OD;

# find the first a, b, c, d, e such that a^5 + b^5 + c^5 + d^5 = e^5         #
# as the fifth powers are in order, we can use a binary search to determine  #
# whether the value is in the table                                          #
BOOL found := FALSE;
FOR a TO max number WHILE NOT found DO
    FOR b FROM a TO max number WHILE NOT found DO
        FOR c FROM b TO max number WHILE NOT found DO
            FOR d FROM c TO max number WHILE NOT found DO
                LONG INT sum   = fifth[a] + fifth[b] + fifth[c] + fifth[d];
                INT      low  := d;
                INT      high := max number;
                WHILE low < high
                  AND NOT found
                DO
                    INT e := ( low + high ) OVER 2;
                    IF fifth[ e ] = sum
                    THEN
                        # the value at e is a fifth power                    #
                        found := TRUE;
                        print( ( ( whole( a, 0 ) + "^5 + " + whole( b, 0 ) + "^5 + "
                                 + whole( c, 0 ) + "^5 + " + whole( d, 0 ) + "^5 = "
                                 + whole( e, 0 ) + "^5"
                                 )
                               , newline
                               )
                             )
                    ELIF sum < fifth[ e ]
                    THEN high := e - 1
                    ELSE low  := e + 1
                    FI
                OD
            OD
        OD
    OD
OD


'EVOLUTION

target="METHINKS IT IS LIKE A WEASEL"
le=len target
progeny=string le,"X"

quad seed
declare QueryPerformanceCounter lib "kernel32.dll" (quad*q)
QueryPerformanceCounter seed

Function Rand(sys max) as sys
  mov    eax,max
  inc    eax
  imul   edx,seed,0x8088405
  inc    edx
  mov    seed,edx
  mul    edx
  return edx
End Function

sys ls=le-1,cp=0,ct=0,ch=0,fit=0,gens=0

do                         '1 mutation per generation
  i=1+rand ls              'mutation position
  ch=64+rand 26            'mutation ascii code
  if ch=64 then ch=32      'change '@' to ' '
  ct=asc target,i          'target ascii code
  cp=asc progeny,i         'parent ascii code
  '
  if ch=ct then
    if cp<>ct then
      mid progeny,i,chr ch 'carry improvement
      fit++                'increment fitness
    end if
  end if
  gens++
  if fit=le then exit do   'matches target
end do
print progeny "  " gens 'RESULT (range 1200-6000 generations)


declare
  Target = "METHINKS IT IS LIKE A WEASEL"
  C = 100
  MutateRate = 5 %% percent

  proc {Main}
     X0 = {MakeN {Length Target} RandomChar}
  in
     for Xi in {Iterate Evolve X0} break:Break do
        {System.showInfo Xi}
        if Xi == Target then {Break} end
     end
  end

  fun {Evolve Xi}
     Copies = {MakeN C fun {$} {Mutate Xi} end}
  in
     {FoldL Copies MaxByFitness Xi}
  end

  fun {Mutate Xs}
     {Map Xs
      fun {$ X}
         if {OS.rand} mod 100 < MutateRate then {RandomChar}
         else X
         end
      end}
  end

  fun {MaxByFitness A B}
     if {Fitness B} > {Fitness A} then B else A end
  end

  fun {Fitness Candidate}
     {Length {Filter {List.zip Candidate Target Value.'=='} Id}}
  end

  Alphabet = & |{List.number &A &Z 1}
  fun {RandomChar}
     I = {OS.rand} mod {Length Alphabet} + 1
  in
     {Nth Alphabet I}
  end

  %% General purpose helpers

  fun {Id X} X end

  fun {MakeN N F}
     Xs = {List.make N}
  in
     {ForAll Xs F}
     Xs
  end

  fun lazy {Iterate F X}
     X|{Iterate F {F X}}
  end
in
  {Main}


: even?  2 % not ;
: odd?  2 % ;
1 even? .   # 0
1 odd? .    # 1


define isoddoreven(i::integer) => {
	#i % 2 ? return 'odd'
	return 'even'
}
isoddoreven(12)


func fib_iter(n) {
    var (a, b) = (0, 1)
    { (a, b) = (b, a+b) } * n
    return a
}


code ChOut=8, CrLf=9, IntOut=11;

func Binomial(N, K);
int  N, K;
int  M, B, I;
[M:= K;
if K>N/2 the M:= N-K;
B:=1;
for I:= 1 to M do
    B:= B*(N-M+I)/I;
return B;
];

int N, K;
[for N:= 0 to 9 do
    [for K:= 0 to 9 do
        [if N>=K then IntOut(0, Binomial(N,K));
        ChOut(0, 9\tab\);
        ];
    CrLf(0);
    ];
] \Mr. Pascal's triangle!


const std = @import("std");

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

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

const rmax = 68;

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

test "n choose k" {
    const expect = std.testing.expect;
    try expect(nCk(10, 5).? == 252);
    try expect(nCk(10, 11).? == 0);
    try expect(nCk(10, 10).? == 1);
    try expect(nCk(67, 33).? == 14226520737620288370);
    try expect(nCk(68, 34) == null);
}


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


10 LET n=33: LET k=17: PRINT "Binomial ";n;",";k;" = ";
20 LET r=1: LET d=n-k
30 IF d>k THEN LET k=d: LET d=n-k
40 IF n<=k THEN GO TO 90
50 LET r=r*n
60 LET n=n-1
70 IF (d>1) AND (FN m(r,d)=0) THEN LET r=r/d: LET d=d-1: GO TO 70
80 GO TO 40
90 PRINT r
100 DEF FN m(a,b)=a-INT (a/b)*b


function Get-Factorial ($x) {
    if ($x -eq 0) {
        return 1
    }
    return $x * (Get-Factorial ($x - 1))
}


int fact(int n){
	if(n <= 1){
		return 1;
	} else{
		return n*fact(n-1);
	}
}


begin
    % find a, b, c, d, e such that a^5 + b^5 + c^5 + d^5 = e^5                              %
    %                        where 1 <= a <= b <= c <= d <= e <= 250                        %
    % we solve this using the equivalent equation a^5 + b^5 + c^5 = e^5 - d^5               %
    % 250^5 is 976 562 500 000 - too large for a 32 bit number so we will use pairs of      %
    % integers and constrain their values to be in 0..1 000 000                             %
    % Note only positive numbers are needed                                                 %
    integer MAX_NUMBER, MAX_V;
    MAX_NUMBER := 250;
    MAX_V      := 1000000;
    begin
        % quick sorts the fifth power differences table                                     %
        procedure quickSort5 ( integer value lb, ub ) ;
            if ub > lb then begin
                % more than one element, so must sort                                       %
                integer left, right, pivot, pivotLo, pivotHi;
                left    := lb;
                right   := ub;
                % choosing the middle element of the array as the pivot %
                pivot   := left + ( ( ( right + 1 ) - left ) div 2 );
                pivotLo := loD( pivot );
                pivotHi := hiD( pivot );
                while begin
                    while left  <= ub
                      and begin integer cmp;
                                cmp := hiD( left ) - pivotHi;
                                if cmp = 0 then cmp := loD( left ) - pivotLo;
                                cmp < 0
                          end
                    do left := left + 1;
                    while right >= lb
                      and begin integer cmp;
                                cmp := hiD( right ) - pivotHi;
                                if cmp = 0 then cmp := loD( right ) - pivotLo;
                                cmp > 0
                          end
                    do right := right - 1;
                    left <= right
                end do begin
                    integer swapLo, swapHi, swapD, swapE;
                    swapLo       := loD( left  );
                    swapHi       := hiD( left  );
                    swapD        := Dd(  left  );
                    swapE        := De(  left  );
                    loD( left  ) := loD( right );
                    hiD( left  ) := hiD( right );
                    Dd(  left  ) := Dd(  right );
                    De(  left  ) := De(  right );
                    loD( right ) := swapLo;
                    hiD( right ) := swapHi;
                    Dd(  right ) := swapD;
                    De(  right ) := swapE;
                    left         := left  + 1;
                    right        := right - 1
                end while_left_le_right ;
                quickSort5( lb,   right );
                quickSort5( left, ub    )
            end quickSort5 ;
        % table of fifth powers                                                             %
        integer array lo5, hi5         ( 1 :: MAX_NUMBER );
        % table if differences between fifth powers                                         %
        integer array loD, hiD, De, Dd ( 1 :: MAX_NUMBER * MAX_NUMBER );
        integer dUsed, dPos;
        % compute fifth powers                                                              %
        for i := 1 until MAX_NUMBER do begin
            lo5( i ) := i * i; hi5( i ) := 0;
            for p := 3 until 5 do begin
                integer carry;
                lo5( i ) := lo5( i ) * i;
                carry    := lo5( i ) div MAX_V;
                lo5( i ) := lo5( i ) rem MAX_V;
                hi5( i ) := hi5( i ) * i;
                hi5( i ) := hi5( i ) + carry
            end for_p
        end for_i ;
        % compute the differences between fifth powers e^5 - d^5, 1 <= d < e <= MAX_NUMBER  %
        dUsed := 0;
        for e := 2 until MAX_NUMBER do begin
            for d := 1 until e - 1  do begin
                dUsed := dUsed + 1;
                De(  dUsed ) := e;
                Dd(  dUsed ) := d;
                loD( dUsed ) := lo5( e ) - lo5( d );
                hiD( dUsed ) := hi5( e ) - hi5( d );
                if loD( dUsed ) < 0 then begin
                    loD( dUsed ) := loD( dUsed ) + MAX_V;
                    hiD( dUsed ) := hiD( dUsed ) - 1
                end if_need_to_borrow
            end for_d
        end for_e;
        % sort the fifth power differences                                                  %
        quickSort5( 1, dUsed );
        % attempt to find a^5 + b^5 + c^5 = e^5 - d^5                                       %
        for a := 1 until MAX_NUMBER do begin
            integer loA, hiA;
            loA := lo5( a ); hiA := hi5( a );
            for b := a until MAX_NUMBER do begin
                integer loB, hiB;
                loB := lo5( b ); hiB := hi5( b );
                for c := b until MAX_NUMBER do begin
                    integer low, high, loSum, hiSum;
                    loSum :=                       loA + loB + lo5( c );
                    hiSum := ( loSum div MAX_V ) + hiA + hiB + hi5( c );
                    loSum :=   loSum rem MAX_V;
                    % look for hiSum,loSum in hiD,loD                                       %
                    low   := 1;
                    high  := dUsed;
                    while low < high do begin
                        integer mid, cmp;
                        mid := ( low + high ) div 2;
                        cmp := hiD( mid ) - hiSum;
                        if cmp = 0 then cmp := loD( mid ) - loSum;
                        if cmp = 0 then begin
                            % the value at mid is the difference of two fifth powers        %
                            write( i_w := 1, s_w := 0
                                 , a, "^5 + ", b, "^5 + ", c, "^5 + "
                                 , Dd( mid ), "^5 = ", De( mid ), "^5"
                                 );
                            go to found
                            end
                        else if cmp > 0 then high := mid - 1
                        else                 low  := mid + 1
                    end while_low_lt_high
                end for_c
            end for_b
        end for_a ;
found :
    end
end.


target="METHINKS IT IS LIKE A WEASEL";
fitness(s)=-dist(Vec(s),Vec(target));
dist(u,v)=sum(i=1,min(#u,#v),u[i]!=v[i])+abs(#u-#v);
letter()=my(r=random(27)); if(r==26, " ", Strchr(r+65));
insert(v,x=letter())=
{
	my(r=random(#v+1));
	if(r==0, return(concat([x],v)));
	if(r==#v, return(concat(v,[x])));
	concat(concat(v[1..r],[x]),v[r+1..#v]);
}
delete(v)=
{
	if(#v<2, return([]));
	my(r=random(#v)+1);
	if(r==1, return(v[2..#v]));
	if(r==#v, return(v[1..#v-1]));
	concat(v[1..r-1],v[r+1..#v]);
}
mutate(s,rateM,rateI,rateD)=
{
	my(v=Vec(s));
	if(random(1.)<rateI, v=insert(v));
	if(random(1.)<rateD, v=delete(v));
	for(i=1,#v,
		if(random(1.)<rateM, v[i]=letter())
	);
	concat(v);
}
evolve(C,rate)=
{
	my(parent=concat(vector(#target,i,letter())),ct=0);
	while(parent != target,
		print(parent" "fitness(parent));
		my(v=vector(C,i,mutate(parent,rate,0,0)),best,t);
		best=fitness(parent=v[1]);
		for(i=2,C,
			t=fitness(v[i]);
			if(t>best, best=t; parent=v[i])
		);
		ct++
	);
	print(parent" "fitness(parent));
	ct;
}
evolve(35,.05)


      .ORIG      0x3000

      LD         R0,NUM
      AND        R1,R0,1
      BRZ        EVEN

      LEA        R0,ODD
      BRNZP      DISP

EVEN  LEA        R0,EVN

DISP  PUTS

      HALT

NUM   .FILL      0x1C

EVN   .STRINGZ   "EVEN\n"
ODD   .STRINGZ   "ODD\n"

      .END


n=12

if n mod 2 = 0 then print "even" else print "odd"


INTEGER PROCEDURE fibonacci(n);
INTEGER n;
BEGIN
    INTEGER lo, hi, temp, i;
    lo := 0;
    hi := 1;
    FOR i := 1 STEP 1 UNTIL n - 1 DO
    BEGIN
        temp := hi;
        hi := hi + lo;
        lo := temp
    END;
    fibonacci := hi
END;


import java.io.IOException;

public class Interpreter {

    public final static int MEMORY_SIZE = 65536;

    private final char[] memory = new char[MEMORY_SIZE];
    private int dp;
    private int ip;
    private int border;

    private void reset() {

        for (int i = 0; i < MEMORY_SIZE; i++) {
            memory[i] = 0;
        }
        ip = 0;
        dp = 0;
    }

    private void load(String program) {

        if (program.length() > MEMORY_SIZE - 2) {
            throw new RuntimeException("Not enough memory.");
        }

        reset();

        for (; dp < program.length(); dp++) {
            memory[dp] = program.charAt(dp);
        }

        // memory[border] = 0 marks the end of instructions. dp (data pointer) cannot move lower than the
        // border into the program area.
        border = dp;

        dp += 1;
    }

    public void execute(String program) {

        load(program);
        char instruction = memory[ip];

        while (instruction != 0) {

            switch (instruction) {
                case '>':
                    dp++;
                    if (dp == MEMORY_SIZE) {
                        throw new RuntimeException("Out of memory.");
                    }
                    break;
                case '<':
                    dp--;
                    if (dp == border) {
                        throw new RuntimeException("Invalid data pointer.");
                    }
                    break;
                case '+':
                    memory[dp]++;
                    break;
                case '-':
                    memory[dp]--;
                    break;
                case '.':
                    System.out.print(memory[dp]);
                    break;
                case ',':
                    try {
                        // Only works for one byte characters.
                        memory[dp] = (char) System.in.read();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    break;
                case '[':
                    if (memory[dp] == 0) {
                        skipLoop();
                    }
                    break;
                case ']':
                    if (memory[dp] != 0) {
                        loop();
                    }
                    break;
                default:
                    throw new RuntimeException("Unknown instruction.");
            }

            instruction = memory[++ip];
        }
    }

    private void skipLoop() {

        int loopCount = 0;

        while (memory[ip] != 0) {
            if (memory[ip] == '[') {
                loopCount++;
            } else if (memory[ip] == ']') {
                loopCount--;
                if (loopCount == 0) {
                    return;
                }
            }
            ip++;
        }

        if (memory[ip] == 0) {
            throw new RuntimeException("Unable to find a matching ']'.");
        }
    }

    private void loop() {

        int loopCount = 0;

        while (ip >= 0) {
            if (memory[ip] == ']') {
                loopCount++;
            } else if (memory[ip] == '[') {
                loopCount--;
                if (loopCount == 0) {
                    return;
                }
            }
            ip--;
        }

        if (ip == -1) {
            throw new RuntimeException("Unable to find a matching '['.");
        }
    }

    public static void main(String[] args) {

        Interpreter interpreter = new Interpreter();
        interpreter.execute(">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.");
    }
}


fact(X, 1) :- X<2.
fact(X, F) :- Y is X-1, fact(Y,Z), F is Z*X.


--
-- demo\rosetta\Euler_method.exw
-- =============================
--
with javascript_semantics
function ivp_euler(atom y, integer f, step, end_t)
    sequence res = {}
    for t=0 to end_t by step do
        if remainder(t,10)==0 then res &= y end if
        y += step * call_func(f,{t, y})
    end for
    return res
end function

function analytic()
    sequence res = {}
    for t=0 to 100 by 10 do
        res &= 20 + 80 * exp(-0.07 * t)
    end for
    return res
end function

function cooling(atom /*t*/, temp)
    return -0.07 * (temp - 20)
end function

constant x = tagset(100,0,10),
         a = analytic(),
        e2 = ivp_euler(100,cooling,2,100),
        e5 = ivp_euler(100,cooling,5,100),
       e10 = ivp_euler(100,cooling,10,100)
printf(1,"    Time:  %s\n",{join(x,fmt:="%7d")})
printf(1,"Analytic:  %s\n",{join(a,fmt:="%7.3f")})
printf(1," Step  2:  %s\n",{join(e2,fmt:="%7.3f")})
printf(1," Step  5:  %s\n",{join(e5,fmt:="%7.3f")})
printf(1," Step 10:  %s\n",{join(e10,fmt:="%7.3f")})

-- and a simple plot
include pGUI.e
include IupGraph.e

function get_data(Ihandle /*graph*/)
    return {{"NAMES",{"analytical","h=2","h=5","h=10"}},
     {x,a,CD_BLUE},{x,e2,CD_GREEN},{x,e5,CD_BLACK},{x,e10,CD_RED}}
end function

IupOpen()
Ihandle graph = IupGraph(get_data,`RASTERSIZE=340x240,GRID=NO`)
IupSetAttributes(graph,`XTICK=20,XMIN=0,XMAX=100,XMARGIN=25`)
IupSetAttributes(graph,`YTICK=20,YMIN=20,YMAX=100`)
IupShow(IupDialog(graph,`TITLE="Euler Method",MINSIZE=260x200`))
if platform()!=JS then
    IupMainLoop()
    IupClose()
end if


eulerSumOfPowers: function [top][
    p5: map 0..top => [& ^ 5]

    loop 4..top 'a [
        loop 3..a-1 'b [
            loop 2..b-1 'c [
                loop 1..c-1 'd [
                    s: (get p5 a) + (get p5 b) + (get p5 c) + (get p5 d)
                    if integer? index p5 s ->
                        return ~"|a|^5 + |b|^5 + |c|^5 + |d|^5 = |index p5 s|^5"
                ]
            ]
        ]
    ]

    return "not found" ; shouldn't reach here
]

print eulerSumOfPowers 249


# syntax: GAWK -f EULERS_SUM_OF_POWERS_CONJECTURE.AWK
BEGIN {
    start_int = systime()
    main()
    printf("%d seconds\n",systime()-start_int)
    exit(0)
}
function main(  sum,s1,x0,x1,x2,x3) {
    for (x0=1; x0<=250; x0++) {
      for (x1=1; x1<=x0; x1++) {
        for (x2=1; x2<=x1; x2++) {
          for (x3=1; x3<=x2; x3++) {
            sum = (x0^5) + (x1^5) + (x2^5) + (x3^5)
            s1 = int(sum ^ 0.2)
            if (sum == s1^5) {
              printf("%d^5 + %d^5 + %d^5 + %d^5 = %d^5\n",x0,x1,x2,x3,s1)
              return
            }
          }
        }
      }
    }
}


PROGRAM EVOLUTION (OUTPUT);

CONST
	TARGET = 'METHINKS IT IS LIKE A WEASEL';
	COPIES = 100;  (* 100 children in each generation. *)
	RATE = 1000;  (* About one character in 1000 will be a mutation. *)

TYPE
	STRLIST = ARRAY [1..COPIES] OF STRING;

FUNCTION RANDCHAR : CHAR;
 (* Generate a random letter or space. *)
 VAR RANDNUM : INTEGER;
 BEGIN
	RANDNUM := RANDOM(27);
	IF RANDNUM = 26 THEN
		RANDCHAR := ' '
	ELSE
		RANDCHAR := CHR(RANDNUM + ORD('A'))
 END;

FUNCTION RANDSTR (SIZE : INTEGER) : STRING;
 (* Generate a random string. *)
 VAR
	N : INTEGER;
	S : STRING;
 BEGIN
	S := '';
	FOR N := 1 TO SIZE DO
		INSERT(RANDCHAR, S, 1);
	RANDSTR := S
 END;

FUNCTION FITNESS (CANDIDATE, GOAL : STRING) : INTEGER;
 (* Count the number of correct letters in the correct places *)
 VAR N, MATCHES : INTEGER;
 BEGIN
	MATCHES := 0;
	FOR N := 1 TO LENGTH(GOAL) DO
		IF CANDIDATE[N] = GOAL[N] THEN
			MATCHES := MATCHES + 1;
	FITNESS := MATCHES
 END;

FUNCTION MUTATE (RATE : INTEGER; S : STRING) : STRING;
 (* Randomly alter a string. Characters change with probability 1/RATE. *)
 VAR
	N : INTEGER;
	CHANGE : BOOLEAN;
 BEGIN
	FOR N := 1 TO LENGTH(TARGET) DO
	 BEGIN
		CHANGE := RANDOM(RATE) = 0;
		IF CHANGE THEN
			S[N] := RANDCHAR
	 END;
	MUTATE := S
 END;

PROCEDURE REPRODUCE (RATE : INTEGER; PARENT : STRING; VAR CHILDREN : STRLIST);
 (* Generate children with random mutations. *)
 VAR N : INTEGER;
 BEGIN
	FOR N := 1 TO COPIES DO
		CHILDREN[N] := MUTATE(RATE, PARENT)
 END;

FUNCTION FITTEST(CHILDREN : STRLIST; GOAL : STRING) : STRING;
 (* Measure the fitness of each child and return the fittest. *)
 (* If multiple children equally match the target, then return the first. *)
 VAR
	MATCHES, MOST_MATCHES, BEST_INDEX, N : INTEGER;
 BEGIN
	MOST_MATCHES := 0;
	BEST_INDEX := 1;
	FOR N := 1 TO COPIES DO
	 BEGIN
		MATCHES := FITNESS(CHILDREN[N], GOAL);
		IF MATCHES > MOST_MATCHES THEN
		 BEGIN
			MOST_MATCHES := MATCHES;
			BEST_INDEX := N
		 END
	 END;
	FITTEST := CHILDREN[BEST_INDEX]
 END;

VAR
	PARENT, BEST_CHILD : STRING;
	CHILDREN : STRLIST;
	GENERATIONS : INTEGER;

BEGIN
	RANDOMIZE;
	GENERATIONS := 0;
	PARENT := RANDSTR(LENGTH(TARGET));
	WHILE NOT (PARENT = TARGET) DO
	 BEGIN
		IF (GENERATIONS MOD 100) = 0 THEN WRITELN(PARENT);
		GENERATIONS := GENERATIONS + 1;
		REPRODUCE(RATE, PARENT, CHILDREN);
		BEST_CHILD := FITTEST(CHILDREN, TARGET);
		IF FITNESS(PARENT, TARGET) < FITNESS(BEST_CHILD, TARGET) THEN
			PARENT := BEST_CHILD
	 END;
	WRITE('The string was matched in ');
	WRITELN(GENERATIONS, ' generations.')
END.


on even (n)
  return n mod 2 = 0
end

on odd (n)
  return n mode 2 <> 0
end


// Input number; output its residue mod 2
       INP        // read input into acc
       BRZ write  // input = 0 is special case
loop   SUB k2     // keep subtracting 2 from acc
       BRZ write  // if acc = 0, input is even
       BRP loop   // if acc > 0, loop back
                  // (BRP branches if acc >= 0, but we've dealt with acc = 0)
       LDA k1     // if acc < 0, input is odd
write  OUT        // output 0 or 1
       HLT        // halt
k1     DAT 1      // constant 1
k2     DAT 2      // constant 2
// end


function odd n
    return (n bitand 1) = 1
end odd

function notEven n
    return (n mod 2) = 1
end notEven


/*
 * javascript bf interpreter
 * by [email protected]
 */

function execute(code)
{
    var mem = new Array(30000);
    var sp = 10000;
    var opcode = new String(code);
    var oplen = opcode.length;
    var ip = 0;
    var loopstack = new Array();
    var output = "";

    for (var i = 0; i < 30000; ++i) mem[i] = 0;

    while (ip < oplen) {
        switch(opcode[ip]) {
            case '+':
                mem[sp]++;
                break;
            case '-':
                mem[sp]--;
                break;
            case '>':
                sp++;
                break;
            case '<':
                sp--;
                break;
            case '.':
                if (mem[sp] != 10 && mem[sp] != 13) {
                    output = output + Util.fromCharCode(mem[sp]);
                } else {
                    puts(output);
                    output = "";
                }
                break;
            case ',':
                var s = console.input();
                if (!s) exit(0);

                mem[sp] = s.charCodeAt(0);
                break;
            case '[':
                if (mem[sp]) {
                    loopstack.push(ip);
                } else {
                    for (var k = ip, j = 0; k < oplen; k++) {
                        opcode[k] == '[' && j++;
                        opcode[k] == ']' && j--;
                        if (j == 0) break;
                    }
                    if (j == 0) ip = k;
                    else {
                        puts("Unmatched loop");
                        return false;
                    }
                }
                break;
            case ']':
                ip = loopstack.pop() - 1;
                break;
            default:
                break;
        }
        ip++;
    }
    return true;
};

if (Interp.conf('unitTest') > 0)  execute('
    ++++++++++[>+>+++>++++>+++++++ >++++++++>+++++++++>++++++++++>+++++++++
    ++>++++++++++++<<<<<<<<<-]>>>>+.>>>>+..<.<++++++++.>>>+.<<+.<<<<++++.<+
    +.>>>+++++++.>>>.+++.<+++++++.--------.<<<<<+.<+++.---.
');


fact n = n*fact (n-1) if n>0;
       = 1 otherwise;
let facts = map fact (1..10); facts;


Procedure factorial(n)
  Protected i, f = 1
  For i = 2 To n
    f = f * i
  Next
  ProcedureReturn f
EndProcedure


with Ada.Environment_Variables; use Ada.Environment_Variables;
with Ada.Text_Io; use Ada.Text_Io;

procedure Print_Path is
begin
   Put_Line("Path : " & Value("PATH"));
end Print_Path;


tell application "Finder" to get name of home


print ["path:" env\PATH]
print ["user:" env\USER]
print ["home:" env\HOME]


(load "@lib/math.l")

(de euler (F Y A B H)
   (while (> B A)
      (prinl (round A) " " (round Y))
      (inc 'Y (*/ H (F A Y) 1.0))
      (inc 'A H) ) )

(de newtonCoolingLaw (A B)
   (*/ -0.07 (- B 20.) 1.0) )

(euler newtonCoolingLaw 100.0 0 100.0 2.0)
(euler newtonCoolingLaw 100.0 0 100.0 5.0)
(euler newtonCoolingLaw 100.0 0 100.0 10.0)


test: procedure options (main); /* 3 December 2012 */

   declare (x, y, z) float;
   declare (T0 initial (100), Tr initial (20)) float;
   declare k float initial (0.07);
   declare t fixed binary;
   declare h fixed binary;

   x, y, z = T0;
   /* Step size is 2 seconds */
   h = 2;
   put skip data (h);
   put skip list ('  t    By formula', 'By Euler');
   do t = 0 to 100 by 2;
      put skip edit (t, Tr + (T0 - Tr)/exp(k*t), x) (f(3), 2 f(17,10));
      x = x + h*f(t, x);
   end;

   /* Step size is 5 seconds */
   h = 5;
   put skip data (h);
   put skip list ('  t    By formula', 'By Euler');
   do t = 0 to 100 by 5;
      put skip edit ( t, Tr + (T0 - Tr)/exp(k*t), y) (f(3), 2 f(17,10));
      y = y + h*f(t, y);
   end;

   /* Step size is 10 seconds */
   h = 10;
   put skip data (h);
   put skip list ('  t    By formula', 'By Euler');
   do t = 0 to 100 by 10;
      put skip edit (t, Tr + (T0 - Tr)/exp(k*t), z) (f(3), 2 f(17,10));
      z = z + h*f(t, z);
   end;

f: procedure (dummy, T) returns (float);
   declare dummy  fixed binary;
   declare T float;

   return ( -k*(T - Tr) );
end f;

end test;


GET "libhdr"

LET solve() BE {
    LET pow5 = VEC 249
    LET sum = ?

    FOR i = 1 TO 249
        pow5!i := i * i * i * i * i

    FOR w = 4 TO 249
        FOR x = 3 TO w - 1
            FOR y = 2 TO x - 1
                FOR z = 1 TO y - 1 {
                    sum := pow5!w + pow5!x + pow5!y + pow5!z
                    FOR a = w + 1 TO 249
                        IF pow5!a = sum {
                            writef("solution found: %d  %d  %d  %d  %d *n", w, x, y, z, a)
                            RETURN
                        }
                }
    writef("Sorry, no solution found.*n")
}

LET start() = VALOF {
    solve()
    RESULTIS 0
}


// Alexander Maximov, July 2nd, 2015
#include <stdio.h>
#include <time.h>
typedef long long mylong;

void compute(int N, char find_only_one_solution)
{	const int M = 30;   /* x^5 == x modulo M=2*3*5 */
	int a, b, c, d, e;
	mylong s, t, max, *p5 = (mylong*)malloc(sizeof(mylong)*(N+M));

	for(s=0; s < N; ++s)
		p5[s] = s * s, p5[s] *= p5[s] * s;
	for(max = p5[N - 1]; s < (N + M); p5[s++] = max + 1);

	for(a = 1; a < N; ++a)
	for(b = a + 1; b < N; ++b)
	for(c = b + 1; c < N; ++c)
	for(d = c + 1, e = d + ((t = p5[a] + p5[b] + p5[c]) % M); ((s = t + p5[d]) <= max); ++d, ++e)
	{	for(e -= M; p5[e + M] <= s; e += M); /* jump over M=30 values for e>d */
		if(p5[e] == s)
		{	printf("%d %d %d %d %d\r\n", a, b, c, d, e);
			if(find_only_one_solution) goto onexit;
		}
	}
onexit:
	free(p5);
}

int main(void)
{
	int tm = clock();
	compute(250, 0);
	printf("time=%d milliseconds\r\n", (int)((clock() - tm) * 1000 / CLOCKS_PER_SEC));
	return 0;
}


use List::Util 'reduce';
use List::MoreUtils 'false';

### Generally useful declarations

sub randElm
 {$_[int rand @_]}

sub minBy (&@)
 {my $f = shift;
  reduce {$f->($b) < $f->($a) ? $b : $a} @_;}

sub zip
 {@_ or return ();
  for (my ($n, @a) = 0 ;; ++$n)
    {my @row;
     foreach (@_)
        {$n < @$_ or return @a;
         push @row, $_->[$n];}
     push @a, \@row;}}

### Task-specific declarations

my $C = 100;
my $mutation_rate = .05;
my @target = split '', 'METHINKS IT IS LIKE A WEASEL';
my @valid_chars = (' ', 'A' .. 'Z');

sub fitness
 {false {$_->[0] eq $_->[1]} zip shift, \@target;}

sub mutate
 {my $rate = shift;
  return [map {rand() < $rate ? randElm @valid_chars : $_} @{shift()}];}

### Main loop

my $parent = [map {randElm @valid_chars} @target];

while (fitness $parent)
   {$parent =
       minBy \&fitness,
       map {mutate $mutation_rate, $parent}
       1 .. $C;
    print @$parent, "\n";}


; This is not strictly LLVM, as it uses the C library function "printf".
; LLVM does not provide a way to print values, so the alternative would be
; to just load the string into memory, and that would be boring.

; Additional comments have been inserted, as well as changes made from the output produced by clang such as putting more meaningful labels for the jumps

;--- The declarations for the external C functions
declare i32 @printf(i8*, ...)

$"EVEN_STR" = comdat any
$"ODD_STR" = comdat any

@"EVEN_STR" = linkonce_odr unnamed_addr constant [12 x i8] c"%d is even\0A\00", comdat, align 1
@"ODD_STR" = linkonce_odr unnamed_addr constant [11 x i8] c"%d is odd\0A\00", comdat, align 1

; Function Attrs: noinline nounwind optnone uwtable
define i32 @main() #0 {
  %1 = alloca i32, align 4          ;-- allocate i
  store i32 0, i32* %1, align 4     ;-- store 0 in i
  br label %loop

loop:
  %2 = load i32, i32* %1, align 4   ;-- load i
  %3 = icmp ult i32 %2, 4           ;-- i < 4
  br i1 %3, label %loop_body, label %exit

loop_body:
  %4 = load i32, i32* %1, align 4   ;-- load i
  %5 = and i32 %4, 1                ;-- i & 1
  %6 = icmp eq i32 %5, 0            ;-- (i & 1) == 0
  br i1 %6, label %even_branch, label %odd_branch

even_branch:
  %7 = load i32, i32* %1, align 4   ;-- load i
  %8 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([12 x i8], [12 x i8]* @"EVEN_STR", i32 0, i32 0), i32 %7)
  br label %loop_increment

odd_branch:
  %9 = load i32, i32* %1, align 4   ;-- load i
  %10 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([11 x i8], [11 x i8]* @"ODD_STR", i32 0, i32 0), i32 %9)
  br label %loop_increment

loop_increment:
  %11 = load i32, i32* %1, align 4  ;-- load i
  %12 = add i32 %11, 1              ;-- increment i
  store i32 %12, i32* %1, align 4   ;-- store i
  br label %loop

exit:
  ret i32 0
}

attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }


[email protected](Integer traits) fib
[
  n <= 0 ifTrue: [^ 0].
  n = 1 ifTrue: [^ 1].
  (n - 1) fib + (n - 2) fib
].

slate[15]> 10 fib = 55.
True


with Ada.Text_Io;
with Ada.Command_Line;
with Ada.Numerics.Elementary_Functions;

procedure Entropy is
   use Ada.Text_Io;

   type Hist_Type is array (Character) of Natural;

   function Log_2 (V : Float) return Float is
      use Ada.Numerics.Elementary_Functions;
   begin
      return Log (V) / Log (2.0);
   end Log_2;

   procedure Read_File (Name : String; Hist : out Hist_Type) is
      File : File_Type;
      Char : Character;
   begin
      Hist := (others => 0);
      Open (File, In_File, Name);
      while not End_Of_File (File) loop
         Get (File, Char);
         Hist (Char) := Hist (Char) + 1;
      end loop;
      Close (File);
   end Read_File;

   function Length_Of (Hist : Hist_Type) return Natural is
      Sum : Natural := 0;
   begin
      for V of Hist loop
         Sum := Sum + V;
      end loop;
      return Sum;
   end Length_Of;

   function Entropy_Of (Hist : Hist_Type) return Float is
      Length : constant Float := Float (Length_Of (Hist));
      Sum    : Float := 0.0;
   begin
      for V of Hist loop
         if V > 0 then
            Sum := Sum + Float (V) / Length * Log_2 (Float (V) / Length);
         end if;
      end loop;
      return -Sum;
   end Entropy_Of;

   package Float_Io is new Ada.Text_Io.Float_Io (Float);
   Name : constant String := Ada.Command_Line.Argument (1);
   Hist : Hist_Type;
   Entr : Float;
begin
   Float_Io.Default_Exp := 0;
   Float_Io.Default_Aft := 6;

   Read_File (Name, Hist);
   Entr := Entropy_Of (Hist);

   Put ("Entropy of '");
   Put (Name);
   Put ("' is ");
   Float_Io.Put (Entr);
   New_Line;
end Entropy;


EnvGet, OutputVar, Path
MsgBox, %OutputVar%


ConsoleWrite("# Environment:" & @CRLF)

Local $sEnvVar = EnvGet("LANG")
ConsoleWrite("LANG : " & $sEnvVar & @CRLF)

ShowEnv("SystemDrive")
ShowEnv("USERNAME")

Func ShowEnv($N)
    ConsoleWrite( StringFormat("%-12s : %s\n", $N, EnvGet($N)) )
EndFunc   ;==>ShowEnv


$ awk 'BEGIN{print "HOME:"ENVIRON["HOME"],"USER:"ENVIRON["USER"]}'


using System;

namespace EulerSumOfPowers {
    class Program {
        const int MAX_NUMBER = 250;

        static void Main(string[] args) {
            bool found = false;
            long[] fifth = new long[MAX_NUMBER];

            for (int i = 1; i <= MAX_NUMBER; i++) {
                long i2 = i * i;
                fifth[i - 1] = i2 * i2 * i;
            }

            for (int a = 0; a < MAX_NUMBER && !found; a++) {
                for (int b = a; b < MAX_NUMBER && !found; b++) {
                    for (int c = b; c < MAX_NUMBER && !found; c++) {
                        for (int d = c; d < MAX_NUMBER && !found; d++) {
                            long sum = fifth[a] + fifth[b] + fifth[c] + fifth[d];
                            int e = Array.BinarySearch(fifth, sum);
                            found = e >= 0;
                            if (found) {
                                Console.WriteLine("{0}^5 + {1}^5 + {2}^5 + {3}^5 = {4}^5", a + 1, b + 1, c + 1, d + 1, e + 1);
                            }
                        }
                    }
                }
            }
        }
    }
}


with javascript_semantics
constant target = "METHINKS IT IS LIKE A WEASEL",
         AZS    = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ",
         C = 5000,  -- children in each generation
         P = 15     -- probability of mutation (1 in 15)

function fitness(string sample, string target)
    return sum(sq_eq(sample,target))
end function

function mutate(string s, integer n)
    for i=1 to length(s) do
        if rand(n)=1 then
            s[i] = AZS[rand(length(AZS))]
        end if
    end for
    return s
end function

string parent = mutate(target,1) -- (mutate with 100% probability)
sequence samples = repeat(0,C)
integer gen = 0, best, fit, best_fit = fitness(parent,target)
while parent!=target do
    printf(1,"Generation%3d: %s, fitness %3.2f%%\n", {gen, parent, (best_fit/length(target))*100})
    best_fit = -1
    for i=1 to C do
        samples[i] = mutate(parent, P)
        fit = fitness(samples[i], target)
        if fit > best_fit then
            best_fit = fit
            best = i
        end if
    end for
    parent = samples[best]
    gen += 1
end while
printf(1,"Finally, \"%s\"\n",{parent})


to even? :num
    output equal? 0 modulo :num 2
end


:- object(even_odd).

    :- public(test_mod/1).
    test_mod(I) :-
        (   I mod 2 =:= 0 ->
            write(even), nl
        ;   write(odd), nl
        ).

    :- public(test_bit/1).
    test_bit(I) :-
        (   I /\ 1 =:= 1 ->
            write(odd), nl
        ;   write(even), nl
        ).

:- end_object.


Integer >> fibI
    |aNMinus1 an t|

    aNMinus1 := 1.
    an := 0.
    self timesRepeat:[
        t := an.
        an := an + aNMinus1 .
        aNMinus1 := t.
    ].
    ^ an


using DataStructures

function execute(src)
    pointers = Dict{Int,Int}()
    stack    = Int[]
    for (ptr, opcode) in enumerate(src)
        if opcode == '[' push!(stack, ptr) end
        if opcode == ']'
            if isempty(stack)
                src = src[1:ptr]
                break
            end
            sptr = pop!(stack)
            pointers[ptr], pointers[sptr] = sptr, ptr
        end
    end
    if ! isempty(stack) error("unclosed loops at $stack") end
    tape = DefaultDict{Int,Int}(0)
    cell, ptr = 0, 1
    while ptr ≤ length(src)
        opcode = src[ptr]
        if     opcode == '>' cell += 1
        elseif opcode == '<' cell -= 1
        elseif opcode == '+' tape[cell] += 1
        elseif opcode == '-' tape[cell] -= 1
        elseif opcode == ',' tape[cell] = Int(read(STDIN, 1))
        elseif opcode == '.' print(STDOUT, Char(tape[cell]))
        elseif (opcode == '[' && tape[cell] == 0) ||
               (opcode == ']' && tape[cell] != 0) ptr = pointers[ptr]
        end
        ptr += 1
    end
end

const src = """\
    >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>
    >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++."""
execute(src)


// version 1.1.2

class Brainf__k(val prog: String, memSize: Int) {
    private val mem = IntArray(memSize)
    private var ip = 0
    private var dp = 0
    private val memVal get() = mem.getOrElse(dp) { 0 }

    fun execute() {
        while (ip < prog.length) {
            when (prog[ip++]) {
                '>' -> dp++
                '<' -> dp--
                '+' -> mem[dp] = memVal + 1
                '-' -> mem[dp] = memVal - 1
                ',' -> mem[dp] = System.`in`.read()
                '.' -> print(memVal.toChar())
                '[' -> handleLoopStart()
                ']' -> handleLoopEnd()
            }
        }
    }

    private fun handleLoopStart() {
        if (memVal != 0) return
        var depth = 1
        while (ip < prog.length) {
            when (prog[ip++]) {
                '[' -> depth++
                ']' -> if (--depth == 0) return
            }
        }
        throw IllegalStateException("Could not find matching end bracket")
    }

    private fun handleLoopEnd() {
        var depth = 0
        while (ip >= 0) {
            when (prog[--ip]) {
                ']' -> depth++
                '[' -> if (--depth == 0) return
            }
        }
        throw IllegalStateException("Could not find matching start bracket")
    }
}

fun main(args: Array<String>) {
    val prog = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."
    Brainf__k(prog, 10).execute()
}


BEGIN
    # calculate the shannon entropy of a string                                #
    PROC shannon entropy = ( STRING s )REAL:
    BEGIN
        INT string length = ( UPB s - LWB s ) + 1;
        # count the occurances of each character #
        [ 0 : max abs char ]INT char count;
        FOR char pos FROM LWB char count TO UPB char count DO
            char count[ char pos ] := 0
        OD;
        FOR char pos FROM LWB s TO UPB s DO
            char count[ ABS s[ char pos ] ] +:= 1
        OD;
        # calculate the entropy, we use log base 10 and then convert #
        # to log base 2 after calculating the sum                    #
        REAL entropy := 0;
        FOR char pos FROM LWB char count TO UPB char count DO
            IF char count[ char pos ] /= 0
            THEN
                # have a character that occurs in the string #
                REAL probability = char count[ char pos ] / string length;
                entropy -:= probability * log( probability )
            FI
        OD;
        entropy / log( 2 )
    END; # shannon entropy #

    IF  FILE input file;
        STRING file name = "entropyNarcissist.a68";
        open( input file, file name, stand in channel ) /= 0
    THEN
        # failed to open the file #
        print( ( "Unable to open """ + file name + """", newline ) )
    ELSE
        # file opened OK #
        BOOL at eof := FALSE;
        # set the EOF handler for the file #
        on logical file end( input file
                           , ( REF FILE f )BOOL:
                             BEGIN
                                 # note that we reached EOF on the latest read #
                                 at eof := TRUE;
                                 # return TRUE so processing can continue #
                                 TRUE
                             END
                           );
        # construct a string containing the whole file #
        STRING file contents := "";
        WHILE STRING line;
              get( input file, ( line, newline ) );
              NOT at eof
        DO
            file contents +:= line + REPR 12
        OD;
        close( input file );
        # show the entropy of the file cotents #
        print( ( shannon entropy( file contents ), newline ) )
    FI
END


FileRead, var, *C %A_ScriptFullPath%
MsgBox, % Entropy(var)

Entropy(n) {
    a := [], len := StrLen(n), m := n
    while StrLen(m) {
        s := SubStr(m, 1, 1)
        m := RegExReplace(m, s, "", c)
        a[s] := c
    }
    for key, val in a {
        m := Log(p := val / len)
        e -= p * m / Log(2)
    }
    return, e
}


REDIM fac#(0)
Factorial fac#(), 655, 10, power#
PRINT power#
SUB Factorial (fac#(), n&, numdigits%, power#)
power# = 0
fac#(0) = 1
remain# = 0
stx& = 0
slog# = 0
NumDiv# = 10 ^ numdigits%
FOR fac# = 1 TO n&
    slog# = slog# + LOG(fac#) / LOG(10)
    FOR x& = 0 TO stx&
        fac#(x&) = fac#(x&) * fac# + remain#
        tx# = fac#(x&) MOD NumDiv#
        remain# = (fac#(x&) - tx#) / NumDiv#
        fac#(x&) = tx#
    NEXT
    IF remain# > 0 THEN
        stx& = UBOUND(fac#) + 1
        REDIM _PRESERVE fac#(stx&)
        fac#(stx&) = remain#
        remain# = 0
    END IF
NEXT

scanz& = LBOUND(fac#)
DO
    IF scanz& < UBOUND(fac#) THEN
        IF fac#(scanz&) THEN
            EXIT DO
        ELSE
            scanz& = scanz& + 1
        END IF
    ELSE
        EXIT DO
    END IF
LOOP

FOR x& = UBOUND(fac#) TO scanz& STEP -1
    m$ = LTRIM$(RTRIM$(STR$(fac#(x&))))
    IF x& < UBOUND(fac#) THEN
        WHILE LEN(m$) < numdigits%
            m$ = "0" + m$
        WEND
    END IF
    PRINT m$; " ";
    power# = power# + LEN(m$)
NEXT
power# = power# + (scanz& * numdigits%) - 1
PRINT slog#
END SUB


      PRINT FNenvironment("PATH")
      PRINT FNenvironment("USERNAME")
      END

      DEF FNenvironment(envar$)
      LOCAL buffer%, size%
      SYS "GetEnvironmentVariable", envar$, 0, 0 TO size%
      DIM buffer% LOCAL size%
      SYS "GetEnvironmentVariable", envar$, buffer%, size%+1
      = $$buffer%


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

int main() {
  puts(getenv("HOME"));
  puts(getenv("PATH"));
  puts(getenv("USER"));
  return 0;
}


using System;

namespace RosettaCode {
    class Program {
        static void Main() {
            string temp = Environment.GetEnvironmentVariable("TEMP");
            Console.WriteLine("TEMP is " + temp);
        }
    }
}


Define.d
Prototype.d Func(Time, t)

Procedure.d Euler(*F.Func, y0, a, b, h)
  Protected y=y0, t=a
  While t<=b
    PrintN(RSet(StrF(t,3),7)+" "+RSet(StrF(y,3),7))
    y + h * *F(t,y)
    t + h
  Wend
EndProcedure

Procedure.d newtonCoolingLaw(Time, t)
  ProcedureReturn -0.07*(t-20)
EndProcedure

If OpenConsole()
  Euler(@newtonCoolingLaw(), 100, 0, 100, 2)
  Euler(@newtonCoolingLaw(), 100, 0, 100, 5)
  Euler(@newtonCoolingLaw(), 100, 0, 100,10)

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


def euler(f,y0,a,b,h):
	t,y = a,y0
	while t <= b:
		print "%6.3f %6.3f" % (t,y)
		t += h
		y += h * f(t,y)

def newtoncooling(time, temp):
	return -0.07 * (temp - 20)

euler(newtoncooling,100,0,100,10)


#include <algorithm>
#include <iostream>
#include <cmath>
#include <set>
#include <vector>

using namespace std;

bool find()
{
    const auto MAX = 250;
    vector<double> pow5(MAX);
    for (auto i = 1; i < MAX; i++)
        pow5[i] = (double)i * i * i * i * i;
    for (auto x0 = 1; x0 < MAX; x0++) {
        for (auto x1 = 1; x1 < x0; x1++) {
            for (auto x2 = 1; x2 < x1; x2++) {
                for (auto x3 = 1; x3 < x2; x3++) {
                    auto sum = pow5[x0] + pow5[x1] + pow5[x2] + pow5[x3];
                    if (binary_search(pow5.begin(), pow5.end(), sum))
                    {
                        cout << x0 << " " << x1 << " " << x2 << " " << x3 << " " << pow(sum, 1.0 / 5.0) << endl;
                        return true;
                    }
                }
            }
        }
    }
    // not found
    return false;
}

int main(void)
{
    int tm = clock();
    if (!find())
        cout << "Nothing found!\n";
    cout << "time=" << (int)((clock() - tm) * 1000 / CLOCKS_PER_SEC) << " milliseconds\r\n";
    return 0;
}


define('TARGET','METHINKS IT IS LIKE A WEASEL');
define('TBL','ABCDEFGHIJKLMNOPQRSTUVWXYZ ');

define('MUTATE',15);
define('COPIES',30);
define('TARGET_COUNT',strlen(TARGET));
define('TBL_COUNT',strlen(TBL));

// Determine number of different chars between a and b

function unfitness($a,$b)
{
        $sum=0;
        for($i=0;$i<strlen($a);$i++)
                if($a[$i]!=$b[$i]) $sum++;
        return($sum);
}

function mutate($a)
{
        $tbl=TBL;
        for($i=0;$i<strlen($a);$i++) $out[$i]=mt_rand(0,MUTATE)?$a[$i]:$tbl[mt_rand(0,TBL_COUNT-1)];
        return(implode('',$out));
}

$tbl=TBL;
for($i=0;$i<TARGET_COUNT;$i++) $tspec[$i]=$tbl[mt_rand(0,TBL_COUNT-1)];
$parent[0]=implode('',$tspec);
$best=TARGET_COUNT+1;
$iters=0;
do {
        for($i=1;$i<COPIES;$i++) $parent[$i]=mutate($parent[0]);

        for($best_i=$i=0; $i<COPIES;$i++) {
                $unfit=unfitness(TARGET,$parent[$i]);
                if($unfit < $best || !$i) {
                        $best=$unfit;
                        $best_i=$i;
                }
        }
        if($best_i>0) $parent[0]=$parent[$best_i];
        $iters++;
        print("Generation $iters, score $best: $parent[0]\n");
} while($best);


HAI 1.4
I HAS A integer
GIMMEH integer
I HAS A remainder
remainder R MOD OF integer AN 2
BOTH SAEM remainder AN 1, O RLY?
YA RLY
VISIBLE "The integer is odd."
NO WAI
VISIBLE "The integer is even."
OIC
KTHXBYE


-- test for even number
if n % 2 == 0 then
  print "The number is even"
end

-- test for odd number
if not (n % 2 == 0) then
  print "The number is odd"
end


FOR i = 0 TO 15
    PRINT fibR(i),fibI(i),fibN(i)
NEXT i

/* Recursive Method */
DEF fibR(n)
    IF n <= 1 THEN
        fibR = n
    ELSE
        fibR = fibR(n-1) + fibR(n-2)
    ENDIF
END DEF

/* Iterative Method */
DEF fibI(n)
    a = 0
    b = 1
    FOR i = 1 TO n
        temp = a + b
        a = b
        b = temp
    NEXT i
    fibI = a
END DEF

/* N-th Term Method */
DEF fibN(n)
    uphi = .5 + SQR(5)/2
    lphi = .5 - SQR(5)/2
    fibN = (uphi^n-lphi^n)/SQR(5)
END DEF


implement Bf;

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

Bf: module {
	init: fn(nil: ref Draw->Context, args: list of string);
	ARENASZ: con 1024 * 1024;
	EXIT, INC, DEC, JZ, JNZ, INCP, DECP, READ, WRITE: con iota;
};

init(nil: ref Draw->Context, args: list of string)
{
	sys = load Sys Sys->PATH;
	args = tl args;
	if(args == nil || len args != 1) {
		sys->fprint(sys->fildes(2), "usage: bf program");
		raise "fail:usage";
	}
	code := compile(hd args);
	execute(code, array[ARENASZ] of { * => byte 0 });
}

compile(p: string): array of int
{
	marks: list of int = nil;
	code := array[len p * 2 + 1] of { * => EXIT };
	pc := 0;
	for(i := 0; i < len p; i++) {
		case p[i] {
		'-' => code[pc++] = DEC;
		'+' => code[pc++] = INC;
		'<' => code[pc++] = DECP;
		'>' => code[pc++] = INCP;
		',' => code[pc++] = READ;
		'.' => code[pc++] = WRITE;
		'[' =>
			code[pc++] = JZ;
			marks = pc++ :: marks;
		']' =>
			if(marks == nil) {
				sys->fprint(sys->fildes(2), "bf: unmatched ']' at character %d.", pc);
				raise "fail:errors";
			}
			c := hd marks;
			marks = tl marks;
			code[pc++] = JNZ;
			code[c] = pc;
			code[pc++] = c;
		}
	}
	if(marks != nil) {
		sys->fprint(sys->fildes(2), "bf: unmatched '['.");
		raise "fail:errors";
	}
	return code;
}

execute(code: array of int, arena: array of byte)
{
	pc := 0;
	p := 0;
	buf := array[1] of byte;
	stopreading := 0;
	for(;;) {
		case code[pc] {
		DEC => arena[p]--;
		INC => arena[p]++;
		DECP =>
			p--;
			if(p < 0)
				p = len arena - 1;
		INCP =>
			p = (p + 1) % len arena;
		READ =>
			if(!stopreading) {
				n := sys->read(sys->fildes(0), buf, 1);
				if(n < 1) {
					arena[p] = byte 0;
					stopreading = 1;
				} else {
					arena[p] = buf[0];
				}
			}
		WRITE =>
			buf[0] = arena[p];
			sys->write(sys->fildes(1), buf, 1);
		JNZ =>
			if(arena[p] != byte 0)
				pc = code[pc + 1];
			else
				pc++;
		JZ =>
			if(arena[p] == byte 0)
				pc = code[pc + 1];
			else
				pc++;
		EXIT => return;
		}
		pc++;
	}
}


local funs = {
['>'] = 'ptr = ptr + 1; ',
['<'] = 'ptr = ptr - 1; ',
['+'] = 'mem[ptr] = mem[ptr] + 1; ',
['-'] = 'mem[ptr] = mem[ptr] - 1; ',
['['] = 'while mem[ptr] ~= 0 do ',
[']'] = 'end; ',
['.'] = 'io.write(string.char(mem[ptr])); ',
[','] = 'mem[ptr] = (io.read(1) or "\\0"):byte(); ',
}

local prog = [[
  local mem = setmetatable({}, { __index = function() return 0 end})
  local ptr = 1
]]

local source = io.read('*all')

for p = 1, #source do
  local snippet = funs[source:sub(p,p)]
  if snippet then prog = prog .. snippet end
end

load(prog)()


BEGIN{FS=""
 RS="\x04"#EOF
 getline<"entropy.awk"
 for(i=1;i<=NF;i++)H[$i]++
 for(i in H)E-=(h=H[i]/NF)*log(h)
 print "bytes ",NF," entropy ",E/log(2)
 exit}


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

#define MAXLEN 961 //maximum string length

int makehist(char *S,int *hist,int len){
	int wherechar[256];
	int i,histlen;
	histlen=0;
	for(i=0;i<256;i++)wherechar[i]=-1;
	for(i=0;i<len;i++){
		if(wherechar[(int)S[i]]==-1){
			wherechar[(int)S[i]]=histlen;
			histlen++;
		}
		hist[wherechar[(int)S[i]]]++;
	}
	return histlen;
}

double entropy(int *hist,int histlen,int len){
	int i;
	double H;
	H=0;
	for(i=0;i<histlen;i++){
		H-=(double)hist[i]/len*log2((double)hist[i]/len);
	}
	return H;
}

int main(void){
	char S[MAXLEN];
	int len,*hist,histlen;
	double H;
	FILE *f;
	f=fopen("entropy.c","r");
	for(len=0;!feof(f);len++)S[len]=fgetc(f);
	S[--len]='\0';
	hist=(int*)calloc(len,sizeof(int));
	histlen=makehist(S,hist,len);
	//hist now has no order (known to the program) but that doesn't matter
	H=entropy(hist,histlen,len);
	printf("%lf\n",H);
	return 0;
}


[ 1 swap times [ i 1+ * ] ] is ! ( n --> n! )


fact <- function(n) {
  if (n <= 1) 1
  else n * Recall(n - 1)
}


#include <cstdlib>
#include <cstdio>

int main()
{
   puts(getenv("HOME"));
   return 0;
}


       IDENTIFICATION DIVISION.
       PROGRAM-ID. Environment-Vars.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  home PIC X(75).

       PROCEDURE DIVISION.
*          *> Method 1.
           ACCEPT home FROM ENVIRONMENT "HOME"
           DISPLAY home

*          *> Method 2.
           DISPLAY "HOME" UPON ENVIRONMENT-NAME
           ACCEPT home FROM ENVIRONMENT-VALUE

           GOBACK
           .


for var_name in ['PATH', 'HOME', 'LANG', 'USER']
  console.log var_name, process.env[var_name]


euler <- function(f, y0, a, b, h)
{
  t <- a
  y <- y0

  while (t < b)
  {
    cat(sprintf("%6.3f %6.3f\n", t, y))
    t <- t + h
    y <- y + h*f(t, y)
  }
}

newtoncooling <- function(time, temp){
  return(-0.07*(temp-20))
  }

euler(newtoncooling, 100, 0, 100, 10)


(define (ODE-solve f init
                   #:x-max x-max
                   #:step h
                   #:method (method euler))
  (reverse
   (iterate-while (λ (x . y) (<= x x-max)) (method f h) init)))


(ns test-p.core
  (:require [clojure.math.numeric-tower :as math])
  (:require [clojure.data.int-map :as i]))

(defn solve-power-sum [max-value max-sols]
  " Finds solutions by using method approach of EchoLisp
    Large difference is we store a dictionary of all combinations
    of y^5 - x^5 with the x, y value so we can simply lookup rather than have to search "
  (let [pow5 (mapv #(math/expt % 5) (range 0 (* 4 max-value)))                  ; Pow5 = Generate Lookup table for x^5
        y5-x3 (into (i/int-map) (for [x (range 1 max-value)                     ; For x0^5 + x1^5 + x2^5 + x3^5  = y^5
                                      y (range (+ 1 x) (* 4 max-value))]        ; compute y5-x3 = set of all possible differnences
                                  [(- (get pow5 y) (get pow5 x)) [x y]])) ; note: (get pow5 y) is closure for: pow5[y]
        solutions-found (atom 0)]

    (for [x0 (range 1 max-value)                                    ; Search over x0, x1, x2 for sums equal y5-x3
          x1 (range 1 x0)
          x2 (range 1 x1)
          :when (< @solutions-found max-sols)
          :let [sum (apply + (map pow5 [x0 x1 x2]))]         ; compute sum of items to the 5th power
          :when (contains? y5-x3 sum)]                       ; check if sum is in set of differences
      (do
        (swap! solutions-found inc)                          ; increment counter for solutions found
        (concat [x0 x1 x2] (get y5-x3 sum))))))              ; create result (since in set of differences)

; Output results with numbers in ascending order placing results into a set (i.e. #{}) so duplicates are discarded
                                                            ; CPU i7 920 Quad Core @2.67 GHz clock Windows 10
(println (into #{} (map sort (solve-power-sum 250 1))))   ; MAX = 250, find only 1 value: Duration was 0.26 seconds
(println (into #{} (map sort (solve-power-sum 1000 1000))));MAX = 1000, high max-value so all solutions found: Time = 4.8 seconds


go =>
  _ = random2(),
  Target = "METHINKS IT IS LIKE A WEASEL",
  Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ",
  C = 50, % Population size in each generation
  M = 80,  % Mutation rate per individual in a generation (0.8)

  evo(Target,Chars,C,M),

  nl.

evo(Target,Chars,C,M) =>
  if member(T,Target), not member(T, Chars) then
     printf("The character %w is not in the character set: %w\n", T, Chars);
     halt
  end,

  % first random string
  TargetLen = Target.length,
  Parent = random_chars(Chars,TargetLen),

  %
  % Until current fitness reaches a score of perfect match
  % with the target string keep generating new populations
  %
  CurrentFitness = 0,
  Gen = 1,
  while (CurrentFitness < TargetLen)
    println([gen=Gen, currentFitness=CurrentFitness, parent=Parent]),
    Gen := Gen + 1,
    [Parent2,CurrentFitness2] = generation(C,Chars,Target,M,Parent),
    CurrentFitness := CurrentFitness2,
    Parent := Parent2
  end,

  println([gen=Gen, currentFitness=CurrentFitness, parent=Parent]),
  printf("\nFound a perfect fitness (%d) at generation %d\n", CurrentFitness, Gen),

  nl.

%
% Generate a random string
%
random_chars(Chars, N) = [Chars[my_rand(Len)] : _ in 1..N] =>
  Len = Chars.length.

%
% Increment the fitness for every position in the string
% S that matches the target
%
fitness(S,Target) = sum([1: I in 1..Target.length, S[I] == Target[I]]).

%
% If a random number between 1 and 100 is inside the
% bounds of mutation randomly alter a character in the string
%
mutate(S,M,Chars) = S2 =>
  S2 = copy_term(S),
  if my_rand(100) <= M then
    S2[my_rand(S.length)] := Chars[my_rand(Chars.length)]
  end.

% Get a random value between 1 and N
my_rand(N) = 1+(random() mod N).

%
% Create the next population of parent
%
generation(C,Chars,Target,M,Parent) = [NextParent,NextFitness] =>
  % generate a random population
  Population = [mutate(Parent,M,Chars) : _ in 1..C],

  % Find the member of the population with highest fitness,
  NextParent = Parent,
  NextFitness = fitness(Parent,Target),
  foreach(X in Population)
    XF = fitness(X,Target),
    if XF > NextFitness then
      NextParent := X,
      NextFitness := XF
    end
  end.


(load "@lib/simul.l")

(setq *Target (chop "METHINKS IT IS LIKE A WEASEL"))

# Generate random character
(de randChar ()
   (if (=0 (rand 0 26))
      " "
      (char (rand `(char "A") `(char "Z"))) ) )

# Fitness function (Hamming distance)
(de fitness (A)
   (cnt = A *Target) )

# Genetic algorithm
(gen
   (make                               # Parent population
      (do 100                             # C = 100 children
         (link
            (make
               (do (length *Target)
                  (link (randChar)) ) ) ) ) )
   '((A)                               # Termination condition
      (prinl (maxi fitness A))            # Print the fittest element
      (member *Target A) )                # and check if solution is found
   '((A B)                             # Recombination function
      (mapcar
         '((C D) (if (rand T) C D))       # Pick one of the chars
         A B ) )
   '((A)                               # Mutation function
      (mapcar
         '((C)
            (if (=0 (rand 0 10))          # With a proability of 10%
               (randChar)                 # generate a new char, otherwise
               C ) )                      # return the current char
         A ) )
   fitness )                           # Selection function


Function F {
      Read x
      code here
}


define(`even', `ifelse(eval(`$1'%2),0,True,False)')
define(`odd',  `ifelse(eval(`$1'%2),0,False,True)')

even(13)
even(8)

odd(5)
odd(0)


EvenOrOdd := proc( x::integer )
   if x mod 2 = 0 then
      print("Even"):
   else
      print("Odd"):
   end if:
end proc:
EvenOrOdd(9);


	define("fib(a)")	:(fib_end)
fib	fib = lt(a,2) a	:s(return)
	fib = fib(a - 1) + fib(a - 2)	:(return)
fib_end

while	a = trim(input)	:f(end)
	output = a " " fib(a)	:(while)
end


Module Checkit {
      \\ Brain**** Compiler

      Escape Off
      \\ no Esc function so we can use Ctrl+Z when input characters to terminate BF
      \\ ctrl+c open dialog for exit - by default in console mode

      Const skipmonitor as boolean=true, output as boolean=True
      Const ob$="{",cb$="}"
      Gosub CallOne
      \\ We use a group object with events.

      Group WithEvents BF=BrainF()

      Function BF_monitor {
            \\ Event functions have same scope as the module where belong
            If skipmonitor Then exit
            Read New pc, mem
            Print pc, mem
            Print "Press space bar": While Key$<>" " {}
      }
      Function BF_newline {
            If not skipmonitor then Print "newline" : exit
            if output then Print
      }
      Function BF_print {
            Read New c$
            If not skipmonitor then Print "character:";c$  : exit
            if output then Print c$;
      }

      Program$ = {++++++[>++++++++++++<-]>.
                  >++++++++++[>++++++++++<-]>+.
                  +++++++..+++.>++++[>+++++++++++<-]>.
                  <+++[>----<-]>.<<<<<+++[>+++++<-]>.
                  >>.+++.------.--------.>>+.
                  }
      Report Program$
      ExecBF(Program$)
      End

      Sub ExecBF(Code$)
            ClearMem()
            code$=filter$(code$, " "+chr$(10)+chr$(13))
            code$<=replace$(".","@", code$)
            code$<=replace$("-","-.D()", code$)
            code$<=replace$("+","-.A()", code$)
            code$<=replace$("<","-.L()", code$)
            code$<=replace$(">","-.R()", code$)
            code$<=replace$("@","-.P()", code$)
            code$<=replace$("[","-.S("+ob$,code$)
            code$<=replace$("]",cb$+")",code$)
            code$<=replace$(",","-.K()", code$)
            Rem : Print code$
            BF.Eval code$
            Print
      End Sub
      Sub ClearMem()
            Dim cMem(1 to 30000)=0
            For BF {
                  .Pc=1
                  .Zero=True
                  .Mem()=cMem()
            }
      End Sub
      CallOne:
      Class BrainF {
            events "monitor", "newline", "print"
            Dim Mem()
            Pc=1, Zero as Boolean=True
            Module UpdateZero {
                  .Zero<=.Mem(.Pc)=0
                  call event "monitor", .pc, .Mem(.pc)
            }
            Function A {   \\ +
                  .Mem(.Pc)++
                  .UpdateZero
            }
            Function D {  \\ -
                  .Mem(.Pc)--
                  .UpdateZero
            }
            Function R { \\ >
                  If .Pc=30000 Then Error "Upper Bound Error"
                  .Pc++
                  .UpdateZero
            }
            Function L { \\ <
                  If .Pc=1 Then Error "Lower Bound Error"
                  .Pc--
                  .UpdateZero
            }
            Function P { \\ .
                  Select Case .Mem(.Pc)
                  Case >31
                        Call Event "print", Chr$(.Mem(.Pc))
                  Case 10
                        Call Event "newline"
                  End Select
            }
            Function K {  \\ ,
                  .Mem(.Pc)=Asc(Key$)
                  \\ ctrl+z for exit
                  If .Mem(.Pc)=26 Then  Error "Finished"
                   .UpdateZero
            }
            Function S  { \\ [
                  If .Zero then =0: exit
                  Read newEval$
                  Do {ret=Eval(newEval$)} until .Zero
            }
            Module Eval {
                  ret=eval(Letter$)
            }
      }
      Return
}
Checkit


bf[program_, input_] :=
  Module[{p = Characters[program], pp = 0, m, mp = 0, bc = 0,
      instr = StringToStream[input]},
    m[_] = 0;
    While[pp < [email protected],
      pp++;
      Switch[p[[pp]],
        ">", mp++,
        "<", mp--,
        "+", m[mp]++,
        "-", m[mp]--,
        ".", BinaryWrite["stdout", m[mp]],
        ",", m[mp] = BinaryRead[instr],
        "[", If[m[mp] == 0,
          bc = 1;
          While[bc > 0, pp++; Switch[p[[pp]], "[", bc++, "]", bc--]]],
        "]", If[m[mp] != 0,
          bc = -1;
          While[bc < 0, pp--; Switch[p[[pp]], "[", bc++, "]", bc--]]]]];
    Close[instr];];
bf[program_] := bf[program, ""]


#include <iostream>
#include <fstream>
#include <cmath>

using namespace std;

string readFile (string path) {
    string contents;
    string line;
    ifstream inFile(path);
    while (getline (inFile, line)) {
        contents.append(line);
        contents.append("\n");
    }
    inFile.close();
    return contents;
}

double entropy (string X) {
    const int MAXCHAR = 127;
    int N = X.length();
    int count[MAXCHAR];
    double count_i;
    char ch;
    double sum = 0.0;
    for (int i = 0; i < MAXCHAR; i++) count[i] = 0;
    for (int pos = 0; pos < N; pos++) {
        ch = X[pos];
        count[(int)ch]++;
    }
    for (int n_i = 0; n_i < MAXCHAR; n_i++) {
        count_i = count[n_i];
        if (count_i > 0) sum -= count_i / N * log2(count_i / N);
    }
    return sum;
}

int main () {
    cout<<entropy(readFile("entropy.cpp"));
    return 0;
}


def entropy(s)
  counts = s.chars.each_with_object(Hash(Char, Float64).new(0.0)) { |c, h| h[c] += 1 }
  counts.values.sum do |count|
    freq = count / s.size
    -freq * Math.log2(freq)
  end
end

puts entropy File.read(__FILE__)


void main(in string[] args) {
    import std.stdio, std.algorithm, std.math, std.file;

    auto data = sort(cast(ubyte[])args[0].read);
    return data
           .group
           .map!(g => g[1] / double(data.length))
           .map!(p => -p * p.log2)
           .sum
           .writeln;
}


(define (factorial n)
  (if (= 0 n)
      1
      (* n (factorial (- n 1)))))


import std.stdio, std.process;

void main() {
    auto home = getenv("HOME");
}


program EnvironmentVariable;

{$APPTYPE CONSOLE}

uses SysUtils;

begin
  WriteLn('Temp = ' + GetEnvironmentVariable('TEMP'));
end.


class
    APPLICATION
inherit
    EXECUTION_ENVIRONMENT
create
    make
feature {NONE} -- Initialization
    make
            -- Retrieve and print value for environment variable `USERNAME'.
        do
            print (get ("USERNAME"))
        end
end


sub euler ( &f, $y0, $a, $b, $h ) {
    my $y = $y0;
    my @t_y;
    for $a, * + $h ... * > $b -> $t {
        @t_y[$t] = $y;
        $y += $h * f( $t, $y );
    }
    return @t_y;
}

constant COOLING_RATE = 0.07;
constant AMBIENT_TEMP =   20;
constant INITIAL_TEMP =  100;
constant INITIAL_TIME =    0;
constant FINAL_TIME   =  100;

sub f ( $time, $temp ) {
    return -COOLING_RATE * ( $temp - AMBIENT_TEMP );
}

my @e;
@e[$_] = euler( &f, INITIAL_TEMP, INITIAL_TIME, FINAL_TIME, $_ ) for 2, 5, 10;

say 'Time Analytic   Step2   Step5  Step10     Err2     Err5    Err10';

for INITIAL_TIME, * + 10 ... * >= FINAL_TIME -> $t {

    my $exact = AMBIENT_TEMP + (INITIAL_TEMP - AMBIENT_TEMP)
                              * (-COOLING_RATE * $t).exp;

    my $err = sub { @^a.map: { 100 * abs( $_ - $exact ) / $exact } }

    my ( $a, $b, $c ) = map { @e[$_][$t] }, 2, 5, 10;

    say $t.fmt('%4d '), ( $exact, $a, $b, $c )».fmt(' %7.3f'),
                           $err.([$a, $b, $c])».fmt(' %7.3f%%');
}


       IDENTIFICATION DIVISION.
       PROGRAM-ID. EULER.
       DATA DIVISION.
       FILE SECTION.
       WORKING-STORAGE SECTION.
       1   TABLE-LENGTH CONSTANT 250.
       1   SEARCHING-FLAG     PIC 9.
        88  FINISHED-SEARCHING VALUE IS 1
                               WHEN SET TO FALSE IS 0.
       1  CALC.
        3  A               PIC 999 USAGE COMPUTATIONAL-5.
        3  B               PIC 999 USAGE COMPUTATIONAL-5.
        3  C               PIC 999 USAGE COMPUTATIONAL-5.
        3  D               PIC 999 USAGE COMPUTATIONAL-5.
        3  ABCD            PIC 9(18) USAGE COMPUTATIONAL-5.
        3  FIFTH-ROOT-OFFS PIC 999 USAGE COMPUTATIONAL-5.
        3  POWER-COUNTER   PIC 999 USAGE COMPUTATIONAL-5.
        88 POWER-MAX       VALUE TABLE-LENGTH.

       1   PRETTY.
        3  A               PIC ZZ9.
        3  FILLER          VALUE "^5 + ".
        3  B               PIC ZZ9.
        3  FILLER          VALUE "^5 + ".
        3  C               PIC ZZ9.
        3  FILLER          VALUE "^5 + ".
        3  D               PIC ZZ9.
        3  FILLER          VALUE "^5 = ".
        3  FIFTH-ROOT-OFFS PIC ZZ9.
        3  FILLER          VALUE "^5.".

       1   FIFTH-POWER-TABLE   OCCURS TABLE-LENGTH TIMES
                               ASCENDING KEY IS FIFTH-POWER
                               INDEXED BY POWER-INDEX.
        3  FIFTH-POWER PIC 9(18) USAGE COMPUTATIONAL-5.

       PROCEDURE DIVISION.
       MAIN-PARAGRAPH.
           SET FINISHED-SEARCHING TO FALSE.
           PERFORM POWERS-OF-FIVE-TABLE-INIT.
           PERFORM VARYING
               A IN CALC
               FROM 1 BY 1 UNTIL A IN CALC = TABLE-LENGTH

               AFTER B IN CALC
               FROM 1 BY 1 UNTIL B IN CALC = A IN CALC

               AFTER C IN CALC
               FROM 1 BY 1 UNTIL C IN CALC = B IN CALC

               AFTER D IN CALC
               FROM 1 BY 1 UNTIL D IN CALC = C IN CALC

               IF FINISHED-SEARCHING
                   STOP RUN
               END-IF

               PERFORM POWER-COMPUTATIONS

           END-PERFORM.

       POWER-COMPUTATIONS.

           MOVE ZERO TO ABCD IN CALC.

           ADD FIFTH-POWER(A IN CALC)
               FIFTH-POWER(B IN CALC)
               FIFTH-POWER(C IN CALC)
               FIFTH-POWER(D IN CALC)
                   TO ABCD IN CALC.

           SET POWER-INDEX TO 1.

           SEARCH ALL FIFTH-POWER-TABLE
               WHEN FIFTH-POWER(POWER-INDEX) = ABCD IN CALC
                      MOVE POWER-INDEX TO FIFTH-ROOT-OFFS IN CALC
                      MOVE CORRESPONDING CALC TO PRETTY
                      DISPLAY PRETTY END-DISPLAY
                      SET FINISHED-SEARCHING TO TRUE
           END-SEARCH

           EXIT PARAGRAPH.

       POWERS-OF-FIVE-TABLE-INIT.
           PERFORM VARYING POWER-COUNTER FROM 1 BY 1 UNTIL POWER-MAX
               COMPUTE FIFTH-POWER(POWER-COUNTER) =
                   POWER-COUNTER *
                   POWER-COUNTER *
                   POWER-COUNTER *
                   POWER-COUNTER *
                   POWER-COUNTER
               END-COMPUTE
           END-PERFORM.
           EXIT PARAGRAPH.

       END PROGRAM EULER.


string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ";

string mutate(string data, int rate)
{
    array(int) alphabet=(array(int))chars;
    multiset index = (multiset)enumerate(sizeof(data));
    while(rate)
    {
        int pos = random(index);
        data[pos]=random(alphabet);
        rate--;
    }
    return data;
}

int fitness(string input, string target)
{
    return `+(@`==(((array)input)[*], ((array)target)[*]));
}

void main()
{
    array(string) alphabet = chars/"";
    string target = "METHINKS IT IS LIKE A WEASEL";
    string parent = "";

    while(sizeof(parent) != sizeof(target))
    {
        parent += random(alphabet);
    }

    int count;
    write(" %5d: %s\n", count, parent);
    while (parent != target)
    {
        string child = mutate(parent, 2);
        count++;
        if (fitness(child, target) > fitness(parent, target))
        {
            write(" %5d: %s\n", count, child);
            parent = child;
        }
    }
}


   isOdd  =  logical(bitand(N,1));
   isEven = ~logical(bitand(N,1));


// nanoquery has no function to get just a character
// so we have to implement our own
def get_char()
    c = ""
    while len(c)=0
        c = input()
    end
    return c[0]
end

// a function to handle fatal errors
def fatal_error(errtext)
    println "%" + errtext
    println "usage: " + args[1] + " [filename.bf]"
    exit
end

// get a filename from the command line and read the file in
fname = null
source = null
try
    fname = args[2]
    source = new(Nanoquery.IO.File, fname).readAll()
catch
    fatal_error("error while trying to read from specified file")
end

// start with one hundred cells and the pointer at 0
cells = {0} * 100
ptr   = 0

// loop through the instructions
loc = 0
while loc < len(source)
        instr = source[loc]

        if instr = ">"
                ptr += 1
                if ptr = len(cells)
                        cells.append(0)
                end
        else if instr = "<"
                ptr -= 1
                if ptr < 0
                        ptr = 0
                end
        else if instr = "+"
                cells[ptr] += 1
        else if instr = "-"
                cells[ptr] -= 1
        else if instr = "."
                print chr(cells[ptr])
        else if instr = ","
                cells[ptr] = ord(get_char())
        else if instr = "["
                if cells[ptr] = 0
                        while source[loc] != "]"
                                loc += 1
                        end
                end
        else if instr = "]"
                if cells[ptr] != 0
                        while source[loc] != "["
                                loc -= 1
                        end
                end
        else
                // do nothing
        end

        loc += 1
end


File.open(__ENV__.file, [:read], fn(file) ->
  text = IO.read(file, :all)
  leng = String.length(text)
  String.codepoints(text)
  |> Enum.group_by(&(&1))
  |> Enum.map(fn{_,value} -> length(value) end)
  |> Enum.reduce(0, fn count, entropy ->
       freq = count / leng
       entropy - freq * :math.log2(freq)
     end)
  |> IO.puts
end)


(defun shannon-entropy (input)
  (let ((freq-table (make-hash-table))
	(entropy 0)
	(length (+ (length input) 0.0)))
    (mapcar (lambda (x)
	      (puthash x
		       (+ 1 (gethash x freq-table 0))
		       freq-table))
	    input)
    (maphash (lambda (k v)
	       (set 'entropy (+ entropy
			     (* (/ v length)
				(log (/ v length) 2)))))
	     freq-table)
  (- entropy)))

(defun narcissist ()
  (shannon-entropy (with-temp-buffer
		     (insert-file-contents "U:/rosetta/narcissist.el")
		     (buffer-string))))


#! /usr/bin/escript

-define(LOG2E, 1.44269504088896340735992).

main(_) ->
    Self = escript:script_name(),
    {ok, Contents} = file:read_file(Self),
    io:format("My entropy is ~p~n", [entropy(Contents)]).

entropy(Data) ->
    Frq = count(Data),
    maps:fold(fun(_, C, E) ->
                  P = C / byte_size(Data),
                  E - P*math:log(P)
              end, 0, Frq) * ?LOG2E.

count(Data) -> count(Data, 0, #{}).
count(Data, I, Frq) when I =:= byte_size(Data) -> Frq;
count(Data, I, Frq) ->
    Chr = binary:at(Data, I),
    case Frq of
        #{Chr := K} -> count(Data, I+1, Frq #{Chr := K+1});
        _ -> count(Data, I+1, Frq #{Chr => 1})
    end.


Фун Факт(n)
  f := 1
  для i от 1 до n
        f := f * i
  кц
  Возврат f
Кон Фун


public int factorial_iter(int n){
	result = 1;
	for(i <- [1..n])
		result *= i;
	return result;
}


open System

[<EntryPoint>]
let main args =
    printfn "%A" (Environment.GetEnvironmentVariable("PATH"))
    0


/* REXX ***************************************************************
* 24.05.2013 Walter Pachl  translated from PL/I
**********************************************************************/
  Numeric Digits 100
  T0=100
  Tr=20
  k=0.07

  h=2
  x=t0
  Call head
  do t=0 to 100 by 2
    Select
      When t<=4 | t>=96 Then
        call o x
      When t=8 Then
        Say '...'
      Otherwise
        Nop
      End
    x=x+h*f(x)
    end

  h=5
  y=t0
  Call head
  do t=0 to 100 by 5
    call o y
    y=y+h*f(y)
    end

  h=10
  z=t0
  Call head
  do t=0 to 100 by 10
    call o z
    z=z+h*f(z)
    end
  Exit

f: procedure Expose k Tr
  Parse Arg t
  return -k*(T-Tr)

head:
  Say 'h='h
  Say '  t    By formula       By Euler'
  Return

o:
  Parse Arg v
  Say right(t,3) format(Tr+(T0-Tr)/exp(k*t),5,10) format(v,5,10)
  Return

exp: Procedure
  Parse Arg x,prec
  If prec<9 Then prec=9
  Numeric Digits (2*prec)
  Numeric Fuzz   3
  o=1
  u=1
  r=1
  Do i=1 By 1
    ra=r
    o=o*x
    u=u*i
    r=r+(o/u)
    If r=ra Then Leave
    End
  Numeric Digits (prec)
  r=r+0
  Return r


decimals(3)
see euler("return -0.07*(y-20)", 100, 0, 100, 2) + nl
see euler("return -0.07*(y-20)", 100, 0, 100, 5) + nl
see euler("return -0.07*(y-20)", 100, 0, 100, 10) + nl

func euler df, y, a, b, s
     t = a
     while t <= b
           see "" + t + " " + y + nl
           y += s * eval(df)
           t += s
     end
     return y


(ql:quickload :alexandria)
(let ((fifth-powers (mapcar #'(lambda (x) (expt x 5))
                            (alexandria:iota 250))))
  (loop named outer for x0 from 1 to (length fifth-powers) do
    (loop for x1 from 1 below x0 do
      (loop for x2 from 1 below x1 do
        (loop for x3 from 1 below x2 do
          (let ((x-sum (+ (nth x0 fifth-powers)
                          (nth x1 fifth-powers)
                          (nth x2 fifth-powers)
                          (nth x3 fifth-powers))))
            (if (member x-sum fifth-powers)
                  (return-from outer (list x0 x1 x2 x3 (round (expt x-sum 0.2)))))))))))


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

auto eulersSumOfPowers() {
    enum maxN = 250;
    auto pow5 = iota(size_t(maxN)).map!(i => ulong(i) ^^ 5).array.assumeSorted;

    foreach (immutable x0; 1 .. maxN)
        foreach (immutable x1; 1 .. x0)
            foreach (immutable x2; 1 .. x1)
                foreach (immutable x3; 1 .. x2) {
                    immutable powSum = pow5[x0] + pow5[x1] + pow5[x2] + pow5[x3];
                    if (pow5.contains(powSum))
                        return tuple(x0, x1, x2, x3, pow5.countUntil(powSum));
                }
    assert(false);
}

void main() {
    writefln("%d^5 + %d^5 + %d^5 + %d^5 == %d^5", eulersSumOfPowers[]);
}


use "random"

actor Main
  let _env: Env
  let _rand: MT = MT	// Mersenne Twister
  let _target: String = "METHINKS IT IS LIKE A WEASEL"
  let _possibilities: String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
  let _c: U16 = 100	// number of spawn per generation
  let _min_mutate_rate: F64 = 0.09
  let _perfect_fitness: USize = _target.size()
  var _parent: String = ""

  new create(env: Env) =>
    _env = env
    _parent = mutate(_target, 1.0)
    var iter: U64 = 0
    while not _target.eq(_parent) do
      let rate: F64 = new_mutate_rate()
      iter = iter + 1
      if (iter % 100) == 0 then
        _env.out.write(iter.string() + ": " + _parent)
        _env.out.write(", fitness: " + fitness(_parent).string())
        _env.out.print(", rate: " + rate.string())
      end
      var best_spawn = ""
      var best_fit: USize = 0
      var i: U16 = 0
      while i < _c do
        let spawn = mutate(_parent, rate)
        let spawn_fitness = fitness(spawn)
        if spawn_fitness > best_fit then
          best_spawn = spawn
          best_fit = spawn_fitness
        end
        i = i + 1
      end
      if best_fit > fitness(_parent) then
        _parent = best_spawn
      end
    end
    _env.out.print(_parent + ", " + iter.string())

  fun fitness(trial: String): USize =>
    var ret_val: USize = 0
    var i: USize = 0
    while i < trial.size() do
      try
        if trial(i)? == _target(i)? then
          ret_val = ret_val + 1
        end
      end
      i = i + 1
    end
    ret_val

  fun new_mutate_rate(): F64 =>
    let perfect_fit = _perfect_fitness.f64()
    ((perfect_fit - fitness(_parent).f64()) / perfect_fit) * (1.0 - _min_mutate_rate)

  fun ref mutate(parent: String box, rate: F64): String =>
    var ret_val = recover trn String end
    for char in parent.values() do
      let rnd_real: F64 = _rand.real()
      if rnd_real <= rate then
        let rnd_int: U64 = _rand.int(_possibilities.size().u64())
        try
          ret_val.push(_possibilities(rnd_int.usize())?)
        end
      else
        ret_val.push(char)
      end
    end
    consume ret_val


target("METHINKS IT IS LIKE A WEASEL").

rndAlpha(64, 32).     % Generate a single random character
rndAlpha(P, P).	      % 32 is a space, and 65->90 are upper case
rndAlpha(Ch) :- random(N), P is truncate(64+(N*27)), !, rndAlpha(P, Ch).

rndTxt(0, []).        % Generate some random text (fixed length)
rndTxt(Len, [H|T]) :- succ(L, Len), rndAlpha(H), !, rndTxt(L, T).

score([], [], Score, Score).   % Score a generated mutation (count diffs)
score([Ht|Tt], [Ht|Tp], C, Score) :- !, score(Tt, Tp, C, Score).
score([_|Tt], [_|Tp], C, Score) :- succ(C, N), !, score(Tt, Tp, N, Score).
score(Txt, Score, Target) :- !, score(Target, Txt, 0, Score).

mutate(_, [], []).             % mutate(Probability, Input, Output)
mutate(P, [H|Txt], [H|Mut]) :- random(R), R < P, !, mutate(P, Txt, Mut).
mutate(P, [_|Txt], [M|Mut]) :- rndAlpha(M), !, mutate(P, Txt, Mut).

weasel(Tries, _, _, mutation(0, Result)) :-               % No differences=success
	format('~w~4|:~w~3| - ~s\n', [Tries, 0, Result]).
weasel(Tries, Chance, Target, mutation(S, Value)) :-	    % output progress
	format('~w~4|:~w~3| - ~s\n', [Tries, S, Value]), !, % and call again
	weasel(Tries, Chance, Target, Value).
weasel(Tries, Chance, Target, Start) :-
	findall(mutation(S,M),  % Generate 30 mutations, select the best.
		(between(1, 30, _), mutate(Chance, Start, M), score(M,S,Target)),
		Mutations),     % List of 30 mutations and their scores
	sort(Mutations, [Best|_]), succ(Tries, N),
	!, weasel(N, Chance, Target, Best).
weasel :-  % Chance->probability for a mutation, T=Target, Start=initial text
	target(T), length(T, Len), rndTxt(Len, Start), Chance is 1 - (1/(Len+1)),
	!, weasel(0, Chance, T, Start).


-- MAXScript : Even or Odd : N.H. 2019
-- Open the MAXScript Listener for input and output
userInt = getKBValue prompt:"Enter an integer and i will tell you if its Even or Odd : "
if classOf userInt != Integer then print "The value you enter must be an integer"
else if (Mod userInt 2) == 0 Then Print "Your number is even"
else Print "Your number is odd"


even(N)  % in a body, suceeeds iff N is even.
odd(N).  % in a body, succeeds iff N is odd.

% rolling our own:
:- pred even(int::in) is semidet.

% It's an error to have all three in one module, mind; even/1 would fail to check as semidet.
even(N) :- N mod 2 = 0.   % using division that truncates towards -infinity
even(N) :- N rem 2 = 0.   % using division that truncates towards zero
even(N) :- N /\ 1 = 0.    % using bit-wise and.


REPORT equilibrium_index.

TYPES: y_i TYPE STANDARD TABLE OF i WITH EMPTY KEY.

cl_demo_output=>display( REDUCE y_i( LET sequences = VALUE y_i( ( -7 ) ( 1 ) ( 5 ) ( 2 ) ( -4 ) ( 3 ) ( 0 ) )
                                         total_sum = REDUCE #( INIT sum = 0
                                                                FOR sequence IN sequences
                                                               NEXT sum = sum + ( sequence ) ) IN
                                      INIT x = VALUE y_i( )
                                           y = 0
                                       FOR i = 1 UNTIL i > lines( sequences )
                                       LET z = sequences[ i ] IN
                                      NEXT x = COND #( WHEN y = ( total_sum - y - z ) THEN VALUE y_i( BASE x ( i - 1 ) ) ELSE x )
                                           y = y + z ) ).


PROC PrintArray(INT ARRAY a INT size)
  INT i

  Put('[)
  FOR i=0 TO size-1
  DO
    IF i>0 THEN Put(' ) FI
    PrintI(a(i))
  OD
  Put(']) PutE()
RETURN

INT FUNC SumRange(INT ARRAY a INT first,last)
  INT sum
  INT i

  sum=0
  FOR i=first TO last
  DO
    sum==+a(i)
  OD
RETURN(sum)

PROC EquilibriumIndices(INT ARRAY a INT size
     INT ARRAY indices INT POINTER indSize)
  INT i,left,right

  indSize^=0
  FOR i=0 TO size-1
  DO
    left=SumRange(a,0,i-1)
    right=SumRange(a,i+1,size-1)
    IF left=right THEN
      indices(indSize^)=i
      indSize^==+1
    FI
  OD
RETURN

PROC Test(INT ARRAY a INT size)
  INT ARRAY indices(100)
  INT indSize

  EquilibriumIndices(a,size,indices,@indSize)
  Print("Array=") PrintArray(a,size)
  Print("Equilibrium indices=") PrintArray(indices,indSize)
  PutE()
RETURN

PROC Main()
  INT ARRAY a=[65529 1 5 2 65532 3 0]
  INT ARRAY b=[65535 1 65535 1 65535 1 65535]
  INT ARRAY c=[1 2 3 4 5 6 7 8 9]
  INT ARRAY d=[0]

  Test(a,7)
  Test(b,7)
  Test(c,9)
  Test(d,1)
RETURN


Function Fibonacci(n)
   x = 0
   y = 1
   i = 0
   n = ABS(n)
   If n < 2 Then
   Fibonacci = n
   Else
   Do Until (i = n)
      sum = x+y
      x=y
      y=sum
      i=i+1
   Loop
   Fibonacci = x
   End If

End Function


record BFI
{
    cmd : char;
    next : BFI;
    jmp : BFI;
}

record MEM
{
    val : int;
    next : MEM;
    prev : MEM;
}

func compile(prog : string) -> BFI
{
    var i = 0;
    var n = BFI;
    var p = BFI;
    var j = BFI;
    var pgm = BFI;

    for (i = 0; i < length(prog); i = i + 1) {
        n = BFI('0', nil, nil);

        if (p != nil) {
            p.next = n
        } else {
            pgm = n
        };

        n.cmd = prog[i];
        p = n;

        if (prog[i] == '[') {
            n.jmp = j;
            j = n;
            0
        } else if (prog[i] == ']') {
            n.jmp = j;
            j = j.jmp;
            n.jmp.jmp = n;
            0
        } else {
            0
        }
    };

    pgm
}

func exec(pgm : BFI) -> int
{
    var m = MEM(0, nil, nil);
    var n = BFI;

    for (n = pgm; n != nil; n = n.next) {
        if (n.cmd == '+') {
            m.val = m.val + 1
        } else if (n.cmd == '-') {
            m.val = m.val - 1
        } else if (n.cmd == '.') {
            printc(chr(m.val));
            0
        } else if (n.cmd == ',') {
            m.val = read()
        } else if (n.cmd == '[') {
            if (m.val == 0) {
                n = n.jmp;
                0
            } else {
                0
            }
        } else if (n.cmd == ']') {
            if (m.val != 0) {
                n = n.jmp;
                0
            } else {
                0
            }
        } else if (n.cmd == '<') {
            m = m.prev;
            0
        } else if (n.cmd == '>') {
            if (m.next == nil) {
                m.next = MEM(0, nil, nil);
                m.next.prev = m;
                0
            } else {
                0
            };

            m = m.next;
            0
        } else {
            0
        }
    };

    0
}

func run(prog : string) -> int
{
    var pgm = BFI;

    pgm = compile(prog);
    exec(pgm);

    0
}

func main() -> int
{
    /* Hello World! */
    run("++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.");
    0
}