# The factors, sorted
def factors:
  . as $num
  | reduce range(1; 1 + sqrt|floor) as $i
      ([];
       if ($num % $i) == 0 then
         ($num / $i) as $r
         | if $i == $r then . + [$i] else . + [$i, $r] end
       else .
       end
       | sort) ;

# If the input is a sorted array of distinct non-negative integers,
# then the output will be a stream of [$x,$y] arrays,
# where $x and $y are non-empty arrays that partition the
# input, and where ($x|add) == $sum.
# If [$x,$y] is emitted, then [$y,$x] will not also be emitted.
# The items in $x appear in the same order as in the input, and similarly
# for $y.
#
def distinct_partitions($sum):
  # input: [$array, $n, $lim] where $n>0
  # output: a stream of arrays, $a, each with $n distinct items from $array,
  #         preserving the order in $array, and such that
  #         add == $lim
  def p:
     . as [$in, $n, $lim]
     | if $n==1  # this condition is very common so it saves time to check early on
       then ($in | bsearch($lim)) as $ix
       | if $ix < 0 then empty
         else [$lim]
         end
       else ($in|length) as $length
       | if $length <= $n then empty
         elif $length==$n            then $in | select(add == $lim)
         elif ($in[-$n:]|add) < $lim then empty
         else  ($in[:$n]|add) as $rsum
         | if $rsum > $lim      then empty
           elif $rsum == $lim   then "amazing" | debug | $in[:$n]
           else range(0; 1 + $length - $n) as $i
           | [$in[$i]] + ([$in[$i+1:], $n-1, $lim - $in[$i]]|p)
           end
         end
       end;

  range(1; (1+length)/2) as $i
  | ([., $i, $sum]|p) as $pi
  | [ $pi, (. - $pi)]
  | select( if (.[0]|length) == (.[1]|length) then (.[0] < .[1]) else true end) #1
  ;

def zumkellerPartitions:
  factors
  | add as $sum
  | if $sum % 2 == 1 then empty
    else distinct_partitions($sum / 2)
    end;

def is_zumkeller:
  first(factors
        | add as $sum
        | if $sum % 2 == 1 then empty
          else distinct_partitions($sum / 2)
	  | select( (.[0]|add) == (.[1]|add)) // ("internal error: \(.)" | debug | empty)  #2
	  end
	| true)
  // false;


using Primes

function factorize(n)
    f = [one(n)]
    for (p, x) in factor(n)
        f = reduce(vcat, [f*p^i for i in 1:x], init=f)
    end
    f
end

function cansum(goal, list)
    if goal == 0 || list[1] == goal
         return true
    elseif length(list) > 1
        if list[1] > goal
            return cansum(goal, list[2:end])
        else
            return cansum(goal - list[1], list[2:end]) ||  cansum(goal, list[2:end])
        end
    end
    return false
end

function iszumkeller(n)
    f = reverse(factorize(n))
    fsum = sum(f)
    return iseven(fsum) && cansum(div(fsum, 2) - f[1], f[2:end])
end

function printconditionalnum(condition, maxcount, numperline = 20)
    count, spacing = 1, div(80, numperline)
    for i in 1:typemax(Int)
        if condition(i)
            count += 1
            print(rpad(i, spacing), (count - 1) % numperline == 0 ? "\n" : "")
            if count > maxcount
                return
            end
        end
    end
end

println("First 220 Zumkeller numbers:")
printconditionalnum(iszumkeller, 220)
println("\n\nFirst 40 odd Zumkeller numbers:")
printconditionalnum((n) -> isodd(n) && iszumkeller(n), 40, 8)
println("\n\nFirst 40 odd Zumkeller numbers not ending with 5:")
printconditionalnum((n) -> isodd(n) && (string(n)[end] != '5') && iszumkeller(n), 40, 8)


Public Sub Main()
Dim cList As Collection = ["2": "quick", "4": "fox", "1": "The", "9": "dog", "7": "the", "5": "jumped", "3": "brown", "6": "over", "8": "lazy"]
Dim siCount As Short
Dim sTemp As String

For Each sTemp In cList
  Print cList.key & "=" & sTemp;;
Next

Print

For siCount = 1 To cList.Count
  Print cList[Str(siCount)];;
Next

End


myMap := map[string]int {
	   "hello": 13,
	   "world": 31,
	   "!"    : 71 }

// iterating over key-value pairs:
for key, value := range myMap {
    fmt.Printf("key = %s, value = %d\n", key, value)
}

// iterating over keys:
for key := range myMap {
    fmt.Printf("key = %s\n", key)
}

// iterating over values:
for _, value := range myMap {
    fmt.Printf("value = %d\n", value)
}


100[$][0^:1-]#                                                  {initialize doors}
%
[s;[$101<][$$;~\:s;+]#%]d:                                     {function d, switch door state function}
1s:[s;101<][d;!s;1+s:]#                                        {increment step width from 1 to 100, execute function d each time}
1[$101<][$$.' ,;['o,'p,'e,'n,10,]['c,'l,'o,'s,'e,'d,10,]?1+]#  {loop through doors, print door number and state}


:- module zero_to_the_zero_power.
:- interface.

:- import_module io.

:- pred main(io::di, io::uo) is det.

:- implementation.

:- import_module float, int, integer, list, string.

main(!IO) :-
   io.format("    int.pow(0, 0) = %d\n", [i(pow(0, 0))], !IO),
   io.format("integer.pow(zero, zero) = %s\n",
        [s(to_string(pow(zero, zero)))], !IO),
   io.format("  float.pow(0.0, 0) = %.1f\n", [f(pow(0.0, 0))], !IO).

:- end_module zero_to_the_zero_power.


begin
    % procedure to find the mean of the elements of a vector.                %
    % As the procedure can't find the bounds of the array for itself,        %
    % we pass them in lb and ub          %
    real procedure mean ( real    array vector ( * )
                        ; integer value lb
                        ; integer value ub
                        ) ;
    begin
        real sum;
        assert( ub > lb ); % terminate the program if there are no elements  %
        sum := 0;
        for i := lb until ub do sum := sum + vector( i );
        sum / ( ( ub + 1 ) - lb )
    end mean ;

    % test the mean procedure by finding the mean of 1.1, 2.2, 3.3, 4.4, 5.5 %
    real array numbers ( 1 :: 5 );
    for i := 1 until 5 do numbers( i ) := i + ( i / 10 );
    r_format := "A"; r_w := 10; r_d := 2; % set fixed point output           %
    write( mean( numbers, 1, 5 ) );
end.


PROC mean(l:PTR TO LONG)
  DEF m, i, ll
  ll := ListLen(l)
  IF ll = 0 THEN RETURN 0.0
  m := 0.0
  FOR i := 0 TO ll-1 DO m := !m + l[i]
  m := !m / (ll!)
ENDPROC m

PROC main()
  DEF s[20] : STRING
  WriteF('mean \s\n',
         RealF(s,mean([1.0, 2.0, 3.0, 4.0, 5.0]), 2))
ENDPROC


import java.util.ArrayList
import kotlin.math.sqrt

object ZumkellerNumbers {
    @JvmStatic
    fun main(args: Array<String>) {
        var n = 1
        println("First 220 Zumkeller numbers:")
        run {
            var count = 1
            while (count <= 220) {
                if (isZumkeller(n)) {
                    print("%3d  ".format(n))
                    if (count % 20 == 0) {
                        println()
                    }
                    count++
                }
                n += 1
            }
        }

        n = 1
        println("\nFirst 40 odd Zumkeller numbers:")
        run {
            var count = 1
            while (count <= 40) {
                if (isZumkeller(n)) {
                    print("%6d".format(n))
                    if (count % 10 == 0) {
                        println()
                    }
                    count++
                }
                n += 2
            }
        }

        n = 1
        println("\nFirst 40 odd Zumkeller numbers that do not end in a 5:")
        var count = 1
        while (count <= 40) {
            if (n % 5 != 0 && isZumkeller(n)) {
                print("%8d".format(n))
                if (count % 10 == 0) {
                    println()
                }
                count++
            }
            n += 2
        }
    }

    private fun isZumkeller(n: Int): Boolean { //  numbers congruent to 6 or 12 modulo 18 are Zumkeller numbers
        if (n % 18 == 6 || n % 18 == 12) {
            return true
        }
        val divisors = getDivisors(n)
        val divisorSum = divisors.stream().mapToInt { i: Int? -> i!! }.sum()
        //  divisor sum cannot be odd
        if (divisorSum % 2 == 1) {
            return false
        }
        // numbers where n is odd and the abundance is even are Zumkeller numbers
        val abundance = divisorSum - 2 * n
        if (n % 2 == 1 && abundance > 0 && abundance % 2 == 0) {
            return true
        }
        divisors.sort()
        val j = divisors.size - 1
        val sum = divisorSum / 2
        //  Largest divisor larger than sum - then cannot partition and not Zumkeller number
        return if (divisors[j] > sum) false else canPartition(j, divisors, sum, IntArray(2))
    }

    private fun canPartition(j: Int, divisors: List<Int>, sum: Int, buckets: IntArray): Boolean {
        if (j < 0) {
            return true
        }
        for (i in 0..1) {
            if (buckets[i] + divisors[j] <= sum) {
                buckets[i] += divisors[j]
                if (canPartition(j - 1, divisors, sum, buckets)) {
                    return true
                }
                buckets[i] -= divisors[j]
            }
            if (buckets[i] == 0) {
                break
            }
        }
        return false
    }

    private fun getDivisors(number: Int): MutableList<Int> {
        val divisors: MutableList<Int> = ArrayList()
        val sqrt = sqrt(number.toDouble()).toLong()
        for (i in 1..sqrt) {
            if (number % i == 0L) {
                divisors.add(i.toInt())
                val div = (number / i).toInt()
                if (div.toLong() != i) {
                    divisors.add(div)
                }
            }
        }
        return divisors
    }
}


def map = [lastName: "Anderson", firstName: "Thomas", nickname: "Neo", age: 24, address: "everywhere"]

println "Entries:"
map.each { println it }

println()
println "Keys:"
map.keySet().each { println it }

println()
println "Values:"
map.values().each { println it }


LOCAL arr := { 6 => 16, "eight" => 8, "eleven" => 11 }
LOCAL x

FOR EACH x IN arr
   // key, value
   ? x:__enumKey(), x
   // or key only
   ? x:__enumKey()
   // or value only
   ? x
NEXT


var doors : array [1..100] of Boolean;
var i, j : Integer;

for i := 1 to 100 do
   for j := i to 100 do
      if (j mod i) = 0 then
         doors[j] := not doors[j];F

for i := 1 to 100 do
   if doors[i] then
      PrintLn('Door '+IntToStr(i)+' is open');


print "The result of zero to the zero power is " + 0^0


/**
 Zero to the zeroth power, in Neko
*/

var math_pow = $loader.loadprim("[email protected]_pow", 2)

$print(math_pow(0, 0), "\n")


on average(listOfNumbers)
    set len to (count listOfNumbers)
    if (len is 0) then return missing value

    set sum to 0
    repeat with thisNumber in listOfNumbers
        set sum to sum + thisNumber
    end repeat

    return sum / len
end average

average({2500, 2700, 2400, 2300, 2550, 2650, 2750, 2450, 2600, 2400})


REM COLLECTION IN DATA STATEMENTS, EMPTY DATA IS THE END OF THE COLLECTION
    0 READ V$
    1 IF LEN(V$) = 0 THEN END
    2 N = 0
    3 S = 0
    4 FOR I = 0 TO 1 STEP 0
    5     S = S + VAL(V$)
    6     N = N + 1
    7     READ V$
    8     IF LEN(V$) THEN NEXT
    9 PRINT S / N
10000 DATA1,2,2.718,3,3.142
63999 DATA

REM COLLECTION IN AN ARRAY, ITEM 0 IS THE SIZE OF THE COLLECTION
A(0) = 5 : A(1) = 1 : A(2) = 2 : A(3) = 2.718 : A(4) = 3 : A(5) = 3.142
N = A(0) : IF N THEN S = 0 : FOR I = 1 TO N : S = S + A(I) : NEXT : ? S / N


import std

// Derived from Julia and Python versions

def get_divisors(n: int) -> [int]:
    var i = 2
    let d = [1, n]
    let limit = sqrt(n)
    while i <= limit:
        if n % i == 0:
            let j = n / i
            push(d,i)
            if i != j:
                push(d,j)
        i += 1
    return d

def isPartSum(divs: [int], sum: int) -> bool:
    if sum == 0:
        return true
    let len = length(divs)
    if len == 0:
        return false
    let last = pop(divs)
    if last > sum:
        return isPartSum(divs, sum)
    return isPartSum(copy(divs), sum) or isPartSum(divs, sum-last)

def isZumkeller(n: int) -> bool:
    let divs = get_divisors(n)
    let sum = fold(divs, 0): _a+_b
    if sum % 2 == 1:
        // if sum is odd can't be split into two partitions with equal sums
        return false
    if n % 2 == 1:
        // if n is odd use 'abundant odd number' optimization
        let abundance = sum - 2 * n
        return abundance > 0 and abundance % 2 == 0
    return isPartSum(divs, sum/2)

def printZumkellers(q: int, oddonly: bool):
    var nprinted = 0
    var res = ""
    for(100000) n:
        if (!oddonly or n % 2 != 0):
            if isZumkeller(n):
                let s = string(n)
                let z = length(s)
                res = concat_string([res, repeat_string(" ",8-z), s], "")
                nprinted += 1
                if nprinted % 10 == 0 or nprinted >= q:
                    print res
                    res = ""
                    if nprinted >= q:
                        return

print "220 Zumkeller numbers:"
printZumkellers(220, false)
print "\n\n40 odd Zumkeller numbers:"
printZumkellers(40, true)


ClearAll[ZumkellerQ]
ZumkellerQ[n_] := Module[{d = Divisors[n], t, ds, x},
   ds = Total[d];
   If[Mod[ds, 2] == 1,
    False
    ,
    t = CoefficientList[Product[1 + x^i, {i, d}], x];
    t[[1 + ds/2]] > 0
    ]
   ];
i = 1;
res = {};
While[Length[res] < 220,
  r = ZumkellerQ[i];
  If[r, AppendTo[res, i]];
  i++;
  ];
res

i = 1;
res = {};
While[Length[res] < 40,
  r = ZumkellerQ[i];
  If[r, AppendTo[res, i]];
  i += 2;
  ];
res


import qualified Data.Map as M

myMap :: M.Map String Int
myMap = M.fromList [("hello", 13), ("world", 31), ("!", 71)]

main :: IO ()
main =
  (putStrLn . unlines) $
  [ show . M.toList     -- Pairs
  , show . M.keys       -- Keys
  , show . M.elems      -- Values
  ] <*>
  pure myMap


procedure main()
    t := table()
    every t[a := !"ABCDE"] := map(a)

    every pair := !sort(t) do
        write("\t",pair[1]," -> ",pair[2])

    writes("Keys:")
    every writes(" ",key(t))
    write()

    writes("Values:")
    every writes(" ",!t)
    write()
end


var doors = Array.Empty(100, false)

for p in 0..99 {
    for d in 0..99 {
        if (d + 1) % (p + 1) == 0 {
            doors[d] = !doors[d];
        }
    }
}

for d in doors.Indices() when doors[d] {
    print("Door \(d+1): Open")
}


import math

echo pow(0.0, 0.0)  # Floating point exponentiation.
echo 0 ^ 0          # Integer exponentiation.


# 0.0 ** 0.0;;
- : float = 1.
# Complex.pow Complex.zero Complex.zero;;
- : Complex.t = {Complex.re = nan; Complex.im = nan}
# #load "nums.cma";;
# open Num;;
# Int 0 **/ Int 0;;
- : Num.num = Int 1


i = 10
Loop, % i {
  Random, v, -3.141592, 3.141592
  list .= v "`n"
  sum += v
}
MsgBox, % i ? list "`nmean: " sum/i:0


import math, strutils

template isEven(n: int): bool = (n and 1) == 0
template isOdd(n: int): bool = (n and 1) != 0

func getDivisors(n: int): seq[int] =
  result = @[1, n]
  for i in 2..sqrt(n.toFloat).int:
    if n mod i == 0:
      let j = n div i
      result.add i
      if i != j: result.add j

func isPartSum(divs: seq[int]; sum: int): bool =
  if sum == 0: return true
  if divs.len == 0: return false
  let last = divs[^1]
  let divs = divs[0..^2]
  result = isPartSum(divs, sum)
  if not result and last <= sum:
    result = isPartSum(divs, sum - last)

func isZumkeller(n: int): bool =
  let divs = n.getDivisors()
  let sum = sum(divs)
  # If "sum" is odd, it can't be split into two partitions with equal sums.
  if sum.isOdd: return false
  # If "n" is odd use "abundant odd number" optimization.
  if n.isOdd:
    let abundance = sum - 2 * n
    return abundance > 0 and abundance.isEven
  # If "n" and "sum" are both even, check if there's a partition which totals "sum / 2".
  result = isPartSum(divs, sum div 2)

when isMainModule:

  echo "The first 220 Zumkeller numbers are:"
  var n = 2
  var count = 0
  while count < 220:
    if n.isZumkeller:
      stdout.write align($n, 3)
      inc count
      stdout.write if count mod 20 == 0: '\n' else: ' '
    inc n
  echo()

  echo "The first 40 odd Zumkeller numbers are:"
  n = 3
  count = 0
  while count < 40:
    if n.isZumkeller:
      stdout.write align($n, 5)
      inc count
      stdout.write if count mod 10 == 0: '\n' else: ' '
    inc n, 2
  echo()

  echo "The first 40 odd Zumkeller numbers which don't end in 5 are:"
  n = 3
  count = 0
  while count < 40:
    if n mod 10 != 5 and n.isZumkeller:
      stdout.write align($n, 7)
      inc count
      stdout.write if count mod 8 == 0: '\n' else: ' '
    inc n, 2


program zumkeller;
//https://oeis.org/A083206/a083206.txt
{$IFDEF FPC}
  {$MODE DELPHI}  {$OPTIMIZATION ON,ALL}  {$COPERATORS ON}
//  {$O+,I+}
{$ELSE}
  {$APPTYPE CONSOLE}
{$ENDIF}
uses
  sysutils
{$IFDEF WINDOWS},Windows{$ENDIF}
  ;
//######################################################################
//prime decomposition
const
//HCN(86) > 1.2E11 = 128,501,493,120     count of divs = 4096   7 3 1 1 1 1 1 1 1
  HCN_DivCnt  = 4096;
//stop never ending recursion
  RECCOUNTMAX = 100*1000*1000;
  DELTAMAX    = 1000*1000;
type
  tItem     = Uint64;
  tDivisors = array [0..HCN_DivCnt-1] of tItem;
  tpDivisor = pUint64;
const
  SizePrDeFe = 12697;//*72 <= 1 or 2 Mb ~ level 2 cache -32kB for DIVS
type
  tdigits    = packed record
                 dgtDgts : array [0..31] of Uint32;
               end;

  //the first number with 11 different divisors =
  // 2*3*5*7*11*13*17*19*23*29*31 = 2E11
  tprimeFac = packed record
                 pfSumOfDivs,
                 pfRemain  : Uint64;  //n div (p[0]^[pPot[0] *...) can handle primes <=821641^2 = 6.7e11
                 pfpotPrim : array[0..9] of UInt32;//+10*4 = 56 Byte
                 pfpotMax  : array[0..9] of byte;  //10  = 66
                 pfMaxIdx  : Uint16; //68
                 pfDivCnt  : Uint32; //72
               end;

  tPrimeDecompField = array[0..SizePrDeFe-1] of tprimeFac;
  tPrimes = array[0..65535] of Uint32;

var
  SmallPrimes: tPrimes;
//######################################################################
//prime decomposition
procedure InitSmallPrimes;
//only odd numbers
const
  MAXLIMIT = (821641-1) shr 1;
var
  pr : array[0..MAXLIMIT] of byte;
  p,j,d,flipflop :NativeUInt;
Begin
  SmallPrimes[0] := 2;
  fillchar(pr[0],SizeOf(pr),#0);
  p := 0;
  repeat
    repeat
      p +=1
    until pr[p]= 0;
    j := (p+1)*p*2;
    if j>MAXLIMIT then
      BREAK;
    d := 2*p+1;
    repeat
      pr[j] := 1;
      j += d;
    until j>MAXLIMIT;
  until false;

  SmallPrimes[1] := 3;
  SmallPrimes[2] := 5;
  j := 3;
  d := 7;
  flipflop := 3-1;
  p := 3;
  repeat
    if pr[p] = 0 then
    begin
      SmallPrimes[j] := d;
      inc(j);
    end;
    d += 2*flipflop;
    p+=flipflop;
    flipflop := 3-flipflop;
  until (p > MAXLIMIT) OR (j>High(SmallPrimes));
end;

function OutPots(const pD:tprimeFac;n:NativeInt):Ansistring;
var
  s: String[31];
Begin
  str(n,s);
  result := s+' :';
  with pd do
  begin
    str(pfDivCnt:3,s);
    result += s+' : ';
    For n := 0 to pfMaxIdx-1 do
    Begin
      if n>0 then
        result += '*';
      str(pFpotPrim[n],s);
      result += s;
      if pfpotMax[n] >1 then
      Begin
        str(pfpotMax[n],s);
        result += '^'+s;
      end;
    end;
    If pfRemain >1 then
    Begin
      str(pfRemain,s);
      result += '*'+s;
    end;
    str(pfSumOfDivs,s);
    result += '_SoD_'+s+'<';
  end;
end;

function CnvtoBASE(var dgt:tDigits;n:Uint64;base:NativeUint):NativeInt;
//n must be multiple of base
var
  q,r: Uint64;
  i : NativeInt;
Begin
  with dgt do
  Begin
    fillchar(dgtDgts,SizeOf(dgtDgts),#0);
    i := 0;
//    dgtNum:= n;
    n := n div base;
    result := 0;
    repeat
      r := n;
      q := n div base;
      r  -= q*base;
      n := q;
      dgtDgts[i] := r;
      inc(i);
    until (q = 0);

    result := 0;
    while (result<i) AND (dgtDgts[result] = 0) do
      inc(result);
    inc(result);
  end;
end;

function IncByBaseInBase(var dgt:tDigits;base:NativeInt):NativeInt;
var
  q :NativeInt;
Begin
  with dgt do
  Begin
    result := 0;
    q := dgtDgts[result]+1;
//    inc(dgtNum,base);
    if q = base then
    begin
      repeat
        dgtDgts[result] := 0;
        inc(result);
        q := dgtDgts[result]+1;
      until q <> base;
    end;
    dgtDgts[result] := q;
    result +=1;
  end;
end;

procedure SieveOneSieve(var pdf:tPrimeDecompField;n:nativeUInt);
var
  dgt:tDigits;
  i, j, k,pr,fac : NativeUInt;
begin
  //init
  for i := 0 to High(pdf) do
    with pdf[i] do
    Begin
      pfDivCnt := 1;
      pfSumOfDivs := 1;
      pfRemain := n+i;
      pfMaxIdx := 0;
    end;

  //first 2 make n+i even
  i := n AND 1;
  repeat
    with pdf[i] do
      if n+i > 0 then
      begin
        j := BsfQWord(n+i);
        pfMaxIdx := 1;
        pfpotPrim[0] := 2;
        pfpotMax[0] := j;
        pfRemain := (n+i) shr j;
        pfSumOfDivs := (1 shl (j+1))-1;
        pfDivCnt := j+1;
      end;
    i += 2;
  until i >High(pdf);

  // i now index in SmallPrimes
  i := 0;
  repeat
    //search next prime that is in bounds of sieve
    repeat
      inc(i);
      if i >= High(SmallPrimes) then
        BREAK;
      pr := SmallPrimes[i];
      k := pr-n MOD pr;
      if (k = pr) AND (n>0) then
        k:= 0;
      if k < SizePrDeFe then
        break;
    until false;
    if i >= High(SmallPrimes) then
      BREAK;
    //no need to use higher primes
    if pr*pr > n+SizePrDeFe then
      BREAK;

    // j is power of prime
    j := CnvtoBASE(dgt,n+k,pr);
    repeat
      with pdf[k] do
      Begin
        pfpotPrim[pfMaxIdx] := pr;
        pfpotMax[pfMaxIdx] := j;
        pfDivCnt *= j+1;
        fac := pr;
        repeat
          pfRemain := pfRemain DIV pr;
          dec(j);
          fac *= pr;
        until j<= 0;
        pfSumOfDivs *= (fac-1)DIV(pr-1);
        inc(pfMaxIdx);
      end;
      k += pr;
      j := IncByBaseInBase(dgt,pr);
    until k >= SizePrDeFe;
  until false;

  //correct sum of & count of divisors
  for i := 0 to High(pdf) do
  Begin
    with pdf[i] do
    begin
      j := pfRemain;
      if j <> 1 then
      begin
        pfSumOFDivs *= (j+1);
        pfDivCnt *=2;
      end;
    end;
  end;
end;
//prime decomposition
//######################################################################
procedure Init_Check_rec(const pD:tprimeFac;var Divs,SumOfDivs:tDivisors);forward;

var
{$ALIGN 32}
  PrimeDecompField:tPrimeDecompField;
{$ALIGN 32}
  Divs :tDivisors;
  SumOfDivs : tDivisors;
  DivUsedIdx : tDivisors;

  pDiv :tpDivisor;
  T0: Int64;
  count,rec_Cnt: NativeInt;
  depth : Int32;
  finished :Boolean;

procedure Check_rek_depth(SoD : Int64;i: NativeInt);
var
  sum : Int64;
begin
  if finished then
    EXIT;
  inc(rec_Cnt);

  WHILE (i>0) AND (pDiv[i]>SoD) do
    dec(i);

  while i >= 0 do
  Begin
    DivUsedIdx[depth] := pDiv[i];
    sum := SoD-pDiv[i];
    if sum = 0 then
    begin
      finished := true;
      EXIT;
    end;
    dec(i);
    inc(depth);
    if (i>= 0) AND (sum <= SumOfDivs[i]) then
      Check_rek_depth(sum,i);
    if finished then
      EXIT;
//  DivUsedIdx[depth] := 0;
    dec(depth);
  end;
end;

procedure Out_One_Sol(const pd:tprimefac;n:NativeUInt;isZK : Boolean);
var
  sum : NativeInt;
Begin
  if n< 7 then
    exit;
  with pd do
  begin
    writeln(OutPots(pD,n));
    if isZK then
    Begin
      Init_Check_rec(pD,Divs,SumOfDivs);
      Check_rek_depth(pfSumOfDivs shr 1-n,pFDivCnt-1);
      write(pfSumOfDivs shr 1:10,' = ');
      sum := n;
      while depth >= 0 do
      Begin
        sum += DivUsedIdx[depth];
        write(DivUsedIdx[depth],'+');
        dec(depth);
      end;
      write(n,' =  ',sum);
    end
    else
      write(' no zumkeller ');
  end;
end;

procedure InsertSort(pDiv:tpDivisor; Left, Right : NativeInt );
var
  I, J: NativeInt;
  Pivot : tItem;
begin
  for i:= 1 + Left to Right do
  begin
    Pivot:= pDiv[i];
    j:= i - 1;
    while (j >= Left) and (pDiv[j] > Pivot) do
    begin
      pDiv[j+1]:=pDiv[j];
      Dec(j);
    end;
    pDiv[j+1]:= pivot;
  end;
end;

procedure GetDivs(const pD:tprimeFac;var Divs,SumOfDivs:tDivisors);
var
  pDivs : tpDivisor;
  pPot : UInt64;
  i,len,j,l,p,k: Int32;
Begin
  i := pD.pfDivCnt;
  pDivs := @Divs[0];
  pDivs[0] := 1;
  len := 1;
  l   := 1;
  with pD do
  Begin
    For i := 0 to pfMaxIdx-1 do
    begin
      //Multiply every divisor before with the new primefactors
      //and append them to the list
      k := pfpotMax[i];
      p := pfpotPrim[i];
      pPot :=1;
      repeat
        pPot *= p;
        For j := 0 to len-1 do
        Begin
          pDivs[l]:= pPot*pDivs[j];
          inc(l);
        end;
        dec(k);
      until k<=0;
      len := l;
    end;
    p := pfRemain;
    If p >1 then
    begin
      For j := 0 to len-1 do
      Begin
        pDivs[l]:= p*pDivs[j];
        inc(l);
      end;
      len := l;
    end;
  end;
  //Sort. Insertsort much faster than QuickSort in this special case
  InsertSort(pDivs,0,len-1);

  pPot := 0;
  For i := 0 to len-1 do
  begin
    pPot += pDivs[i];
    SumOfDivs[i] := pPot;
  end;
end;

procedure Init_Check_rec(const pD:tprimeFac;var Divs,SumOfDivs:tDivisors);
begin
  GetDivs(pD,Divs,SUmOfDivs);
  finished := false;
  depth := 0;
  pDiv := @Divs[0];
end;

procedure Check_rek(SoD : Int64;i: NativeInt);
var
  sum : Int64;
begin
  if finished then
    EXIT;
  if rec_Cnt >RECCOUNTMAX then
  begin
    rec_Cnt := -1;
    finished := true;
    exit;
  end;
  inc(rec_Cnt);

  WHILE (i>0) AND (pDiv[i]>SoD) do
    dec(i);

  while i >= 0 do
  Begin
    sum := SoD-pDiv[i];
    if sum = 0 then
    begin
      finished := true;
      EXIT;
    end;
    dec(i);
    if (i>= 0) AND (sum <= SumOfDivs[i]) then
      Check_rek(sum,i);
    if finished then
      EXIT;
 end;
end;

function GetZumKeller(n: NativeUint;var pD:tPrimefac): boolean;
var
  SoD,sum : Int64;
  Div_cnt,i,pracLmt: NativeInt;
begin
  rec_Cnt := 0;
  SoD:= pd.pfSumOfDivs;
  //sum must be even and n not deficient
  if Odd(SoD) or (SoD<2*n) THEN
    EXIT(false);
//if Odd(n) then Exit(Not(odd(sum)));// to be tested

  SoD := SoD shr 1-n;
  If SoD < 2 then //0,1 is always true
    Exit(true);

  Div_cnt := pD.pfDivCnt;

  if Not(odd(n)) then
    if ((n mod 18) in [6,12]) then
      EXIT(true);

  //Now one needs to get the divisors
  Init_check_rec(pD,Divs,SumOfDivs);

  pracLmt:= 0;
  if Not(odd(n)) then
  begin
    For i := 1 to Div_Cnt do
    Begin
      sum := SumOfDivs[i];
      If (sum+1<Divs[i+1]) AND (sum<SoD) then
      Begin
        pracLmt := i;
        BREAK;
      end;
     IF (sum>=SoD) then break;
    end;
    if pracLmt = 0 then
      Exit(true);
  end;
  //number is practical followed by one big prime
  if pracLmt = (Div_Cnt-1) shr 1 then
  begin
    i := SoD mod Divs[pracLmt+1];
    with pD do
    begin
      if pfRemain > 1 then
        EXIT((pfRemain<=i) OR (i<=sum))
      else
        EXIT((pfpotPrim[pfMaxIdx-1]<=i)OR (i<=sum));
    end;
  end;

  Begin
    IF Div_cnt <= HCN_DivCnt then
    Begin
      Check_rek(SoD,Div_cnt-1);
      IF rec_Cnt = -1 then
        exit(true);
      exit(finished);
    end;
  end;
  result := false;
end;

var
  Ofs,i,n : NativeUInt;
  Max: NativeUInt;

procedure Init_Sieve(n:NativeUint);
//Init Sieve i,oFs are Global
begin
  i := n MOD SizePrDeFe;
  Ofs := (n DIV SizePrDeFe)*SizePrDeFe;
  SieveOneSieve(PrimeDecompField,Ofs);
end;

procedure GetSmall(MaxIdx:Int32);
var
  ZK: Array of Uint32;
  idx: UInt32;
Begin
  If MaxIdx<1 then
    EXIT;
  writeln('The first ',MaxIdx,' zumkeller numbers');
  Init_Sieve(0);
  setlength(ZK,MaxIdx);
  idx := Low(ZK);
  repeat
    if GetZumKeller(n,PrimeDecompField[i]) then
    Begin
      ZK[idx] := n;
      inc(idx);
    end;
    inc(i);
    inc(n);
    If i > High(PrimeDecompField) then
    begin
      dec(i,SizePrDeFe);
      inc(ofs,SizePrDeFe);
      SieveOneSieve(PrimeDecompField,Ofs);
    end;
  until idx >= MaxIdx;
  For idx := 0 to MaxIdx-1 do
  begin
    if idx MOD 20 = 0 then
      writeln;
    write(ZK[idx]:4);
  end;
  setlength(ZK,0);
  writeln;
  writeln;
end;

procedure GetOdd(MaxIdx:Int32);
var
  ZK: Array of Uint32;
  idx: UInt32;
Begin
  If MaxIdx<1 then
    EXIT;
  writeln('The first odd 40 zumkeller numbers');
  n := 1;
  Init_Sieve(n);
  setlength(ZK,MaxIdx);
  idx := Low(ZK);
  repeat
    if GetZumKeller(n,PrimeDecompField[i]) then
    Begin
      ZK[idx] := n;
      inc(idx);
    end;
    inc(i,2);
    inc(n,2);
    If i > High(PrimeDecompField) then
    begin
      dec(i,SizePrDeFe);
      inc(ofs,SizePrDeFe);
      SieveOneSieve(PrimeDecompField,Ofs);
    end;
  until idx >= MaxIdx;
  For idx := 0 to MaxIdx-1 do
  begin
    if idx MOD (80 DIV 8) = 0 then
      writeln;
    write(ZK[idx]:8);
  end;
  setlength(ZK,0);
  writeln;
  writeln;
end;

procedure GetOddNot5(MaxIdx:Int32);
var
  ZK: Array of Uint32;
  idx: UInt32;
Begin
  If MaxIdx<1 then
    EXIT;
  writeln('The first odd 40 zumkeller numbers not ending in 5');
  n := 1;
  Init_Sieve(n);
  setlength(ZK,MaxIdx);
  idx := Low(ZK);
  repeat
    if GetZumKeller(n,PrimeDecompField[i]) then
    Begin
      ZK[idx] := n;
      inc(idx);
    end;
    inc(i,2);
    inc(n,2);
    If n mod 5 = 0 then
    begin
      inc(i,2);
      inc(n,2);
    end;
    If i > High(PrimeDecompField) then
    begin
      dec(i,SizePrDeFe);
      inc(ofs,SizePrDeFe);
      SieveOneSieve(PrimeDecompField,Ofs);
    end;
  until idx >= MaxIdx;
  For idx := 0 to MaxIdx-1 do
  begin
    if idx MOD (80 DIV 8) = 0 then
      writeln;
    write(ZK[idx]:8);
  end;
  setlength(ZK,0);
  writeln;
  writeln;
end;
BEGIN
  InitSmallPrimes;

  T0 := GetTickCount64;
  GetSmall(220);
  GetOdd(40);
  GetOddNot5(40);

  writeln;
  n := 1;//8996229720;//1;
  Init_Sieve(n);
  writeln('Start ',n,' at ',i);
  T0 := GetTickCount64;
  MAX := (n DIV DELTAMAX+1)*DELTAMAX;
  count := 0;
  repeat
    writeln('Count of zumkeller numbers up to ',MAX:12);
    repeat
      if GetZumKeller(n,PrimeDecompField[i]) then
        inc(count);
      inc(i);
      inc(n);
      If i > High(PrimeDecompField) then
      begin
        dec(i,SizePrDeFe);
        inc(ofs,SizePrDeFe);
        SieveOneSieve(PrimeDecompField,Ofs);
      end;
    until n > MAX;
    writeln(n-1:10,' tested found ',count:10,' ratio ',count/n:10:7);
    MAX += DELTAMAX;
  until MAX>10*DELTAMAX;
  writeln('runtime ',(GetTickCount64-T0)/1000:8:3,' s');
  writeln;
  writeln('Count of recursion 59,641,327 for 8,996,229,720');
  n := 8996229720;
  Init_Sieve(n);
  T0 := GetTickCount64;
  Out_One_Sol(PrimeDecompField[i],n,true);
  writeln;
  writeln('runtime ',(GetTickCount64-T0)/1000:8:3,' s');
END.


myDict := Map with(
    "hello", 13,
    "world", 31,
    "!"    , 71
)

// iterating over key-value pairs:
myDict foreach( key, value,
    writeln("key = ", key, ", value = ", value)
)

// iterating over keys:
myDict keys foreach( key,
    writeln("key = ", key)
)

// iterating over values:
myDict foreach( value,
    writeln("value = ", value)
)
// or alternatively:
myDict values foreach( value,
    writeln("value = ", value)
)


define method doors()
  let doors = make(<array>, fill: #f, size: 100);
  for (x from 0 below 100)
    for (y from x below 100 by x + 1)
      doors[y] := ~doors[y]
    end
  end;
  for (x from 1 to 100)
    if (doors[x - 1])
      format-out("door %d open\n", x)
    end
  end
end


program ZToZ;
uses
  math;
begin
  write('0.0 ^ 0 :',IntPower(0.0,0):4:2);
  writeln('   0.0 ^ 0.0 :',Power(0.0,0.0):4:2);
end.


print 0 ** 0, "\n";

use Math::Complex;

print cplx(0,0) ** cplx(0,0), "\n";


cat mean.awk
#!/usr/local/bin/gawk -f

# User defined function
function mean(v,      i,n,sum) {
  for (i in v) {
    n++
    sum += v[i]
  }
  if (n>0) {
    return(sum/n)
  } else {
    return("zero-length input !")
  }
}

BEGIN {
  # fill a vector with random numbers
  for(i=0; i < 10; i++) {
    vett[i] = rand()*10
  }
  print mean(vett)
  print mean(nothing)
}


use strict;
use warnings;
use feature 'say';
use ntheory <is_prime divisor_sum divisors vecsum forcomb lastfor>;

sub in_columns {
    my($columns, $values) = @_;
    my @v = split ' ', $values;
    my $width = int(80/$columns);
    printf "%${width}d"x$columns."\n", @v[$_*$columns .. -1+(1+$_)*$columns] for 0..-1+@v/$columns;
    print "\n";
}

sub is_Zumkeller {
    my($n) = @_;
    return 0 if is_prime($n);
    my @divisors = divisors($n);
    return 0 unless @divisors > 2 && 0 == @divisors % 2;
    my $sigma = divisor_sum($n);
    return 0 unless 0 == $sigma%2 && ($sigma/2) >= $n;
    if (1 == $n%2) {
        return 1
    } else {
        my $Z = 0;
        forcomb { $Z++, lastfor if vecsum(@divisors[@_]) == $sigma/2 } @divisors;
        return $Z;
    }
}

use constant Inf  => 1e10;

say 'First 220 Zumkeller numbers:';
my $n = 0; my $z;
$z .= do { $n < 220 ? (is_Zumkeller($_) and ++$n and "$_ ") : last } for 1 .. Inf;
in_columns(20, $z);

say 'First 40 odd Zumkeller numbers:';
$n = 0; $z = '';
$z .= do { $n < 40 ? (!!($_%2) and is_Zumkeller($_) and ++$n and "$_ ") : last } for 1 .. Inf;
in_columns(10, $z);

say 'First 40 odd Zumkeller numbers not divisible by 5:';
$n = 0; $z = '';
$z .= do { $n < 40 ? (!!($_%2 and $_%5) and is_Zumkeller($_) and ++$n and "$_ ") : last } for 1 .. Inf;
in_columns(10, $z);


Map<String, Integer> map = new HashMap<String, Integer>();
map.put("hello", 1);
map.put("world", 2);
map.put("!", 3);

// iterating over key-value pairs:
for (Map.Entry<String, Integer> e : map.entrySet()) {
    String key = e.getKey();
    Integer value = e.getValue();
    System.out.println("key = " + key + ", value = " + value);
}

// iterating over keys:
for (String key : map.keySet()) {
    System.out.println("key = " + key);
}

// iterating over values:
for (Integer value : map.values()) {
    System.out.println("value = " + value);
}


var myhash = {}; //a new, empty object
myhash["hello"] = 3;
myhash.world = 6; //obj.name is equivalent to obj["name"] for certain values of name
myhash["!"] = 9;

//iterate using for..in loop
for (var key in myhash) {
  //ensure key is in object and not in prototype
  if (myhash.hasOwnProperty(key)) {
    console.log("Key is: " + key + '. Value is: ' + myhash[key]);
  }
}

//iterate using ES5.1 Object.keys() and Array.prototype.Map()
var keys = Object.keys(); //get Array of object keys (doesn't get prototype keys)
keys.map(function (key) {
  console.log("Key is: " + key + '. Value is: ' + myhash[key]);
});


local :open-doors [ rep 101 false ]

for i range 1 100:
	local :j i
	while <= j 100:
		set-to open-doors j not open-doors! j
		set :j + j i

!print\ "Open doors: "
for i range 1 100:
	if open-doors! i:
		!print\( to-str i " " )


?power(0,0)
requires("0.8.4") -- (now fixed/crashes on earlier versions)
include complex.e
complex a = complex_new(0,0),
        b = complex_power(a,a)
string sa = complex_sprint(a,true),
       sb = complex_sprint(b,true)
printf(1,"%s ^ %s = %s\n",{sa,sa,sb})


def mypower
    dup not if
        . sign dup 0 == if . 1 endif
    else
        power
    endif
enddef

0 0 mypower print


<?php
echo pow(0,0);
echo 0 ** 0; // PHP 5.6+ only
?>


mean = 0
sum = 0;
FOR i = LBOUND(nums) TO UBOUND(nums)
   sum = sum + nums(i);
NEXT i
size = UBOUND(nums) - LBOUND(nums) + 1
PRINT "The mean is: ";
IF size <> 0 THEN
   PRINT (sum / size)
ELSE
   PRINT 0
END IF


define m(a[], n) {
    auto i, s

    for (i = 0; i < n; i++) {
        s += a[i]
    }
    return(s / n)
}


function isPartSum(sequence f, integer l, t)
    if t=0 then return true end if
    if l=0 then return false end if
    integer last = f[l]
    return (t>=last and isPartSum(f, l-1, t-last))
        or isPartSum(f, l-1, t)
end function

function isZumkeller(integer n)
    sequence f = factors(n,1)
    integer t = sum(f)
    -- an odd sum cannot be split into two equal sums
    if remainder(t,2)=1 then return false end if
    -- if n is odd use 'abundant odd number' optimization
    if remainder(n,2)=1 then
        integer abundance := t - 2*n
        return abundance>0 and remainder(abundance,2)=0
    end if
    -- if n and t both even check for any partition of t/2
    return isPartSum(f, length(f), t/2)
end function

sequence tests = {{220,1,0,20,"%3d "},
                  {40,2,0,10,"%5d "},
                  {40,2,5,8,"%7d "}}
integer lim, step, rem, cr; string fmt
for t=1 to length(tests) do
    {lim, step, rem, cr, fmt} = tests[t]
    string odd = iff(step=1?"":"odd "),
           wch = iff(rem=0?"":"which don't end in 5 ")
    printf(1,"The first %d %sZumkeller numbers %sare:\n",{lim,odd,wch})
    integer i = step+1, count = 0
    while count<lim do
        if (rem=0 or remainder(i,10)!=rem)
        and isZumkeller(i) then
            printf(1,fmt,i)
            count += 1
            if remainder(count,cr)=0 then puts(1,"\n") end if
        end if
        i += step
    end while
    printf(1,"\n")
end for


- functionally, e.g. using map on an array
- by enumeration, i.e. by generating a stream
- by performing a reduction


dict = Dict("hello" => 13, "world" => 31, "!" => 71)

# applying a function to key-value pairs:
foreach(println, dict)

# iterating over key-value pairs:
for (key, value) in dict
    println("dict[$key] = $value")
end

# iterating over keys:
for key in keys(dict)
    @show key
end

# iterating over values:
for value in values(dict)
    @show value
end


#!/usr/bin/env rune

var toggles := []
var gets := []

# Set up GUI (and data model)
def frame := <swing:makeJFrame>("100 doors")
frame.getContentPane().setLayout(<awt:makeGridLayout>(10, 10))
for i in 1..100 {
  def component := <import:javax.swing.makeJCheckBox>(E.toString(i))
  toggles with= fn { component.setSelected(!component.isSelected()) }
  gets with= fn { component.isSelected() }
  frame.getContentPane().add(component)
}

# Set up termination condition
def done
frame.addWindowListener(def _ {
  to windowClosing(event) {
    bind done := true
  }
  match _ {}
})

# Open and close doors
def loop(step, i) {
  toggles[i] <- ()
  def next := i + step
  timer.whenPast(timer.now() + 10, fn {
    if (next >= 100) {
      if (step >= 100) {
        # Done.
      } else {
        loop <- (step + 1, step)
      }
    } else {
      loop <- (step, i + step)
    }
  })
}
loop(1, 0)

frame.pack()
frame.show()
interp.waitAtTop(done)


 zhz: Proc Options(Main);
 Dcl a dec float(10) Init(1);
 Dcl b dec float(10) Init(0);
 Put skip list('1**0=',a**b);
 Put skip list('0**1=',b**a);
 Put skip list('0**0=',b**b);
 End;


To run:
Start up.
Put 0 into a number.
Raise the number to 0.
Convert the number to a string.
Write the string to the console.
Wait for the escape key.
Shut down.


If OpenConsole()
  PrintN("Zero to the zero power is " + Pow(0,0))
  PrintN("")
  PrintN("Press any key to close the console")
  Repeat: Delay(10) : Until Inkey() <> ""
  CloseConsole()
EndIf


:mean(vec)
    vec.fold_left(0, (x, y -> x + y)) / vec.length()
end


(mean1=
  sum length n
.   0:?sum:?length
  &   whl
    ' ( !arg:%?n ?arg
      & 1+!length:?length
      & !n+!sum:?sum
      )
  & !sum*!length^-1
);

(mean2=
  sum length n
.     0:?sum:?length
    &   !arg
      :   ?
          ( #%@?n
          & 1+!length:?length
          & !n+!sum:?sum
          & ~
          )
          ?
  | !sum*!length^-1
);


mean = { list |
  true? list.empty?, 0, { list.reduce(0, :+) / list.length }
}

p mean 1.to 10  #Prints 5.5


(de propdiv (N)
   (make
      (for I N
         (and (=0 (% N I)) (link I)) ) ) )
(de sum? (G L)
   (cond
      ((=0 G) T)
      ((= (car L) G) T)
      ((cdr L)
         (if (> (car L) G)
            (sum? G (cdr L))
            (or
               (sum? (- G (car L)) (cdr L))
               (sum? G (cdr L)) ) ) ) ) )
(de zum? (N)
   (let (L (propdiv N)  S (sum prog L))
      (and
         (not (bit? 1 S))
         (if (bit? 1 N)
            (let A (- S (* 2 N))
               (and (gt0 A) (not (bit? 1 A)))
            )
            (sum?
               (- (/ S 2) (car L))
               (cdr L) ) ) ) ) )
(zero C)
(for (I 2 (> 220 C) (inc I))
   (when (zum? I)
      (prin (align 3 I) " ")
      (inc 'C)
      (and
         (=0 (% C 20))
         (prinl) ) ) )
(prinl)
(zero C)
(for (I 1 (> 40 C) (inc 'I 2))
   (when (zum? I)
      (prin (align 9 I) " ")
      (inc 'C)
      (and
         (=0 (% C 8))
         (prinl) ) ) )
(prinl)
(zero C)
# cheater
(for (I 81079 (> 40 C) (inc 'I 2))
   (when (and (<> 5 (% I 10)) (zum? I))
      (prin (align 9 I) " ")
      (inc 'C)
      (and
         (=0 (% C 8))
         (prinl) ) ) )


from sympy import divisors

from sympy.combinatorics.subsets import Subset

def isZumkeller(n):
    d = divisors(n)
    s = sum(d)
    if not s % 2 and max(d) <= s/2:
        for x in range(1, 2**len(d)):
            if sum(Subset.unrank_binary(x, d).subset) == s/2:
                return True

    return False

def printZumkellers(N, oddonly=False):
    nprinted = 0
    for n in range(1, 10**5):
        if (oddonly == False or n % 2) and isZumkeller(n):
            print(f'{n:>8}', end='')
            nprinted += 1
            if nprinted % 10 == 0:
                print()
            if nprinted >= N:
                return

print("220 Zumkeller numbers:")
printZumkellers(220)
print("\n\n40 odd Zumkeller numbers:")
printZumkellers(40, True)


fun main(a: Array<String>) {
    val map = mapOf("hello" to 1, "world" to 2, "!" to 3)

    with(map) {
        entries.forEach { println("key = ${it.key}, value = ${it.value}") }
        keys.forEach { println("key = $it") }
        values.forEach { println("value = $it") }
    }
}


: first  0 extract nip ; : second  1 extract nip ; : nip  swap drop ;
: say(*)  dup first " => " 2 compress "" join . second . ;

[['foo 5] ['bar 10] ['baz 20]] 'say apply drop


//iterate over associative array
//Lasso maps
	local('aMap' = map('weight' = 112,
					'height' = 45,
					'name' = 'jason'))
	' Map output: \n  '
	#aMap->forEachPair => {^
		//display pair, then show accessing key and value individually
		#1+'\n  '
		#1->first+': '+#1->second+'\n  '
	^}
	//display keys and values separately
	'\n'
	' Map Keys: '+#aMap->keys->join(',')+'\n'
	' Map values: '+#aMap->values->join(',')+'\n'

	//display using forEach
	'\n'
	' Use ForEach to iterate Map keys: \n'
	#aMap->keys->forEach => {^
		#1+'\n'
	^}
	'\n'
	' Use ForEach to iterate Map values: \n'
	#aMap->values->forEach => {^
		#1+'\n'
	^}
	//the {^ ^} indicates that output should be printed (AutoCollect) ,
	// if output is not desired, just { } is used


len d[] 101
for p = 1 to 100
  i = p
  while i <= 100
    d[i] = 1 - d[i]
    i += p
  .
.
for i = 1 to 100
  if d[i] = 1
    print i
  .
.


from decimal import Decimal
from fractions import Fraction
from itertools import product

zeroes = [0, 0.0, 0j, Decimal(0), Fraction(0, 1), -0.0, -0.0j, Decimal(-0.0)]
for i, j in product(zeroes, repeat=2):
    try:
        ans = i**j
    except:
        ans = '<Exception raised>'
    print(f'{i!r:>15} ** {j!r:<15} = {ans!r}')


#lang racket
;; as many zeros as I can think of...
(define zeros (list
               0  ; unspecified number type
               0. ; hinted as float
               #e0 ; explicitly exact
               #i0 ; explicitly inexact
               0+0i ; exact complex
               0.+0.i ; float inexact
               ))
(for*((z zeros) (p zeros))
  (printf "(~a)^(~a) = ~s~%" z p
  (with-handlers [(exn:fail:contract:divide-by-zero? exn-message)]
    (expt z p))))


#include <stdio.h>

double mean(double *v, int len)
{
	double sum = 0;
	int i;
	for (i = 0; i < len; i++)
		sum += v[i];
	return sum / len;
}

int main(void)
{
	double v[] = {1, 2, 2.718, 3, 3.142};
	int i, len;
	for (len = 5; len >= 0; len--) {
		printf("mean[");
		for (i = 0; i < len; i++)
			printf(i ? ", %g" : "%g", v[i]);
		printf("] = %g\n", mean(v, len));
	}

	return 0;
}


#lang racket

(require math/number-theory)

(define (zum? n)
  (let* ((set (divisors n))
         (sum (apply + set)))
    (cond
      [(odd? sum) #f]
      [(odd? n) ; if n is odd use 'abundant odd number' optimization
       (let ((abundance (- sum (* n 2)))) (and (positive? abundance) (even? abundance)))]
      [else
       (let ((sum/2 (quotient sum 2)))
         (let loop ((acc (car set)) (set (cdr set)))
           (cond [(= acc sum/2) #t]
                 [(> acc sum/2) #f]
                 [(null? set) #f]
                 [else (or (loop (+ (car set) acc) (cdr set))
                           (loop acc (cdr set)))])))])))

(define (first-n-matching-naturals count pred)
  (for/list ((i count) (j (stream-filter pred (in-naturals 1)))) j))

(define (tabulate title ns (row-width 132))
  (displayln title)
  (let* ((cell-width (+ 2 (order-of-magnitude (apply max ns))))
         (cells/row (quotient row-width cell-width)))
    (let loop ((ns ns) (col cells/row))
      (cond [(null? ns) (unless (= col cells/row) (newline))]
            [(zero? col) (newline) (loop ns cells/row)]
            [else (display (~a #:width cell-width #:align 'right (car ns)))
                  (loop (cdr ns) (sub1 col))]))))

(tabulate  "First 220 Zumkeller numbers:" (first-n-matching-naturals 220 zum?))
(newline)
(tabulate "First 40 odd Zumkeller numbers:"
          (first-n-matching-naturals 40 (λ (n) (and (odd? n) (zum? n)))))
(newline)
(tabulate "First 40 odd Zumkeller numbers not ending in 5:"
          (first-n-matching-naturals 40 (λ (n) (and (odd? n) (not (= 5 (modulo n 10))) (zum? n)))))


use ntheory:from<Perl5> <factor is_prime>;

sub zumkeller ($range)  {
    $range.grep: -> $maybe {
        next if $maybe < 3 or $maybe.&is_prime;
        my @divisors = $maybe.&factor.combinations».reduce( &[×] ).unique.reverse;
        next unless [and] @divisors > 2, @divisors %% 2, (my $sum = @divisors.sum) %% 2, ($sum /= 2) ≥ $maybe;
        my $zumkeller = False;
        if $maybe % 2 {
            $zumkeller = True
        } else {
            TEST: for 1 ..^ @divisors/2 -> $c {
                @divisors.combinations($c).map: -> $d {
                    next if $d.sum != $sum;
                    $zumkeller = True and last TEST
                }
            }
        }
        $zumkeller
    }
}

say "First 220 Zumkeller numbers:\n" ~
    zumkeller(^Inf)[^220].rotor(20)».fmt('%3d').join: "\n";

put "\nFirst 40 odd Zumkeller numbers:\n" ~
    zumkeller((^Inf).map: * × 2 + 1)[^40].rotor(10)».fmt('%7d').join: "\n";

# Stretch. Slow to calculate. (minutes)
put "\nFirst 40 odd Zumkeller numbers not divisible by 5:\n" ~
    zumkeller(flat (^Inf).map: {my \p = 10 * $_; p+1, p+3, p+7, p+9} )[^40].rotor(10)».fmt('%7d').join: "\n";


(let ((data '(#(key1 "foo") #(key2 "bar")))
      (hash (: dict from_list data)))
  (: dict fold
    (lambda (key val accum)
      (: io format '"~s: ~s~n" (list key val)))
    0
    hash))


data "red",      "255 50 50",       "green", "50 255 50",     "blue", "50 50 255"
data "my fave",  "220 120 120",     "black", "0 0 0"

myAssocList$ =""

for i =1 to 5
    read k$
    read dat$
    call sl.Set myAssocList$, k$, dat$
next i

keys$ = ""   ' List to hold the keys in myList$.
keys  = 0

keys = sl.Keys( myAssocList$, keys$)
print " Number of key-data pairs ="; keys

For i = 1 To keys
    keyName$ = sl.Get$( keys$, Str$( i))
    Print "  Key "; i; ":", keyName$, "Data: ", sl.Get$( myAssocList$, keyName$)
Next i

end


; initial state = closed = #f
(define doors (make-vector 101 #f))
; run pass 100 to 1
(for*
   ((pass (in-range 100 0 -1))
   (door (in-range 0 101 pass)))
    (when (and
        (vector-set! doors door (not (vector-ref doors door)))
        (= pass 1))
        (writeln door "is open")))

1     "is open"
4     "is open"
9     "is open"
16     "is open"
25     "is open"
36     "is open"
49     "is open"
64     "is open"
81     "is open"
100     "is open"


Red[]
print 0 ** 0
print power 0 0
print math [0 ** 0]


/*REXX program shows the results of  raising zero  to the  zeroth power.*/
say  '0 ** 0  (zero to the zeroth power) ───► '    0**0


x = 0
y = 0
z = pow(x,y)
see "z=" + z + nl   # z=1


using System;
using System.Linq;

class Program
{
    static void Main()
    {
        Console.WriteLine(new[] { 1, 2, 3 }.Average());
    }
}


#include <vector>

double mean(const std::vector<double>& numbers)
{
     if (numbers.size() == 0)
          return 0;

     double sum = 0;
     for (std::vector<double>::iterator i = numbers.begin(); i != numbers.end(); i++)
          sum += *i;
     return sum / numbers.size();
}


/*REXX pgm finds & shows Zumkeller numbers: 1st N; 1st odd M; 1st odd V not ending in 5.*/
parse arg n m v .                                /*obtain optional arguments from the CL*/
if n=='' | n==","  then n= 220                   /*Not specified?  Then use the default.*/
if m=='' | m==","  then m=  40                   /* "      "         "   "   "     "    */
if v=='' | v==","  then v=  40                   /* "      "         "   "   "     "    */
@zum= ' Zumkeller numbers are: '                 /*literal used for displaying messages.*/
sw= linesize() - 1                               /*obtain the usable screen width.      */
say
if n>0  then say center(' The first '       n       @zum,  sw, "═")
#= 0                                             /*the count of Zumkeller numbers so far*/
$=                                               /*initialize the  $  list  (to a null).*/
        do j=1  until #==n                       /*traipse through integers 'til done.  */
        if \Zum(j)  then iterate                 /*if not a Zumkeller number, then skip.*/
        #= # + 1;           call add$            /*bump Zumkeller count;  add to $ list.*/
        end   /*j*/

if $\==''  then say $                            /*Are there any residuals? Then display*/
say
if m>0  then say center(' The first odd '   m       @zum,  sw, "═")
#= 0                                             /*the count of Zumkeller numbers so far*/
$=                                               /*initialize the  $  list  (to a null).*/
        do j=1  by 2  until #==m                 /*traipse through integers 'til done.  */
        if \Zum(j)  then iterate                 /*if not a Zumkeller number, then skip.*/
        #= # + 1;           call add$            /*bump Zumkeller count;  add to $ list.*/
        end   /*j*/

if $\==''  then say $                            /*Are there any residuals? Then display*/
say
if v>0  then say center(' The first odd '   v       " (not ending in 5) " @zum,  sw, '═')
#= 0                                             /*the count of Zumkeller numbers so far*/
$=                                               /*initialize the  $  list  (to a null).*/
        do j=1  by 2  until #==v                 /*traipse through integers 'til done.  */
        if right(j,1)==5  then iterate           /*skip if odd number ends in digit "5".*/
        if \Zum(j)  then iterate                 /*if not a Zumkeller number, then skip.*/
        #= # + 1;           call add$            /*bump Zumkeller count;  add to $ list.*/
        end   /*j*/

if $\==''  then say $                            /*Are there any residuals? Then display*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
add$: _= strip($ j, 'L');   if length(_)<sw  then do;  $= _;  return;  end    /*add to $*/
      say  strip($, 'L');                              $= j;  return          /*say, add*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
iSqrt: procedure; parse arg x;  r= 0;  q= 1;                    do while q<=x; q=q*4;  end
          do while q>1; q= q%4; _= x-r-q; r= r%2; if _>=0  then do; x= _; r= r+q; end; end
       return r                                  /*R  is the integer square root of  X. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
PDaS: procedure; parse arg x 1 b;  odd= x//2     /*obtain  X  and  B (the 1st argument).*/
      if x==1  then return 1 1                   /*handle special case for unity.       */
      r= iSqrt(x)                                /*calculate integer square root of  X. */
      a= 1                                       /* [↓]  use all, or only odd numbers.  */
      sig= a + b                                 /*initialize the sigma  (so far)   ___ */
          do j=2+odd  by 1+odd  to r - (r*r==x)  /*divide by some integers up to   √ X  */
          if x//j==0  then do;  a=a j;  b= x%j b /*if ÷, add both divisors to α & ß.    */
                                sig= sig +j +x%j /*bump the sigma (the sum of divisors).*/
                           end
          end   /*j*/                            /* [↑]  %  is the REXX integer division*/
                                                 /* [↓]  adjust for a square.        ___*/
      if j*j==x  then  return sig+j  a j b       /*Was  X  a square?    If so, add  √ X */
                       return sig    a   b       /*return the divisors  (both lists).   */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Zum:  procedure; parse arg x .                   /*obtain a # to be tested for Zumkeller*/
      if x<6    then return 0                    /*test if X is too low     "      "    */
      if x<945  then if x//2==1  then return 0   /*  "   " "  "  "   "  for odd    "    */
      parse value  PDaS(x)  with  sigma pdivs    /*obtain sigma and the proper divisors.*/
      if sigma//2  then return 0                 /*Is the  sigma  odd?    Not Zumkeller.*/
      #= words(pdivs)                            /*count the number of divisors for  X. */
      if #<3       then return 0                 /*Not enough divisors?    "      "     */
      if x//2      then do; _= sigma - x - x     /*use abundant optimization for odd #'s*/
                            return _>0 & _//2==0 /*Abundant is > 0 and even?  It's a Zum*/
                        end
      if #>23      then return 1                 /*# divisors is 24 or more?  It's a Zum*/

           do i=1  for #;   @.i= word(pdivs, i)  /*assign proper divisors to the @ array*/
           end   /*i*/
      c=0;            u= 2**#;   !.= .
          do p=1  for u-2;       b= x2b(d2x(p))  /*convert P──►binary with leading zeros*/
          b= right(strip(b, 'L', 0), #, 0)       /*ensure enough leading zeros for  B.  */
          r= reverse(b); if !.r\==. then iterate /*is this binary# a palindrome of prev?*/
          c= c + 1;   yy.c= b;   !.b=            /*store this particular combination.   */
          end   /*p*/

          do part=1  for c;      p1= 0;   p2= 0  /*test of two partitions add to same #.*/
          _= yy.part                             /*obtain one method of partitioning.   */
            do cp=1  for #                       /*obtain the sums of the two partitions*/
            if substr(_, cp, 1)  then p1= p1 + @.cp     /*if a  one, then add it to  P1.*/
                                 else p2= p2 + @.cp     /* " " zero,   "   "   "  "  P2.*/
            end   /*cp*/
          if p1==p2  then return 1               /*Partition sums equal?  Then X is Zum.*/
          end   /*part*/
      return 0                                   /*no partition sum passed.  X isn't Zum*/


hash = [#key1:"value1", #key2:"value2", #key3:"value3"]

-- iterate over key-value pairs
repeat with i = 1 to hash.count
  put hash.getPropAt(i) & "=" & hash[i]
end repeat

-- iterating over values only can be written shorter
repeat with val in hash
  put val
end repeat


put 3 into fruit["apples"]
put 5 into fruit["pears"]
put 6 into fruit["oranges"]
put "none" into fruit["bananas"]

put "Keys:" & cr & the keys of fruit & cr into tTmp
put "Values 1:" & tab after tTmp
repeat for each line tKey in the keys of fruit
    put fruit[tkey] & comma after tTmp
end repeat

-- need to copy array as combine will change variable
put fruit into fruit2
combine fruit2 using comma
put cr & "Values2:" & tab after tTmp
repeat for each item f2val in fruit2
    put f2val & comma after tTmp
end repeat

combine fruit using return and ":"
put cr & "Key:Values" & cr & fruit after tTmp
-- alternatively, use same loop as for values 1 with tkey && fruit[tKey]

put tTmp


local t = {
    ["foo"] = "bar",
    ["baz"] = 6,
    fortytwo = 7
}

for key,val in pairs(t) do
    print(string.format("%s: %s", key, val))
end


Doors := RECORD
 UNSIGNED1 DoorNumber;
 STRING6   State;
END;

AllDoors := DATASET([{0,0}],Doors);

Doors  OpenThem(AllDoors L,INTEGER Cnt) := TRANSFORM
 SELF.DoorNumber := Cnt;
 SELF.State      := IF((CNT * 10) % (SQRT(CNT)*10)<>0,'Closed','Opened');
END;

OpenDoors := NORMALIZE(AllDoors,100,OpenThem(LEFT,COUNTER));

OpenDoors;


require 'bigdecimal'

[0, 0.0, Complex(0), Rational(0), BigDecimal("0")].each do |n|
  printf "%10s: ** -> %s\n" % [n.class, n**n]
end


assert(math.pow(0, 0) == 1, "Scala blunder, should go back to school !")


(display (expt 0 0)) (newline)
(display (expt 0.0 0.0)) (newline)
(display (expt 0+0i 0+0i)) (newline)


Mean.

Chef has no way to detect EOF, so rather than interpreting
some arbitrary number as meaning "end of input", this program
expects the first input to be the sample size. Pass in the samples
themselves as the other inputs. For example, if you wanted to
compute the mean of 10, 100, 47, you could pass in 3, 10, 100, and
47. To test the "zero-length vector" case, you need to pass in 0.

Ingredients.
0 g Sample Size
0 g Counter
0 g Current Sample

Method.
Take Sample Size from refrigerator.
Put Sample Size into mixing bowl.
Fold Counter into mixing bowl.
Put Current Sample into mixing bowl.
Loop Counter.
Take Current Sample from refrigerator.
Add Current Sample into mixing bowl.
Endloop Counter until looped.
If Sample Size.
Divide Sample Size into mixing bowl.
Put Counter into 2nd mixing bowl.
Fold Sample Size into 2nd mixing bowl.
Endif until ifed.
Pour contents of mixing bowl into baking dish.

Serves 1.


(defn mean [sq]
  (if (empty? sq)
      0
      (/ (reduce + sq) (count sq))))


load "stdlib.ring"

see "working..." + nl
see "The first 220 Zumkeller numbers are:" + nl

permut = []
zumind = []
zumodd = []
limit = 19305
num1 = 0
num2 = 0

for n = 2 to limit
    zumkeller = []
    zumList = []
    permut = []
    calmo = []
    zumind = []
    num = 0
    nold = 0
    for m = 1 to n
        if n % m = 0
           num = num + 1
           add(zumind,m)
        ok
    next
    for p = 1 to num
        add(zumList,1)
        add(zumList,2)
    next
    permut(zumList)
    lenZum = len(zumList)

    for n2 = 1 to len(permut)/lenZum
        str = ""
        for m = (n2-1)*lenZum+1 to n2*lenZum
            str = str + string(permut[m])
        next
        if str != ""
           strNum = number(str)
           add(calmo,strNum)
        ok
    next

    calmo = sort(calmo)

    for x = len(calmo) to 2 step -1
        if calmo[x] = calmo[x-1]
           del(calmo,x)
        ok
    next

    zumkeller = []
    calmoLen = len(string(calmo[1]))
    calmoLen2 = calmoLen/2
    for y = 1 to len(calmo)
        tmpStr = string(calmo[y])
        tmp1 = left(tmpStr,calmoLen2)
        tmp2 = number(tmp1)
        add(zumkeller,tmp2)
    next

    zumkeller = sort(zumkeller)

    for x = len(zumkeller) to 2 step -1
        if zumkeller[x] = zumkeller[x-1]
           del(zumkeller,x)
        ok
    next

    for z = 1 to len(zumkeller)
        zumsum1 = 0
        zumsum2 = 0
        zum1 = []
        zum2 = []

        for m = 1 to len(string(zumkeller[z]))
            zumstr = string(zumkeller[z])
            tmp = number(zumstr[m])
            if tmp = 1
               add(zum1,zumind[m])
            else
               add(zum2,zumind[m])
            ok
        next

        for z1 = 1 to len(zum1)
            zumsum1 = zumsum1 + zum1[z1]
        next

        for z2 = 1 to len(zum2)
            zumsum2 = zumsum2 + zum2[z2]
        next

        if zumsum1 = zumsum2
           num1 = num1 + 1
           if n != nold
              if num1 < 221
                 if (n-1)%22 = 0
                    see nl + " " + n
                 else
                    see " " + n
                 ok
              ok
              if zumsum1%2 = 1
                 num2 = num2 + 1
                 if num2 < 41
                    add(zumodd,n)
                 ok
              ok
           ok
           nold = n
        ok
    next
next

see "The first 40 odd Zumkeller numbers are:" + nl
for n = 1 to len(zumodd)
    if (n-1)%8 = 0
       see nl + " " + zumodd[n]
    else
       see " " + zumodd[n]
    ok
next

see nl + "done..." + nl

func permut(list)
     for perm = 1 to factorial(len(list))
         for i = 1 to len(list)
             add(permut,list[i])
         next
         perm(list)
     next

func perm(a)
     elementcount = len(a)
     if elementcount < 1
        return
     ok
     pos = elementcount-1
     while a[pos] >= a[pos+1]
           pos -= 1
           if pos <= 0 permutationReverse(a, 1, elementcount)
              return
           ok
     end
     last = elementcount
     while a[last] <= a[pos]
           last -= 1
     end
     temp = a[pos]
     a[pos] = a[last]
     a[last] = temp
     permReverse(a, pos+1, elementcount)

 func permReverse(a,first,last)
      while first < last
            temp = a[first]
            a[first] = a[last]
            a[last] = temp
            first += 1
            last -= 1
      end


class Integer

  def divisors
    res = [1, self]
    (2..Integer.sqrt(self)).each do |n|
      div, mod = divmod(n)
      res << n << div if mod.zero?
    end
    res.uniq.sort
  end

  def zumkeller?
    divs = divisors
    sum  = divs.sum
    return false unless sum.even? && sum >= self*2
    half = sum / 2
    max_combi_size = divs.size / 2
    1.upto(max_combi_size).any? do |combi_size|
      divs.combination(combi_size).any?{|combi| combi.sum == half}
    end
  end

end

def p_enum(enum, cols = 10, col_width = 8)
  enum.each_slice(cols) {|slice| puts "%#{col_width}d"*slice.size % slice}
end

puts "#{n=220} Zumkeller numbers:"
p_enum 1.step.lazy.select(&:zumkeller?).take(n), 14, 6

puts "\n#{n=40} odd Zumkeller numbers:"
p_enum 1.step(by: 2).lazy.select(&:zumkeller?).take(n)

puts "\n#{n=40} odd Zumkeller numbers not ending with 5:"
p_enum 1.step(by: 2).lazy.select{|x| x % 5 > 0 && x.zumkeller?}.take(n)


Module checkit {
      \\ Inventories are objects with keys and values, or keys (used as read only values)
      \\ They use hash function.
      \\ Function TwoKeys return Inventory object (as a pointer to object)
      Function TwoKeys {
            Inventory Alfa="key1":=100, "key2":=200
            =Alfa
      }
      M=TwoKeys()
      Print Type$(M)="Inventory"
      \\ Normal Use:
            \\ Inventories Keys are case sensitive
            \\ M2000 identifiers are not case sensitive
      Print M("key1"), m("key2")
      \\ numeric values can convert to strings
      Print M$("key1"), m$("key2")
      \\ Iteration
      N=Each(M)
      While N {
            Print Eval(N)  ' prints 100, 200 as number
            Print M(N^!)  ' The same using index N^
      }
      N=Each(M)
      While N {
            Print Eval$(N)  ' prints  100, 200 as strings
            Print M$(N^!)  ' The same using index N^
      }
      N=Each(M)
      While N {
            Print Eval$(N, N^)  ' Prints Keys
      }
      \\ double iteration
      Append M, "key3":=500
      N=Each(M, 1, -1)  ' start to end
      N1=Each(M, -1, 1) ' end to start
      \\ 3x3 prints
      While N {
            While N1 {
                  Print format$("{0}*{1}={2}", Eval(N1), Eval(N), Eval(N1)*Eval(N))
            }
      }
      \\ sort results from lower product to greater product (3+2+1, 6 prints only)
      N=Each(M, 1, -1)
      While N {
            N1=Each(M, N^+1, -1)
            While N1 {
                  Print format$("{0}*{1}={2}", Eval(N1), Eval(N), Eval(N1)*Eval(N))
            }
      }
      N=Each(M)
      N1=Each(M,-2, 1)  ' from second from end to start
      \\ print only 2 values. While block ends when one iterator finish
      While N, N1 {
            Print Eval(N1)*Eval(N)
      }
}
Checkit


divert(-1)
define(`for',
   `ifelse($#,0,``$0'',
   `ifelse(eval($2<=$3),1,
   `pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')')
define(`new',`define(`$1[size]key',0)')
define(`asize',`defn(`$1[size]key')')
define(`aget',`defn(`$1[$2]')')
define(`akget',`defn(`$1[$2]key')')
define(`avget',`aget($1,akget($1,$2))')
define(`aset',
   `ifdef($1[$2],
      `',
      `define(`$1[size]key',incr(asize(`$1')))`'define($1[asize(`$1')]key,$2)')`'define($1[$2],$3)')
define(`dquote', ``[email protected]'')
define(`akeyvalue',`dquote(akget($1,$2),aget($1,akget($1,$2)))')
define(`akey',`dquote(akget($1,$2))')
define(`avalue',`dquote(aget($1,akget($1,$2)))')
divert
new(`a')
aset(`a',`wow',5)
aset(`a',`wow',flame)
aset(`a',`bow',7)
key-value pairs
for(`x',1,asize(`a'),
   `akeyvalue(`a',x)
')
keys
for(`x',1,asize(`a'),
   `akey(`a',x)
')
values
for(`x',1,asize(`a'),
   `avalue(`a',x)
')


> T := table( [ "A" = 1, "B" = 2, "C" = 3, "D" = 4 ] );
> for i in indices( T, nolist ) do print(i ) end:
                                  "A"

                                  "B"

                                  "C"

                                  "D"


[Hundred doors problem from Rosetta Code website]
[EDSAC program, Initial Orders 2]

[Library subroutine M3. Prints header and is then overwritten.
Here, the last character sets the teleprinter to figures.]
       [email protected]@E8FEZPF
       @&*[email protected]&#
       ..PZ   [blank tape, needed to mark end of header text]

[Library subroutine P6. Prints strictly positive integer.
32 locations; working locations 1, 4, 5]
        T56K  [define load address for subroutine]
        [email protected]@[email protected]@[email protected]
        [email protected]
        [email protected]@[email protected]@J995FJF!F

        T88K   [define load address for main program]
        GK     [set @ (theta) for relative addresses]

[The 100 doors are at locations 200..299.
Doors are numbered 0..99 internally, and 1..100 for output.
The base address and the number of doors can be varied.
The value of a door is 0 if open, negative if closed.]

                   [Constants. Program also uses order 'P 1 F'
                    which is permanently at absolute address 2.]
    [0] P200F  [address of door #0]
    [1] P100F  [number of doors, as an address]
    [2] UF     [makes S order from T, since 'S' = 'T' + 'U']
    [3] MF     [makes A order from T, since 'A' = 'T' + 'M']
    [4] V2047D [all 1's for "closed" (any negative value will do)]
    [5] &F     [line feed]
    [6] @F     [carriage return]
    [7] K4096F [teleprinter null[

                   [Variables]
    [8] PF   [pass number; step when toggling doors]
    [9] PF   [door number, as address, 0-based]
   [10] PF   [order referring to door 0]

                   [Enter with acc = 0]
                   [Part 1 : close all the doors]
   [11] [email protected]  [pass := 0 (used in part 2)]
        [email protected]  [door number := 0]
        [email protected] [load 'T F' order]
        [email protected]   [add base address]
        [email protected] [store T order for door #0]
   [16] TF   [clear acc; also serves as constant]
        [email protected]  [load door number]
        [email protected] [make T order]
        [email protected] [plant in code]
        [email protected]  [load value for "closed"]
   [21] TF   [store in current door]
        [email protected]  [load door number]
        A2F  [add 1]
        [email protected]  [update door number]
        [email protected]  [done all doors yet?]
        [email protected] [if not, loop back]

                   [Part 2 : 100 passes, toggling the doors]
   [27] TF   [clear acc]
        [email protected]  [load pass number]
        A2F  [add 1]
        [email protected]  [save updated pass number]
        S2F  [make -1]
        [email protected]  [door number := -1]
        [email protected]  [add pass number to get first door toggled on this pass]
        [email protected]  [gone beyond end?]
        [email protected] [if so, move on to part 3]
   [36] [email protected]  [restore acc after test]
        [email protected]  [store current door number]
        [email protected] [make T order to load status]
        [email protected] [plant T order for first door in pass]
        [email protected]  [convert to S order]
        [email protected] [plant S order]
        [email protected]  [load value for "closed"]
   [43] SF   [subtract status; toggles status]
   [44] TF   [update status]
        [email protected]  [load door number just toggled]
        [email protected]  [add pass number to get next door in pass]
        [email protected]  [gone beyond end?]
        [email protected] [no, loop to do next door]
        [email protected] [yes, loop to do next pass]

                   [Part 3 : Print list of open doors.
                    Header has set teleprinter to figures.]
   [50] TF   [clear acc]
        [email protected]  [door nr := 0]
        [email protected] [T order for door 0]
        [email protected]  [convert to A order]
        [email protected]
   [55] TF
        [email protected]  [load door number]
        [email protected] [make A order to load value]
        [email protected] [plant in next order]
   [59] AF   [acc := 0 if open, < 0 if closed]
        [email protected] [skip if closed]
        [email protected]  [door number as address]
        A2F  [add 1 for 1-based output]
        RD   [shift 1 right, address --> integer]
        TF   [store integer at 0 for printing]
   [65] [email protected] [for return from subroutine]
        G56F [call subroutine to print door number]
        [email protected]  [followed by CRLF]
        [email protected]
   [69] TF   [clear acc]
        [email protected]  [load door number]
        A2F  [add 1]
        [email protected]  [update door number]
        [email protected]  [done all doors yet?]
        [email protected]  [if not, loop back]
   [75] [email protected]  [output null to flush teleprinter buffer]
        ZF   [stop]
        E11Z [define relative start address]
        PF


$ include "seed7_05.s7i";
  include "float.s7i";
  include "complex.s7i";

const proc: main is func
  begin
    writeln("0      ** 0   = " <& 0 ** 0);
    writeln("0.0    ** 0   = " <& 0.0 ** 0);
    writeln("0.0    ** 0.0 = " <& 0.0 ** 0.0);
    writeln("0.0+0i ** 0   = " <& complex(0.0) ** 0);
  end func;


set a to 0
set b to 0

put a to the power of b
// Prints: 1


[0, Complex(0, 0)].each {|n|
    say n**n
}


class Rosetta
	def mean(ns as List<of number>) as number
		if ns.count == 0
			return 0
		else
			sum = 0.0
			for n in ns
				sum += n
			return sum / ns.count

	def main
		print "mean of [[]] is [.mean(List<of number>())]"
		print "mean of [[1,2,3,4]] is [.mean([1.0,2.0,3.0,4.0])]"


mean = (array) ->
 return 0 if array.length is 0
 sum = array.reduce (s,i,0) -> s += i
 sum / array.length

alert mean [1]


(defun mean (&rest sequence)
  (if (null sequence)
      nil
      (/ (reduce #'+ sequence) (length sequence))))


use std::convert::TryInto;

/// Gets all divisors of a number, including itself
fn get_divisors(n: u32) -> Vec<u32> {
    let mut results = Vec::new();

    for i in 1..(n / 2 + 1) {
        if n % i == 0 {
            results.push(i);
        }
    }
    results.push(n);
    results
}

/// Calculates whether the divisors can be partitioned into two disjoint
/// sets that sum to the same value
fn is_summable(x: i32, divisors: &[u32]) -> bool {
    if !divisors.is_empty() {
        if divisors.contains(&(x as u32)) {
            return true;
        } else if let Some((first, t)) = divisors.split_first() {
            return is_summable(x - *first as i32, &t) || is_summable(x, &t);
        }
    }
    false
}

/// Calculates whether the number is a Zumkeller number
/// Zumkeller numbers are the set of numbers whose divisors can be partitioned
/// into two disjoint sets that sum to the same value. Each sum must contain
/// divisor values that are not in the other sum, and all of the divisors must
/// be in one or the other.
fn is_zumkeller_number(number: u32) -> bool {
    if number % 18 == 6 || number % 18 == 12 {
        return true;
    }

    let div = get_divisors(number);
    let divisor_sum: u32 = div.iter().sum();
    if divisor_sum == 0 {
        return false;
    }
    if divisor_sum % 2 == 1 {
        return false;
    }

    // numbers where n is odd and the abundance is even are Zumkeller numbers
    let abundance = divisor_sum as i32 - 2 * number as i32;
    if number % 2 == 1 && abundance > 0 && abundance % 2 == 0 {
        return true;
    }

    let half = divisor_sum / 2;
    return div.contains(&half)
        || (div.iter().filter(|&&d| d < half).count() > 0
            && is_summable(half.try_into().unwrap(), &div));
}

fn main() {
    println!("\nFirst 220 Zumkeller numbers:");
    let mut counter: u32 = 0;
    let mut i: u32 = 0;
    while counter < 220 {
        if is_zumkeller_number(i) {
            print!("{:>3}", i);
            counter += 1;
            print!("{}", if counter % 20 == 0 { "\n" } else { "," });
        }
        i += 1;
    }

    println!("\nFirst 40 odd Zumkeller numbers:");
    let mut counter: u32 = 0;
    let mut i: u32 = 3;
    while counter < 40 {
        if is_zumkeller_number(i) {
            print!("{:>5}", i);
            counter += 1;
            print!("{}", if counter % 20 == 0 { "\n" } else { "," });
        }
        i += 2;
    }
}


func is_Zumkeller(n) {

    return false if n.is_prime
    return false if n.is_square

    var sigma = n.sigma

    # n must have an even abundance
    return false if (sigma.is_odd || (sigma < 2*n))

    # true if n is odd and has an even abundance
    return true if n.is_odd    # conjecture

    var divisors = n.divisors

    for k in (2 .. divisors.end) {
        divisors.combinations(k, {|*a|
            if (2*a.sum == sigma) {
                return true
            }
        })
    }

    return false
}

say "First 220 Zumkeller numbers:"
say (1..Inf -> lazy.grep(is_Zumkeller).first(220).join(' '))

say "\nFirst 40 odd Zumkeller numbers: "
say (1..Inf `by` 2 -> lazy.grep(is_Zumkeller).first(40).join(' '))

say "\nFirst 40 odd Zumkeller numbers not divisible by 5: "
say (1..Inf `by` 2 -> lazy.grep { _ % 5 != 0 }.grep(is_Zumkeller).first(40).join(' '))


keys=DownValues[#,Sort->False][[All,1,1,1]]&;
hashes=#/@keys[#]&;

a[2]="string";a["sometext"]=23;
keys[a]
->{2,sometext}
hashes[a]
->{string,23}


   keys = fieldnames(hash);
   for k=1:length(keys),
        key = keys{k};
	value = getfield(hash,key);        % get value of key
	hash = setfield(hash,key,-value);  % set value of key
   end;


h[1]: 6$
h[9]: 2$

/* iterate over values */
for val in listarray(h) do (
  print(val))$

/* iterate over the keys */
for key in rest(arrayinfo(h), 2) do (
  val: arrayapply(h, key),
  print(key, val))$


#import <Foundation/Foundation.h>

int main()
  square := 1, increment = 3

  for int door in 1 .. 100
    printf("door #%d", door)

    if door == square
      puts(" is open.")
      square += increment
      increment += 2
    else
      puts(" is closed.")

  return 0


- Math.pow (0.0, 0.0);
val it = 1.0 : real


# Crystal will return NaN if an empty array is passed
def mean(arr) : Float64
  arr.sum / arr.size.to_f
end


real mean(Range)(Range r) pure nothrow @nogc {
    real sum = 0.0;
    int count;

    foreach (item; r) {
        sum += item;
        count++;
    }

    if (count == 0)
        return 0.0;
    else
        return sum / count;
}

void main() {
    import std.stdio;

    int[] data;
    writeln("Mean: ", data.mean);
    data = [3, 1, 4, 1, 5, 9];
    writeln("Mean: ", data.mean);
}


exception Found of string ;

val divisors  = fn n =>
let
 val rec divr = fn  ( c, divlist ,i) =>
    if c <2*i then c::divlist
              else divr  (if c mod i = 0 then (c,i::divlist,i+1)  else (c,divlist,i+1) )
in
   divr  (n,[],1)
end;

val subsetSums = fn M => fn input =>
let
 val getnrs = fn (v,x) =>                                 (* out: list of numbers index where v is true + x *)
  let
     val rec runthr =  fn (v,i,x,lst)=> if i>=M then (v,i,x,lst) else  runthr (v,i+1,x,if Vector.sub(v,i) then (i+x)::lst else lst) ;
  in
     #4 (runthr (v,0,x,[]))
  end;

 val nwVec =  fn  (v,nrs) =>
  let
    val rec upd = fn (v,i,[])   => (v,i,[])
                  | (v,i,h::t)  => upd ( case Int.compare (h,M) of
		            LESS    => ( Vector.update (v,h,true),i+1,t)
		          | GREATER => (v,i+1,t)
		          | EQUAL   => raise Found ("done "^(Int.toString h))  )
  in
    #1 (upd (v,0,nrs))
  end;

 val rec setSums = fn ([],v)  => ([],v)
                   | (x::t,v) => setSums(t, nwVec(v, getnrs (v,x)))
in

  #2 (setSums (input,Vector.tabulate (M+1,fn 0=> true|_=>false) ))

end;

val rec Zumkeller =  fn n =>
  let
   val d    =  divisors n;
   val s    =  List.foldr op+ 0 d ;
   val hs   =  s div 2 -n ;
  in

   if s mod 2 = 1 orelse 0 > hs then false else
       Vector.sub (  subsetSums hs (tl d) ,hs)             handle Found nr => true

end;


import Foundation

extension BinaryInteger {
  @inlinable
  public var isZumkeller: Bool {
    let divs = factors(sorted: false)
    let sum = divs.reduce(0, +)

    guard sum & 1 != 1 else {
      return false
    }

    guard self & 1 != 1 else {
      let abundance = sum - 2*self

      return abundance > 0 && abundance & 1 == 0
    }

    return isPartSum(divs: divs[...], sum: sum / 2)
  }

  @inlinable
  public func factors(sorted: Bool = true) -> [Self] {
    let maxN = Self(Double(self).squareRoot())
    var res = Set<Self>()

    for factor in stride(from: 1, through: maxN, by: 1) where self % factor == 0 {
      res.insert(factor)
      res.insert(self / factor)
    }

    return sorted ? res.sorted() : Array(res)
  }
}

@usableFromInline
func isPartSum<T: BinaryInteger>(divs: ArraySlice<T>, sum: T) -> Bool {
  guard sum != 0 else {
    return true
  }

  guard !divs.isEmpty else {
    return false
  }

  let last = divs.last!

  if last > sum {
    return isPartSum(divs: divs.dropLast(), sum: sum)
  }

  return isPartSum(divs: divs.dropLast(), sum: sum) || isPartSum(divs: divs.dropLast(), sum: sum - last)
}

let zums = (2...).lazy.filter({ $0.isZumkeller })
let oddZums = zums.filter({ $0 & 1 == 1 })
let oddZumsWithout5 = oddZums.filter({ String($0).last! != "5" })

print("First 220 zumkeller numbers are \(Array(zums.prefix(220)))")
print("First 40 odd zumkeller numbers are \(Array(oddZums.prefix(40)))")
print("First 40 odd zumkeller numbers that don't end in a 5 are: \(Array(oddZumsWithout5.prefix(40)))")


d = { 3: "test", "foo": 3 }

for keyVal in d
    print keyVal   // produces results like: { "key": 3, "value": "test" }
end for

for key in d.indexes
    print key
end for

for  val in d.values
    print val
end for


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

surname = 'Unknown' -- default value
surname['Fred'] = 'Bloggs'
surname['Davy'] = 'Jones'

try = 'Fred'
say surname[try] surname['Bert']

-- extract the keys
loop fn over surname
  say fn.right(10) ':' surname[fn]
  end fn


;; using an association list:
(setq alist '(("A" "a") ("B" "b") ("C" "c")))

;; list keys
(map first alist)

;; list values
(map last alist)

;; loop over the assocation list:
(dolist (elem alist)
  (println (format "%s -> %s" (first elem) (last elem))))


import "prelude.eg"

using System
using List

data open, closed

def toggle =
    [ open N -> closed N | closed N -> open N ]

def doors =
    [ N -> map [ N -> closed N ] (fromto 1 N) ]

def toggleK =
    [ K nil              -> nil
    | K (cons (D N) DD)  ->
         let DOOR = if (N%K) == 0 then toggle (D N) else D N in
             cons DOOR (toggleK K DD) ]

def toggleEvery =
    [ nil DOORS -> DOORS
    | (cons K KK) DOORS -> toggleEvery KK (toggleK K DOORS) ]

def run =
    [ N -> toggleEvery (fromto 1 N) (doors N) ]

def main = run 100


Public Sub zero()
    x = 0
    y = 0
    z = 0 ^ 0
    Debug.Print "z ="; z
End Sub


module main;
  initial begin
    $display("0 ^ 0 = ", 0**0);
    $finish ;
  end
endmodule


Module Program
    Sub Main()
        Console.Write(0^0)
    End Sub
End Module


// Zero to the zero power, in V
// Tectonics: v run zero-to-the-zero-power.v
module main
import math

// starts here
// V does not include an exponentiation operator, but uses a math module
pub fn main() {
    println(math.pow(0, 0))
}


num mean(List<num> l) => l.reduce((num p, num n) => p + n) / l.length;

void main(){
  print(mean([1,2,3,4,5,6,7]));
}


program AveragesArithmeticMean;

{$APPTYPE CONSOLE}

uses Types;

function ArithmeticMean(aArray: TDoubleDynArray): Double;
var
  lValue: Double;
begin
  Result := 0;

  for lValue in aArray do
    Result := Result + lValue;
  if Result > 0 then
    Result := Result / Length(aArray);
end;

begin
  Writeln(Mean(TDoubleDynArray.Create()));
  Writeln(Mean(TDoubleDynArray.Create(1,2,3,4,5)));
end.


Module Module1
    Function GetDivisors(n As Integer) As List(Of Integer)
        Dim divs As New List(Of Integer) From {
            1, n
        }
        Dim i = 2
        While i * i <= n
            If n Mod i = 0 Then
                Dim j = n \ i
                divs.Add(i)
                If i <> j Then
                    divs.Add(j)
                End If
            End If
            i += 1
        End While
        Return divs
    End Function

    Function IsPartSum(divs As List(Of Integer), sum As Integer) As Boolean
        If sum = 0 Then
            Return True
        End If
        Dim le = divs.Count
        If le = 0 Then
            Return False
        End If
        Dim last = divs(le - 1)
        Dim newDivs As New List(Of Integer)
        For i = 1 To le - 1
            newDivs.Add(divs(i - 1))
        Next
        If last > sum Then
            Return IsPartSum(newDivs, sum)
        End If
        Return IsPartSum(newDivs, sum) OrElse IsPartSum(newDivs, sum - last)
    End Function

    Function IsZumkeller(n As Integer) As Boolean
        Dim divs = GetDivisors(n)
        Dim sum = divs.Sum()
        REM if sum is odd can't be split into two partitions with equal sums
        If sum Mod 2 = 1 Then
            Return False
        End If
        REM if n is odd use 'abundant odd number' optimization
        If n Mod 2 = 1 Then
            Dim abundance = sum - 2 * n
            Return abundance > 0 AndAlso abundance Mod 2 = 0
        End If
        REM if n and sum are both even check if there's a partition which totals sum / 2
        Return IsPartSum(divs, sum \ 2)
    End Function

    Sub Main()
        Console.WriteLine("The first 220 Zumkeller numbers are:")
        Dim i = 2
        Dim count = 0
        While count < 220
            If IsZumkeller(i) Then
                Console.Write("{0,3} ", i)
                count += 1
                If count Mod 20 = 0 Then
                    Console.WriteLine()
                End If
            End If
            i += 1
        End While
        Console.WriteLine()

        Console.WriteLine("The first 40 odd Zumkeller numbers are:")
        i = 3
        count = 0
        While count < 40
            If IsZumkeller(i) Then
                Console.Write("{0,5} ", i)
                count += 1
                If count Mod 10 = 0 Then
                    Console.WriteLine()
                End If
            End If
            i += 2
        End While
        Console.WriteLine()

        Console.WriteLine("The first 40 odd Zumkeller numbers which don't end in 5 are:")
        i = 3
        count = 0
        While count < 40
            If i Mod 10 <> 5 AndAlso IsZumkeller(i) Then
                Console.Write("{0,7} ", i)
                count += 1
                If count Mod 8 = 0 Then
                    Console.WriteLine()
                End If
            End If
            i += 2
        End While
    End Sub
End Module


import tables

var t: Table[int,string]

t[1] = "one"
t[2] = "two"
t[3] = "three"
t[4] = "four"

echo "t has " & $t.len & " elements"

echo "has t key 4? " & $t.hasKey(4)
echo "has t key 5? " & $t.hasKey(5)

#iterate keys
echo "key iteration:"
for k in t.keys:
  echo "at[" & $k & "]=" & t[k]

#iterate pairs
echo "pair iteration:"
for k,v in t.pairs:
  echo "at[" & $k & "]=" & v


MODULE AssociativeArray;
IMPORT
  ADT:Dictionary,
  Object:Boxed,
  Out;
TYPE
  Key = STRING;
  Value = Boxed.LongInt;

VAR
  assocArray: Dictionary.Dictionary(Key,Value);
  iterK: Dictionary.IterKeys(Key,Value);
  iterV: Dictionary.IterValues(Key,Value);
  aux: Value;
  k: Key;

BEGIN
  assocArray := NEW(Dictionary.Dictionary(Key,Value));
  assocArray.Set("ten",NEW(Value,10));
  assocArray.Set("eleven",NEW(Value,11));

  aux := assocArray.Get("ten");
  Out.LongInt(aux.value,0);Out.Ln;
  aux := assocArray.Get("eleven");
  Out.LongInt(aux.value,0);Out.Ln;Out.Ln;

  (* Iterate keys *)
  iterK := assocArray.IterKeys();
  WHILE (iterK.Next(k)) DO
    Out.Object(k);Out.Ln
  END;

  Out.Ln;

  (* Iterate values *)
  iterV := assocArray.IterValues();
  WHILE (iterV.Next(aux)) DO
    Out.LongInt(aux.value,0);Out.Ln
  END

END AssociativeArray.


program OneHundredDoors

   function main()

      doors boolean[] = new boolean[100];
      n int = 100;

      for (i int from 1 to n)
         for (j int from i to n by i)
            doors[j] = !doors[j];
         end
      end

      for (i int from 1 to n)
         if (doors[i])
            SysLib.writeStdout( "Door " + i + " is open" );
         end
      end

   end

end


XLISP 3.3, September 6, 2002 Copyright (c) 1984-2002, by David Betz
[1] (expt 0 0)

1
[2]


const std = @import("std");

pub fn main() !void {
    const stdout = std.io.getStdOut().writer();
    try stdout.print("0^0 = {d:.8}\n", .{std.math.pow(f32, 0, 0)});
}


func avg(args...) {
    var acc = .0
    var len = 0
    for x in args {
        len += 1
        acc += x
    }
    acc / len
}

avg(1, 2, 3, 4, 5, 6)


def meanOrZero(numbers) {
    var count := 0
    var sum := 0
    for x in numbers {
        sum += x
        count += 1
    }
    return sum / 1.max(count)
}


func mean . f[] r .
  for i range len f[]
    s += f[i]
  .
  r = s / len f[]
.
f[] = [ 1 2 3 4 5 6 7 8 ]
call mean f[] r
print r


fn get_divisors(n int) []int {
    mut divs := [1, n]
    for i := 2; i*i <= n; i++ {
        if n%i == 0 {
            j := n / i
            divs << i
            if i != j {
                divs << j
            }
        }
    }
    return divs
}

fn sum(divs []int) int {
    mut sum := 0
    for div in divs {
        sum += div
    }
    return sum
}

fn is_part_sum(d []int, sum int) bool {
    mut divs := d.clone()
    if sum == 0 {
        return true
    }
    le := divs.len
    if le == 0 {
        return false
    }
    last := divs[le-1]
    divs = divs[0 .. le-1]
    if last > sum {
        return is_part_sum(divs, sum)
    }
    return is_part_sum(divs, sum) || is_part_sum(divs, sum-last)
}

fn is_zumkeller(n int) bool {
    divs := get_divisors(n)
    s := sum(divs)
    // if sum is odd can't be split into two partitions with equal sums
    if s%2 == 1 {
        return false
    }
    // if n is odd use 'abundant odd number' optimization
    if n%2 == 1 {
        abundance := s - 2*n
        return abundance > 0 && abundance%2 == 0
    }
    // if n and sum are both even check if there's a partition which totals sum / 2
    return is_part_sum(divs, s/2)
}

fn main() {
    println("The first 220 Zumkeller numbers are:")
    for i, count := 2, 0; count < 220; i++ {
        if is_zumkeller(i) {
            print("${i:3} ")
            count++
            if count%20 == 0 {
                println('')
            }
        }
    }
    println("\nThe first 40 odd Zumkeller numbers are:")
    for i, count := 3, 0; count < 40; i += 2 {
        if is_zumkeller(i) {
            print("${i:5} ")
            count++
            if count%10 == 0 {
                println('')
            }
        }
    }
    println("\nThe first 40 odd Zumkeller numbers which don't end in 5 are:")
    for i, count := 3, 0; count < 40; i += 2 {
        if (i % 10 != 5) && is_zumkeller(i) {
            print("${i:7} ")
            count++
            if count%8 == 0 {
                println('')
            }
        }
    }
    println('')
}


import "/math" for Int, Nums
import "/fmt" for Fmt
import "io" for Stdout

var isPartSum // recursive
isPartSum = Fn.new { |divs, sum|
    if (sum == 0) return true
    if (divs.count == 0) return false
    var last = divs[-1]
    divs = divs[0...-1]
    if (last > sum) return isPartSum.call(divs, sum)
    return isPartSum.call(divs, sum-last) || isPartSum.call(divs, sum)
}

var isZumkeller = Fn.new { |n|
    var divs = Int.divisors(n)
    var sum = Nums.sum(divs)
    // if sum is odd can't be split into two partitions with equal sums
    if (sum % 2 == 1) return false
    // if n is odd use 'abundant odd number' optimization
    if (n % 2 == 1) {
        var abundance = sum - 2 * n
        return abundance > 0 && abundance % 2 == 0
    }
    // if n and sum are both even check if there's a partition which totals sum / 2
    return isPartSum.call(divs, sum / 2)
}

System.print("The first 220 Zumkeller numbers are:")
var count = 0
var i = 2
while (count < 220) {
    if (isZumkeller.call(i)) {
        Fmt.write("$3d ", i)
        Stdout.flush()
        count = count + 1
        if (count % 20 ==  0) System.print()
    }
    i = i + 1
}

System.print("\nThe first 40 odd Zumkeller numbers are:")
count = 0
i = 3
while (count < 40) {
    if (isZumkeller.call(i)) {
        Fmt.write("$5d ", i)
        Stdout.flush()
        count = count + 1
        if (count % 10 == 0) System.print()
    }
    i = i + 2
}

System.print("\nThe first 40 odd Zumkeller numbers which don't end in 5 are:")
count = 0
i = 3
while (count < 40) {
    if ((i % 10 != 5) && isZumkeller.call(i)) {
        Fmt.write("$7d ", i)
        Stdout.flush()
        count = count + 1
        if (count % 8 == 0) System.print()
    }
    i = i + 2
}
System.print()


class Iteration {
  function : Main(args : String[]) ~ Nil {
    assoc_array := Collection.StringMap->New();
    assoc_array->Insert("Hello", IntHolder->New(1));
    assoc_array->Insert("World", IntHolder->New(2));
    assoc_array->Insert("!", IntHolder->New(3));

    keys := assoc_array->GetKeys();
    values := assoc_array->GetValues();

    each(i : keys) {
      key := keys->Get(i)->As(String);
      value := assoc_array->Find(key)->As(IntHolder)->Get();
      "key={$key}, value={$value}"->PrintLine();
    };

    "-------------"->PrintLine();

    each(i : keys) {
      key := keys->Get(i)->As(String);
      value := values->Get(i)->As(IntHolder)->Get();
      "key={$key}, value={$value}"->PrintLine();
    };
  }
}


note
	description: "100 Doors problem"
	date: "08-JUL-2015"
	revision: "1.1"

class
	APPLICATION

create
	make

feature {NONE} -- Initialization

	make
			-- Main application routine.
		do
			initialize_closed_doors
			toggle_doors
			output_door_states
		end

feature -- Access

	doors: ARRAYED_LIST [DOOR]
			-- A set of doors (self-initialized to capacity of `max_door_count').
		attribute
			create Result.make (max_door_count)
		end

feature -- Basic Operations

	initialize_closed_doors
			-- Initialize all `doors'.
		do
			across min_door_count |..| max_door_count as ic_address_list loop
				doors.extend (create {DOOR}.make_closed (ic_address_list.item))
			end
		ensure
			has_all_closed_doors: across doors as ic_doors_list all not ic_doors_list.item.is_open end
		end

	toggle_doors
			-- Toggle all `doors'.
		do
			across min_door_count |..| max_door_count as ic_addresses_list loop
				across doors as ic_doors_list loop
					if is_door_to_toggle (ic_doors_list.item.address, ic_addresses_list.item) then
						ic_doors_list.item.toggle_door
					end
				end
			end
		end

	output_door_states
			-- Output the state of all `doors'.
		do
			doors.do_all (agent door_state_out)
		end

feature -- Status Report

	is_door_to_toggle (a_door_address, a_index_address: like {DOOR}.address): BOOLEAN
			-- Is the door at `a_door_address' needing to be toggled, when compared to `a_index_address'?
		do
			Result := a_door_address \\ a_index_address = 0
		ensure
			only_modulus_zero: Result = (a_door_address \\ a_index_address = 0)
		end

feature -- Outputs

	door_state_out (a_door: DOOR)
			-- Output the state of `a_door'.
		do
			print ("Door " + a_door.address.out + " is ")
			if a_door.is_open then
				print ("open.")
			else
				print ("closed.")
			end
			io.new_line
		end

feature {DOOR} -- Constants

	min_door_count: INTEGER = 1
			-- Minimum number of doors.

	max_door_count: INTEGER = 100
			-- Maximum number of doors.

end


(lib 'math)
(mean '(1 2 3 4)) ;; mean of a list
    → 2.5
(mean #(1 2 3 4)) ;; mean of a vector
    → 2.5

(lib 'sequences)
(mean [1 3 .. 10]) ;; mean of a sequence
    → 5

;; error handling
(mean 'elvis)
    ⛔ error: mean : expected sequence : elvis
(mean ())
    💣 error: mean : null is not an object
(mean #())
    😐 warning: mean : zero-divide : empty-vector
    → 0
(mean [2 2 .. 2])
    😁 warning: mean : zero-divide : empty-sequence
    → 0


AveVal(SET OF INTEGER s) := AVE(s);

//example usage

SetVals := [14,9,16,20,91];
AveVal(SetVals) //returns 30.0 ;


import extensions;

extension op
{
    average()
    {
        real sum := 0;
        int count := 0;

        var enumerator := self.enumerator();

        while (enumerator.next())
        {
            sum += enumerator.get();
            count += 1;
        };

        ^ sum / count
    }
}

public program()
{
    var array := new int[]{1, 2, 3, 4, 5, 6, 7, 8};
    console.printLine(
        "Arithmetic mean of {",array.asEnumerable(),"} is ",
        array.average()).readChar()
}


fcn properDivs(n){ // does not include n
//   if(n==1) return(T);	// we con't care about this case
   ( pd:=[1..(n).toFloat().sqrt()].filter('wrap(x){ n%x==0 }) )
   .pump(pd,'wrap(pd){ if(pd!=1 and (y:=n/pd)!=pd ) y else Void.Skip })
}
fcn canSum(goal,divs){
   if(goal==0 or divs[0]==goal) return(True);
   if(divs.len()>1){
      if(divs[0]>goal) return(canSum(goal,divs[1,*]));  // tail recursion
      else return(canSum(goal - divs[0], divs[1,*]) or canSum(goal, divs[1,*]));
   }
   False
}
fcn isZumkellerW(n){	// a filter for a iterator
   ds,sum := properDivs(n), ds.sum(0) + n;
   // if sum is odd, it can't be split into two partitions with equal sums
   if(sum.isOdd) return(Void.Skip);
   // if n is odd use 'abundant odd number' optimization
   if(n.isOdd){
      abundance:=sum - 2*n;
      return( if(abundance>0 and abundance.isEven) n else Void.Skip);
   }
   canSum(sum/2,ds) and n or Void.Skip	// sum is even
}


NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys:
                        [NSNumber numberWithInt:13], @"hello",
                        [NSNumber numberWithInt:31], @"world",
                        [NSNumber numberWithInt:71], @"!", nil];

// iterating over keys:
for (id key in myDict) {
    NSLog(@"key = %@", key);
}

// iterating over values:
for (id value in [myDict objectEnumerator]) {
    NSLog(@"value = %@", value);
}


#!/usr/bin/env ocaml

let map = [| ('A', 1); ('B', 2); ('C', 3) |] ;;

(* iterate over pairs *)
Array.iter (fun (k,v) -> Printf.printf "key: %c - value: %d\n" k v) map ;;

(* iterate over keys *)
Array.iter (fun (k,_) -> Printf.printf "key: %c\n" k) map ;;

(* iterate over values *)
Array.iter (fun (_,v) -> Printf.printf "value: %d\n" v) map ;;

(* in functional programming it is often more useful to fold over the elements *)
Array.fold_left (fun acc (k,v) -> acc ^ Printf.sprintf "key: %c - value: %d\n" k v) "Elements:\n" map ;;


open generic

type Door = Open | Closed
  deriving Show

gate [] _ = []
gate (x::xs) (y::ys)
  | x == y = Open :: gate xs ys
  | else = Closed :: gate xs ys

run n = gate [1..n] [& k*k \\ k <- [1..]]


defmodule Average do
  def mean(list), do: Enum.sum(list) / length(list)
end


(defun mean (lst)
  (/ (float (apply '+ lst)) (length lst)))
(mean '(1 2 3 4))


mean([]) -> 0;
mean(L)  -> lists:sum(L)/erlang:length(L).


;;; create sample associative array
(define aa (list->ff '(
   (hello . 1)
   (world . 2)
   (! . 3))))

(print aa)
; ==> #((! . 3) (hello . 1) (world . 2))

;;; simplest iteration over all associative array (using ff-iter, lazy iterator)
(let loop ((kv (ff-iter aa)))
   (cond
      ((null? kv) #true)
      ((pair? kv)
         (print (car kv))
         (loop (cdr kv)))
      (else (loop (force kv)))))
; ==> (! . 3)
; ==> (hello . 1)
; ==> (world . 2)

;;; iteration with returning value (using ff-fold)
(print
   "folding result: "
   (ff-fold
      (lambda (result key value)
         (print "key: " key ", value: " value)
         (+ result 1))
      0
      aa))

; ==> key: !, value: 3
; ==> key: hello, value: 1
; ==> key: world, value: 2
; ==> folding result: 3

;;; same but right fold (using ff-foldr)
(print
   "rfolding result: "
   (ff-foldr
      (lambda (result key value)
         (print "key: " key ", value: " value)
         (+ result 1))
      0
      aa))

; ==> key: world, value: 2
; ==> key: hello, value: 1
; ==> key: !, value: 3
; ==> rfolding result: 3

;;; at least create new array from existing (let's multiply every value by value)
(define bb (ff-map aa
      (lambda (key value)
         (* value value))))
(print bb)

; ==> #((! . 9) (hello . 1) (world . 4))


d = .directory~new
d["hello"] = 1
d["world"] = 2
d["!"] = 3

-- iterating over keys:
loop key over d
    say "key =" key
end

-- iterating over values:
loop value over d~allitems
    say "value =" value
end

-- iterating over key-value pairs:
s = d~supplier
loop while s~available
    say "key =" s~index", value =" s~item
    s~next
end


declare
  MyMap = unit('hello':13 'world':31 '!':71)
in
  {ForAll {Record.toListInd MyMap} Show}  %% pairs
  {ForAll {Record.arity     MyMap} Show}  %% keys
  {ForAll {Record.toList    MyMap} Show}  %% values


import system'routines;
import extensions;

public program()
{
    var Doors := Array.allocate(100).populate:(n=>false);
    for(int i := 0, i < 100, i := i + 1)
    {
        for(int j := i, j < 100, j := j + i + 1)
        {
            Doors[j] := Doors[j].Inverted
        }
    };

    for(int i := 0, i < 100, i := i + 1)
    {
        console.printLine("Door #",i + 1," :",Doors[i].iif("Open","Closed"))
    };

    console.readChar()
}


function mean(sequence s)
  atom sum
  if length(s) = 0 then
    return 0
  else
    sum = 0
    for i = 1 to length(s) do
      sum += s[i]
    end for
    return sum/length(s)
  end if
end function

sequence test
test = {1.0, 2.0, 5.0, -5.0, 9.5, 3.14159}
? mean(test)


let avg (a:float) (v:float) n =
    a + (1. / ((float n) + 1.)) * (v - a)

let mean_series list =
    let a, _ = List.fold_left (fun (a, n) h -> avg a (float h) n, n + 1) (0., 0) list in
    a


#! /usr/bin/perl
use strict;

my %pairs = ( "hello" => 13,
	      "world" => 31,
	      "!" => 71 );

# iterate over pairs

# Be careful when using each(), however, because it uses a global iterator
# associated with the hash. If you call keys() or values() on the hash in the
# middle of the loop, the each() iterator will be reset to the beginning. If
# you call each() on the hash somewhere in the middle of the loop, it will
# skip over elements for the "outer" each(). Only use each() if you are sure
# that the code inside the loop will not call keys(), values(), or each().
while ( my ($k, $v) = each %pairs) {
    print "(k,v) = ($k, $v)\n";
}

# iterate over keys
foreach my $key ( keys %pairs ) {
    print "key = $key, value = $pairs{$key}\n";
}
# or (see note about each() above)
while ( my $key = each %pairs) {
    print "key = $key, value = $pairs{$key}\n";
}

# iterate over values
foreach my $val ( values %pairs ) {
    print "value = $val\n";
}