defmodule HundredDoors do
  def doors(n \\ 100) do
    List.duplicate(false, n)
  end

  def toggle(doors, n) do
    List.update_at(doors, n, &(!&1))
  end

  def toggle_every(doors, n) do
    Enum.reduce( Enum.take_every((n-1)..99, n), doors, fn(n, acc) -> toggle(acc, n) end )
  end
end

# unoptimized
final_state = Enum.reduce(1..100, HundredDoors.doors, fn(n, acc) -> HundredDoors.toggle_every(acc, n) end)

open_doors = Enum.with_index(final_state)
             |> Enum.filter_map(fn {door,_} -> door end, fn {_,index} -> index+1 end)

IO.puts "All doors are closed except these: #{inspect open_doors}"

# optimized
final_state = Enum.reduce(1..10, HundredDoors.doors, fn(n, acc) -> HundredDoors.toggle(acc, n*n-1) end)

open_doors = Enum.with_index(final_state)
             |> Enum.filter_map(fn {door,_} -> door end, fn {_,index} -> index+1 end)

IO.puts "All doors are closed except these: #{inspect open_doors}"


USING: math math.statistics ;

: arithmetic-mean ( seq -- n )
    [ 0 ] [ mean ] if-empty ;


class Main
{
  static Float average (Float[] nums)
  {
    if (nums.size == 0) return 0.0f
    Float sum := 0f
    nums.each |num| { sum += num }
    return sum / nums.size.toFloat
  }

  public static Void main ()
  {
    [[,], [1f], [1f,2f,3f,4f]].each |Float[] i|
    {
      echo ("Average of $i is: " + average(i))
    }
  }
}


with javascript_semantics
setd("one",1)
setd(2,"duo")
setd({3,4},{5,"six"})

function visitor(object key, object data, object /*userdata*/)
    ?{key,data}
    return 1    -- (continue traversal)
end function
traverse_dict(routine_id("visitor"))


include ..\Utilitys.pmt

def getd    /# dict key -- dict data #/
    swap 1 get rot find nip
    dup if
        swap 2 get rot get nip
    else
        drop "Unfound"
    endif
enddef

def setd    /# dict ( key data ) -- dict #/
    1 get var ikey
    2 get var idata
    drop
    1 get ikey find var p drop
    p if
        2 get idata p set 2 set
    else
        2 get idata 0 put 2 set
        1 get ikey 0 put 1 set
    endif
enddef

def pair    /# dict n -- dict ( k d ) #/
    1 over 2 tolist var ikey
    2 swap 2 tolist var idata
    ikey sget
    swap idata sget rot swap
    2 tolist
enddef

def scandict    /# dict n -- dict ( ) #/
    var n
    1 get len nip
    for
        pair
        n if n get nip endif
        print nl
    endfor
enddef

def pairs   /# dict -- dict ( ) #/
    0 scandict
enddef

def keys
    1 scandict
enddef

def values
    2 scandict
enddef

/# ---------- MAIN ---------- #/

( ( ) ( ) )

( "one" 1 ) setd
( 2 "duo" ) setd
( ( 3 4 ) ( 5 "six" ) ) setd

pairs nl
keys nl
values


-- Unoptimized
import List exposing (indexedMap, foldl, repeat, range)
import Html exposing (text)
import Debug exposing (toString)

type Door = Open | Closed

toggle d = if d == Open then Closed else Open

toggleEvery : Int -> List Door -> List Door
toggleEvery k doors = indexedMap
  (\i door -> if modBy k (i+1) == 0 then toggle door else door)
  doors

n = 100

main =
  text (toString (foldl toggleEvery (repeat n Closed) (range 1 n)))


: fmean ( addr n -- f )
  0e
  dup 0= if 2drop exit then
  tuck floats bounds do
    i [email protected] f+
  1 floats +loop
  0 d>f f/ ;

create test 3e f, 1e f, 4e f, 1e f, 5e f, 9e f,
test 6 fmean f.     \ 3.83333333333333


real, target, dimension(100) :: a = (/ (i, i=1, 100) /)
real, dimension(5,20) :: b = reshape( a, (/ 5,20 /) )
real, pointer, dimension(:) :: p => a(2:1)       ! pointer to zero-length array
real :: mean, zmean, bmean
real, dimension(20) :: colmeans
real, dimension(5) :: rowmeans

mean = sum(a)/size(a)                ! SUM of A's elements divided by SIZE of A
mean = sum(a)/max(size(a),1)         ! Same result, but safer code
                                     ! MAX of SIZE and 1 prevents divide by zero if SIZE == 0 (zero-length array)

zmean = sum(p)/max(size(p),1)        ! Here the safety check pays off. Since P is a zero-length array,
                                     ! expression becomes "0 / MAX( 0, 1 ) -> 0 / 1 -> 0", rather than "0 / 0 -> NaN"

bmean = sum(b)/max(size(b),1)        ! multidimensional SUM over multidimensional SIZE

rowmeans = sum(b,1)/max(size(b,2),1) ! SUM elements in each row (dimension 1)
                                     ! dividing by the length of the row, which is the number of columns (SIZE of dimension 2)
colmeans = sum(b,2)/max(size(b,1),1) ! SUM elements in each column (dimension 2)
                                     ! dividing by the length of the column, which is the number of rows (SIZE of dimension 1)


<?php
$pairs = array( "hello" => 1,
		"world" => 2,
		"!"     => 3 );

// iterate over key-value pairs
foreach($pairs as $k => $v) {
  echo "(k,v) = ($k, $v)\n";
}

// iterate over keys
foreach(array_keys($pairs) as $key) {
  echo "key = $key, value = $pairs[$key]\n";
}

// iterate over values
foreach($pairs as $value) {
  echo "values = $value\n";
}
?>


go =>
  Map = new_map([1=one,2=two,3=three,4=four]),
  foreach(K=V in Map)
    println(K=V)
  end,
  nl,

  println(keys=Map.keys),
  foreach(K in Map.keys.sort)
    println(K=Map.get(K))
  end,
  nl,

  println(values=Map.values),
  foreach(V in Map.values.sort)
    % This works but gets a warning: nonlocal_var_in_iterator_pattern
    % println(V=[K : K=V in Map])

    % No warning:
    println(V=[K : K=V1 in Map,V1 == V])
  end,
  nl.


(put 'A 'foo 5)
(put 'A 'bar 10)
(put 'A 'baz 15)

: (getl 'A)                            # Get the whole property list
-> ((15 . baz) (10 . bar) (5 . foo))

: (mapcar cdr (getl 'A))               # Get all keys
-> (baz bar foo)

: (mapcar car (getl 'A))               # Get all values
-> (15 10 5)


(defun create-doors ()
  "Returns a list of closed doors

Each door only has two status: open or closed.
If a door is closed it has the value 0, if it's open it has the value 1."
  (let ((return_value '(0))
         ;; There is already a door in the return_value, so k starts at 1
         ;; otherwise we would need to compare k against 99 and not 100 in
         ;; the while loop
         (k 1))
    (while (< k 100)
      (setq return_value (cons 0 return_value))
      (setq k (+ 1 k)))
    return_value))

(defun toggle-single-door (doors)
  "Toggle the stat of the door at the `car' position of the DOORS list

DOORS is a list of integers with either the value 0 or 1 and it represents
a row of doors.

Returns a list where the `car' of the list has it's value toggled (if open
it becomes closed, if closed it becomes open)."
  (if (= (car doors) 1)
    (cons 0 (cdr doors))
    (cons 1 (cdr doors))))

(defun toggle-doors (doors step original-step)
  "Step through all elements of the doors' list and toggle a door when step is 1

DOORS is a list of integers with either the value 0 or 1 and it represents
a row of doors.
STEP is the number of doors we still need to transverse before we arrive
at a door that has to be toggled.
ORIGINAL-STEP is the value of the argument step when this function is
called for the first time.

Returns a list of doors"
  (cond ((null doors)
          '())
    ((= step 1)
      (cons (car (toggle-single-door doors))
        (toggle-doors (cdr doors) original-step original-step)))
    (t
      (cons (car doors)
        (toggle-doors (cdr doors) (- step 1) original-step)))))

(defun main-program ()
  "The main loop for the program"
  (let ((doors_list (create-doors))
         (k 1)
         ;; We need to define max-specpdl-size and max-specpdl-size to big
         ;; numbers otherwise the loop reaches the max recursion depth and
         ;; throws an error.
         ;; If you want more information about these variables, press Ctrl
         ;; and h at the same time and then press v and then type the name
         ;; of the variable that you want to read the documentation.
         (max-specpdl-size 5000)
         (max-lisp-eval-depth 2000))
    (while (< k 101)
      (setq doors_list (toggle-doors doors_list k k))
      (setq k (+ 1 k)))
    doors_list))

(defun print-doors (doors)
  "This function prints the values of the doors into the current buffer.

DOORS is a list of integers with either the value 0 or 1 and it represents
a row of doors.
"
  ;; As in the main-program function, we need to set the variable
  ;; max-lisp-eval-depth to a big number so it doesn't reach max recursion
  ;; depth.
  (let ((max-lisp-eval-depth 5000))
    (unless (null doors)
      (insert (int-to-string (car doors)))
      (print-doors (cdr doors)))))

;; Returns a list with the final solution
(main-program)

;; Print the final solution on the buffer
(print-doors (main-program))


' FB 1.05.0 Win64

Function Mean(array() As Double) As Double
  Dim length As Integer = Ubound(array) - Lbound(array) + 1
  If length = 0 Then
    Return 0.0/0.0 'NaN
  End If
  Dim As Double sum = 0.0
  For i As Integer = LBound(array) To UBound(array)
    sum += array(i)
  Next
  Return sum/length
End Function

Function IsNaN(number As Double) As Boolean
  Return Str(number) = "-1.#IND" ' NaN as a string in FB
End Function

Dim As Integer n, i
Dim As Double num
Print "Sample input and output"
Print
Do
  Input "How many numbers are to be input ? : ", n
Loop Until n > 0
Dim vector(1 To N) As Double
Print
For i = 1 to n
  Print "  Number #"; i; " : ";
  Input "", vector(i)
Next
Print
Print "Mean is"; Mean(vector())
Print
Erase vector
num = Mean(vector())
If IsNaN(num) Then
  Print "After clearing the vector, the mean is 'NaN'"
End If
Print
Print "Press any key to quit the program"
Sleep


mean[x] := length[x] > 0 ? sum[x] / length[x] : undef


mapping(string:string) m = ([ "A":"a", "B":"b", "C":"c" ]);
foreach(m; string key; string value)
{
    write(key+value);
}
Result: BbAaCc

// only keys
foreach(m; string key;)
{
    write(key);
}
Result: BAC

// only values
foreach(m;; string value)
{
    write(value);
}
Result: bac


% over keys and values
<</a 1 /b 2 /c 3>> {= =} forall
% just keys
<</a 1 /b 2 /c 3>> {= } forall
% just values
<</a 1 /b 2 /c 3>> {pop =} forall


mydictionary = (red=0xff0000, green=0x00ff00, blue=0x0000ff)

mydictionary each (key, val): (key, ":", val, "\n") join print.
mydictionary each (key): (key, "\n") join print.


-module(hundoors).

-export([go/0]).

toggle(closed) -> open;
toggle(open) -> closed.

go() -> go([closed || _ <- lists:seq(1, 100)],[], 1, 1).
go([], L, N, _I) when N =:= 101 -> lists:reverse(L);
go([], L, N, _I) -> go(lists:reverse(L), [], N + 1, 1);
go([H|T], L, N, I) ->
  H2 = case I rem N of
    0 -> toggle(H);
    _ -> H
  end,
  go(T, [H2|L], N, I + 1).


Mean := function(v)
  local n;
  n := Length(v);
  if n = 0 then
    return 0;
  else
    return Sum(v)/n;
  fi;
end;

Mean([3, 1, 4, 1, 5, 9]);
# 23/6


R (n) P ;
0
1, n rep (i)
   R P +
]
n div
P


DIM a%(10)
FOR i%=0 TO 10
  a%(i%)=i%*2
  PRINT "element ";i%;" is ";a%(i%)
NEXT i%
PRINT "mean is ";@mean(a%)
'
FUNCTION mean(a%)
  LOCAL i%,size%,sum
  ' find size of array,
  size%=DIM?(a%())
  ' return 0 for empty arrays
  IF size%<=0
    RETURN 0
  ENDIF
  ' find sum of all elements
  sum=0
  FOR i%=0 TO size%-1
    sum=sum+a%(i%)
  NEXT i%
  ' mean is sum over size
  RETURN sum/size%
ENDFUNC


assert( mymap(key1,value1) ).
assert( mymap(key2,value1) ).


NewMap dict.s()
dict("de") = "German"
dict("en") = "English"
dict("fr") = "French"

ForEach dict()
  Debug MapKey(dict()) + ":" + dict()
Next


! "100 Doors" program for ERRE LANGUAGE
! Author: Claudio Larini
! Date: 21-Nov-2014
!
! PC Unoptimized version translated from a QB version

PROGRAM 100DOORS

!$INTEGER

CONST N=100

DIM DOOR[N]

BEGIN

FOR STRIDE=1 TO N DO
    FOR INDEX=STRIDE TO N STEP STRIDE DO
        DOOR[INDEX]=NOT(DOOR[INDEX])
    END FOR
END FOR

PRINT("Open doors:";)
FOR INDEX=1 TO N DO
    IF DOOR[INDEX] THEN PRINT(INDEX;) END IF
END FOR
PRINT

END PROGRAM


package main

import (
    "fmt"
    "math"
)

func mean(v []float64) (m float64, ok bool) {
    if len(v) == 0 {
        return
    }
    // an algorithm that attempts to retain accuracy
    // with widely different values.
    var parts []float64
    for _, x := range v {
        var i int
        for _, p := range parts {
            sum := p + x
            var err float64
            switch ax, ap := math.Abs(x), math.Abs(p); {
            case ax < ap:
                err = x - (sum - p)
            case ap < ax:
                err = p - (sum - x)
            }
            if err != 0 {
                parts[i] = err
                i++
            }
            x = sum
        }
        parts = append(parts[:i], x)
    }
    var sum float64
    for _, x := range parts {
        sum += x
    }
    return sum / float64(len(v)), true
}

func main() {
    for _, v := range [][]float64{
        []float64{},                         // mean returns ok = false
        []float64{math.Inf(1), math.Inf(1)}, // answer is +Inf

        // answer is NaN, and mean returns ok = true, indicating NaN
        // is the correct result
        []float64{math.Inf(1), math.Inf(-1)},

        []float64{3, 1, 4, 1, 5, 9},

        // large magnitude numbers cancel. answer is mean of small numbers.
        []float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},

        []float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},
        []float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},
    } {
        fmt.Println("Vector:", v)
        if m, ok := mean(v); ok {
            fmt.Printf("Mean of %d numbers is %g\n\n", len(v), m)
        } else {
            fmt.Println("Mean undefined\n")
        }
    }
}


myDict = { "hello": 13,
	   "world": 31,
	   "!"    : 71 }

# iterating over key-value pairs:
for key, value in myDict.items():
    print ("key = %s, value = %s" % (key, value))

# iterating over keys:
for key in myDict:
    print ("key = %s" % key)
# (is a shortcut for:)
for key in myDict.keys():
    print ("key = %s" % key)

# iterating over values:
for value in myDict.values():
    print ("value = %s" % value)


'dictionary is not native data type of QB64
' here a dictionary engine using a string to store data
Dim Shared Skey As String * 1, SValue As String * 1, EValue As String * 1
Skey = Chr$(0)
SValue = Chr$(1)
EValue = Chr$(255)

'Demo area---------------->
Dim MyDictionary As String

If ChangeValue(MyDictionary, "a", "Ananas") Then Print "added new couple key value"
If ChangeValue(MyDictionary, "b", "Banana") Then Print "added new couple key value"
If ChangeValue(MyDictionary, "c", "cherry") Then Print "added new couple key value"
If ChangeValue(MyDictionary, "d", "Drake") Then Print "added new couple key value"
If ChangeValue(MyDictionary, "e", "Elm") Then Print "added new couple key value"
If ChangeValue(MyDictionary, "f", "Fire") Then Print "added new couple key value"
Print LenDict(MyDictionary)
Print "to key e there is  "; GetDict$(MyDictionary, "e")
Print "to key e there is  "; GetDict$(MyDictionary, "a")
If ChangeValue(MyDictionary, "e", "Elephant") Then Print " changed value of key passed"
Print "to key e there is  "; GetDict$(MyDictionary, "e")
If Not (EraseKeyValue(MyDictionary, "e")) Then Print " Failed to erase key value passed" Else Print "Erased key value passed"
If GetDict$(MyDictionary, "e") = "" Then Print " No couple key value found for key value 'e'"
If ChangeKey(MyDictionary, "e", "f") = 0 Then
    Print "key -a- has value "; GetDict$(MyDictionary, "a")
    Print "we change key a to key e "
    If ChangeKey(MyDictionary, "a", "e") = -1 Then
        Print "key -a- has value "; GetDict$(MyDictionary, "a")
        Print "key -e- has value "; GetDict$(MyDictionary, "e")
    End If
End If
If InsertCouple(MyDictionary, "c", "m", "mellon") = -1 Then
    Print " New couple inserted after key -c- "; GetDict$(MyDictionary, "c")
    Print " new couple is  key -m- "; GetDict$(MyDictionary, "m")
End If
Print LenDict(MyDictionary)
' End demo area --------------->
End

' it returns value/s for a key
Function GetDict$ (dict As String, Keys As String)
    Dim StartK As Integer, StartV As Integer, EndV As Integer
    StartK = InStr(dict, Skey + Keys + SValue)
    StartV = InStr(StartK, dict, SValue)
    EndV = InStr(StartV, dict, EValue)
    If StartK = 0 Then GetDict$ = "" Else GetDict = Mid$(dict, StartV + 1, EndV - StartV)
End Function

' it changes value of a key or append the couple key, newvalue if key is new
Function ChangeValue (dict As String, Keys As String, NewValue As String)
    ChangeValue = 0
    Dim StartK As Integer, StartV As Integer, EndV As Integer
    StartK = InStr(dict, Skey + Keys + SValue)
    StartV = InStr(StartK, dict, SValue)
    EndV = InStr(StartV, dict, EValue)
    If StartK = 0 Then
        dict = dict + Skey + Keys + SValue + NewValue + EValue
    Else
        dict = Left$(dict, StartV) + NewValue + Right$(dict, Len(dict) - EndV + 1)
    End If
    ChangeValue = -1
End Function

'it changes a key if it is in the dictionary
Function ChangeKey (dict As String, Keys As String, NewKey As String)
    ChangeKey = 0
    Dim StartK As Integer, StartV As Integer
    StartK = InStr(dict, Skey + Keys + SValue)
    StartV = InStr(StartK, dict, SValue)
    If StartK = 0 Then
        Print "Key " + Keys + " not found"
        Exit Function
    Else
        dict = Left$(dict, StartK) + NewKey + Right$(dict, Len(dict) - StartV + 1)
    End If
    ChangeKey = -1
End Function

'it erases the couple key value
Function EraseKeyValue (dict As String, keys As String)
    EraseKeyValue = 0
    Dim StartK As Integer, StartV As Integer, EndV As Integer
    StartK = InStr(dict, Skey + keys + SValue)
    StartV = InStr(StartK, dict, SValue)
    EndV = InStr(StartV, dict, EValue)
    If StartK = 0 Then
        Exit Function
    Else
        dict = Left$(dict, StartK - 1) + Right$(dict, Len(dict) - EndV + 1)
    End If
    EraseKeyValue = -1
End Function

'it inserts a couple after a defined key, if key is not in dictionary it append couple key value
Function InsertCouple (dict As String, SKeys As String, Keys As String, Value As String)
    InsertCouple = 0
    Dim StartK As Integer, StartV As Integer, EndV As Integer
    StartK = InStr(dict, Skey + SKeys + SValue)
    StartV = InStr(StartK, dict, SValue)
    EndV = InStr(StartV, dict, EValue)
    If StartK = 0 Then
        dict = dict + Skey + Keys + SValue + Value + EValue
    Else
        dict = Left$(dict, EndV) + Skey + Keys + SValue + Value + EValue + Right$(dict, Len(dict) - EndV + 1)
    End If
    InsertCouple = -1
End Function

Function LenDict (dict As String)
    LenDict = 0
    Dim a As Integer, count As Integer
    If Len(dict) <= 0 Then Exit Function
    While a <= Len(dict)
        a = InStr(a + 1, dict, EValue)
        If a > 0 Then count = count + 1 Else Exit While
    Wend
    LenDict = count
End Function


>function Doors () ...
$  doors:=zeros(1,100);
$  for i=1 to 100
$    for j=i to 100 step i
$      doors[j]=!doors[j];
$    end;
$  end;
$  return doors
$endfunction
>nonzeros(Doors())
 [ 1  4  9  16  25  36  49  64  81  100 ]


def avg = { list -> list == [] ? 0 : list.sum() / list.size() }


mean :: (Fractional a) => [a] -> a
mean [] = 0
mean xs = sum xs / Data.List.genericLength xs


REAL :: vec(100)               ! no zero-length arrays in HicEst

   vec = $ - 1/2               ! 0.5 ... 99.5
   mean = SUM(vec) / LEN(vec)  ! 50
END


#lang racket

(define dict1 #hash((apple . 5) (orange . 10))) ; hash table
(define dict2 '((apple . 5) (orange . 10)))     ; a-list
(define dict3 (vector "a" "b" "c"))             ; vector (integer keys)

(dict-keys dict1)                   ; => '(orange apple)
(dict-values dict2)                 ; => '(5 10)
(for/list ([(k v) (in-dict dict3)]) ; => '("0 -> a" "1 -> b" "2 -> c")
  (format "~a -> ~a" k v))


my %pairs = hello => 13, world => 31, '!' => 71;

for %pairs.kv -> $k, $v {
    say "(k,v) = ($k, $v)";
}

# Stable order
for %pairs.sort(*.value)>>.kv -> ($k, $v) {
    say "(k,v) = ($k, $v)";
}

{ say "$^a => $^b" } for %pairs.kv;

say "key = $_" for %pairs.keys;

say "value = $_" for %pairs.values;


/*REXX program demonstrates how to  set and display  values  for an  associative array. */
/*╔════════════════════════════════════════════════════════════════════════════════════╗
  ║ The (below) two REXX statements aren't really necessary,  but it shows how to      ║
  ║ define any and all entries in a associative array so that if a "key" is used that  ║
  ║ isn't defined, it can be displayed to indicate such,  or its value can be checked  ║
  ║ to determine if a particular associative array element has been set (defined).     ║
  ╚════════════════════════════════════════════════════════════════════════════════════╝*/
stateF.= ' [not defined yet] '                   /*sets any/all state  former  capitals.*/
stateN.= ' [not defined yet] '                   /*sets any/all state names.            */
w      = 0                                       /*the maximum  length  of a state name.*/
stateL =
/*╔════════════════════════════════════════════════════════════════════════════════════╗
  ║ The list of states (empty as of now).  It's convenient to have them in alphabetic  ║
  ║ order;  they'll be listed in the order as they are in the REXX program below).     ║
  ║ In REXX,  when a key is used  (for a stemmed array,  as they are called in REXX),  ║
  ║ and the key isn't assigned a value,  the key's  name  is stored (internally)  as   ║
  ║ uppercase  (Latin)  characters  (as in the examples below.   If the  key  has a    ║
  ║ a value, the key's value is used as is  (i.e.:  no upper translation is performed).║
  ║ Actually,  any characters can be used,  including blank(s)  and  non─displayable   ║
  ║ characters  (including   '00'x,   'ff'x,   commas,   periods,   quotes,   ···).    ║
  ╚════════════════════════════════════════════════════════════════════════════════════╝*/
call setSC 'al',  "Alabama"            ,  'Tuscaloosa'
call setSC 'ca',  "California"         ,  'Benicia'
call setSC 'co',  "Colorado"           ,  'Denver City'
call setSC 'ct',  "Connecticut"        ,  'Hartford and New Haven  (jointly)'
call setSC 'de',  "Delaware"           ,  'New-Castle'
call setSC 'ga',  "Georgia"            ,  'Milledgeville'
call setSC 'il',  "Illinois"           ,  'Vandalia'
call setSC 'in',  "Indiana"            ,  'Corydon'
call setSC 'ia',  "Iowa"               ,  'Iowa City'
call setSC 'la',  "Louisiana"          ,  'New Orleans'
call setSC 'me',  "Maine"              ,  'Portland'
call setSC 'mi',  "Michigan"           ,  'Detroit'
call setSC 'ms',  "Mississippi"        ,  'Natchez'
call setSC 'mo',  "Missouri"           ,  'Saint Charles'
call setSC 'mt',  "Montana"            ,  'Virginia City'
call setSC 'ne',  "Nebraska"           ,  'Lancaster'
call setSC 'nh',  "New Hampshire"      ,  'Exeter'
call setSC 'ny',  "New York"           ,  'New York'
call setSC 'nc',  "North Carolina"     ,  'Fayetteville'
call setSC 'oh',  "Ohio"               ,  'Chillicothe'
call setSC 'ok',  "Oklahoma"           ,  'Guthrie'
call setSC 'pa',  "Pennsylvania"       ,  'Lancaster'
call setSC 'sc',  "South Carolina"     ,  'Charlestown'
call setSC 'tn',  "Tennessee"          ,  'Murfreesboro'
call setSC 'vt',  "Vermont"            ,  'Windsor'

       do j=1  for words(stateL)                 /*show all capitals that were defined. */
       $= word(stateL, j)                        /*get the next (USA) state in the list.*/
       say 'the former capital of  ('$") "    left(stateN.$, w)      " was "      stateC.$
       end    /*j*/                              /* [↑]   show states that were defined.*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
setSC: parse arg code,name,cap;   upper code     /*get code, name & cap.; uppercase code*/
       stateL= stateL code                       /*keep a list of all the US state codes*/
       stateN.code= name; w= max(w,length(name)) /*define the state's name;  max width. */
       stateC.code= cap                          /*   "    "     "   code to the capital*/
       return                                    /*return to invoker, SETSC is finished.*/


-- doors.ex
include std/console.e
sequence doors
doors = repeat( 0, 100 ) -- 1 to 100, initialised to false

for pass = 1 to 100 do
	for door = pass to 100 by pass do
		--printf( 1, "%d", doors[door] )
		--printf( 1, "%d", not doors[door] )
		doors[door] = not doors[door]
	end for
end for

sequence oc

for i = 1 to 100 do
	if doors[i] then
		oc = "open"
	else
		oc = "closed"
	end if
 	printf( 1, "door %d is %s\n", { i, oc } )
end for


(defn arithmetic-mean [xs]
    (if xs
        (/ (sum xs) (len xs))))


procedure main(args)
    every (s := 0) +:= !args
    write((real(s)/(0 ~= *args)) | 0)
end


# Project : Associative array/Iteration

lst = [["hello", 13], ["world", 31], ["!", 71]]
for n = 1 to len(lst)
    see lst[n][1] + " : " + lst[n][2] + nl
next


x = <<>>;  // create an empty list
x.hello = 1;
x.world = 2;
x.["!"] = 3;

// to iterate over identifiers of a list one needs to use the function ''members''
// the identifiers are returned as a lexicographically ordered string row-vector
// here    ["!", "hello", "world"]
for(i in members(x))
{ printf("%s %g\n", i,  x.[i]); }

// occasionally one needs to check if there exists member of a list
y = members(x);  // y contains ["!", "hello", "world"]
clear(x.["!"]);  // remove member with identifier "!" from the list "x"
for(i in y)
{ printf("%s %g\n", i,  x.[i]); }  // this produces error because x.["!"] does not exist

for(i in y)
{
  if (exist(x.[i]))
  { printf("%s %g\n", i,  x.[i]); }  // we print a member of the list "x" only if it exists
}


my_dict = { "hello" => 13,
	   "world" => 31,
	   "!"     => 71 }

# iterating over key-value pairs:
my_dict.each {|key, value| puts "key = #{key}, value = #{value}"}
# or
my_dict.each_pair {|key, value| puts "key = #{key}, value = #{value}"}

# iterating over keys:
my_dict.each_key {|key| puts "key = #{key}"}

# iterating over values:
my_dict.each_value {|value| puts "value =#{value}"}


public static double avg(double... arr) {
    double sum = 0.0;
    for (double x : arr) {
        sum += x;
    }
    return sum / arr.length;
}


function mean(array)
{
 var sum = 0, i;
 for (i = 0; i < array.length; i++)
 {
  sum += array[i];
 }
  return array.length ? sum / array.length : 0;
}

alert( mean( [1,2,3,4,5] ) );   // 3
alert( mean( [] ) );            // 0


use std::collections::HashMap;
fn main() {
    let mut olympic_medals = HashMap::new();
    olympic_medals.insert("United States", (1072, 859, 749));
    olympic_medals.insert("Soviet Union", (473, 376, 355));
    olympic_medals.insert("Great Britain", (246, 276, 284));
    olympic_medals.insert("Germany", (252, 260, 270));
    for (country, medals) in olympic_medals {
        println!("{} has had {} gold medals, {} silver medals, and {} bronze medals",
               country, medals.0, medals.1, medals.2);

    }
}


val m = Map("Amsterdam" -> "Netherlands", "New York" -> "USA", "Heemstede" -> "Netherlands")

println(f"Key->Value: ${m.mkString(", ")}%s")
println(f"Pairs: ${m.toList.mkString(", ")}%s")
println(f"Keys: ${m.keys.mkString(", ")}%s")
println(f"Values: ${m.values.mkString(", ")}%s")
println(f"Unique values: ${m.values.toSet.mkString(", ")}%s")


;; Create an associative array (hash-table) whose keys are strings:
(define table (hash-table 'string=?
  '("hello" . 0) '("world" . 22) '("!" . 999)))

;; Iterate over the table, passing the key and the value of each entry
;; as arguments to a function:
(hash-table-for-each
  table
  ;; Create by "partial application" a function that accepts 2 arguments,
  ;; the key and the value:
  (pa$ format #t "Key = ~a, Value = ~a\n"))


let answerDoors =
    let ToggleNth n (lst:bool array) =                  // Toggle every n'th door
        [(n-1) .. n .. 99]                              // For each appropriate door
        |> Seq.iter (fun i -> lst.[i] <- not lst.[i])   // toggle it
    let doors = Array.create 100 false                  // Initialize all doors to closed
    Seq.iter (fun n -> ToggleNth n doors) [1..100]      // toggle the appropriate doors for each pass
    doors                                               // Initialize all doors to closed


julia> using Statistics; mean([1,2,3])
2.0
julia> mean(1:10)
5.5
julia> mean([])
ERROR: mean of empty collection undefined: []


  mean: {(+/x)%#x}
  mean 1 2 3 5 7
3.6
  [email protected]!0    / empty array
0.0


V n = 20
F z(=n)
   I n == 0
      R [0]
   V fib = [2, 1]
   L fib[0] < n
      fib = [sum(fib[0.<2])] [+] fib
   [Int] dig
   L(f) fib
      I f <= n
         dig [+]= 1
         n -= f
      E
         dig [+]= 0
   R I dig[0] {dig} E dig[1..]

L(i) 0..n
   print(‘#3: #8’.format(i, z(i).map(d -> String(d)).join(‘’)))


$ include "seed7_05.s7i";

const type: dictType is hash [string] integer;
var dictType: myDict is dictType.value;

const proc: main is func
  local
    var string: stri is "";
    var integer: number is 0;
  begin
    myDict @:= ["hello"] 1;
    myDict @:= ["world"] 2;
    myDict @:= ["!"] 3;

    # iterating over key-value pairs:
    for number key stri range myDict do
      writeln("key = " <& number <& ", value = " <& stri);
    end for;

    # iterating over keys:
    for key stri range myDict do
      writeln("key = " <& stri);
    end for;

    # iterating over values:
    for number range myDict do
      writeln("value = " <& number);
    end for;
  end func;


put {name:"Fluffy", type:"Rabbit", color:"White"} into animal
put "Carries a watch" into animal's habits

put "The animal: " & animal
put "The keys: " & keys of animal
put "The values: " & animal's values
// Keys and Values
put ,"All Properties:"
repeat with each [key,value] in animal
	put !"Key: [[key]]  Value: [[value]]"
end repeat

// Keys only
put ,"Keys:"
repeat with each [key] in animal
	put key
end repeat

// Values only
put ,"Values:"
repeat with each [,value] in animal
	put value
end repeat

// Using an iterator
put ,"Treating the property list as an iterator:"
put animal's nextValue -- calling any of the "next" functions begins iteration
put animal's nextKeyValue
put animal's nextKey
put animal's nextKeyValue
put animal's nextValue -- walking off the end returns a unique endValue


var hash = Hash.new(
    key1 => 'value1',
    key2 => 'value2',
)

# Iterate over key-value pairs
hash.each { |key, value|
    say "#{key}: #{value}";
}

# Iterate only over keys
hash.keys.each { |key|
    say key;
}

# Iterate only over values
hash.values.each { |value|
    say value;
}


USING: bit-arrays formatting fry kernel math math.ranges
sequences ;
IN: rosetta.doors

CONSTANT: number-of-doors 100

: multiples ( n -- range )
    0 number-of-doors rot <range> ;

: toggle-multiples ( n doors -- )
    [ multiples ] dip '[ _ [ not ] change-nth ] each ;

: toggle-all-multiples ( doors -- )
    [ number-of-doors [1,b] ] dip '[ _ toggle-multiples ] each ;

: print-doors ( doors -- )
    [
        swap "open" "closed" ? "Door %d is %s\n" printf
    ] each-index ;

: main ( -- )
    number-of-doors 1 + <bit-array>
    [ toggle-all-multiples ] [ print-doors ] bi ;

main


fun main(args: Array<String>) {
    val nums = doubleArrayOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)
    println("average = %f".format(nums.average()))
}


let dataset = datatable(values:real)[
                        1,      1.5,    3,  5,      6.5];

dataset|summarize avg(values)


{def mean
 {lambda {:s}
  {if {S.empty? :s}
   then 0
   else {/ {+ :s} {S.length :s}}}}}

{mean {S.serie 0 1000}}
-> 500


*        Zeckendorf number representation  04/04/2017
ZECKEN   CSECT
         USING  ZECKEN,R13         base register
         B      72(R15)            skip savearea
         DC     17F'0'             savearea
         STM    R14,R12,12(R13)    save previous context
         ST     R13,4(R15)         link backward
         ST     R15,8(R13)         link forward
         LR     R13,R15            set addressability
         LA     R6,0               i=0
       DO WHILE=(C,R6,LE,=A(20))   do i=0 to 20
         MVC    PG,=CL80'xx : '      init buffer
         LA     R10,PG               pgi=0
         XDECO  R6,XDEC              i
         MVC    0(2,R10),XDEC+10     output i
         LA     R10,5(R10)           pgi+=5
         MVC    FIB,=A(1)            fib(1)=1
         MVC    FIB+4,=A(2)          fib(2)=2
         LA     R7,2                 j=2
         LR     R1,R7                j
         SLA    R1,2                 @fib(j)
       DO WHILE=(C,R6,GT,FIB-4(R1)   do while fib(j)<i
         LA     R7,1(R7)               j++
         LR     R1,R7                  j
         SLA    R1,2                   ~
         L      R2,FIB-8(R1)           fib(j-1)
         A      R2,FIB-12(R1)          fib(j-2)
         ST     R2,FIB-4(R1)           fib(j)=fib(j-1)+fib(j-2)
         LR     R1,R7                  j
         SLA    R1,2                   @fib(j)
       ENDDO    ,                    enddo j
         LR     R8,R6                k=i
         MVI    BB,X'00'             bb=false
       DO WHILE=(C,R7,GE,=A(1))      do j=j to 1 by -1
         LR     R1,R7                  j
         SLA    R1,2                   ~
       IF C,R8,GE,FIB-4(R1) THEN       if fib(j)<=k then
         MVI    BB,X'01'                 bb=true
         MVC    0(1,R10),=C'1'           output '1'
         LA     R10,1(R10)               pgi+=1
         LR     R1,R7                    j
         SLA    R1,2                     ~
         S      R8,FIB-4(R1)             k=k-fib(j)
       ELSE     ,                      else
       IF CLI,BB,EQ,X'01' THEN           if bb then
         MVC    0(1,R10),=C'0'             output '0'
         LA     R10,1(R10)                 pgi+=1
       ENDIF    ,                        endif
       ENDIF    ,                      endif
         BCTR   R7,0                   j--
       ENDDO    ,                    enddo j
       IF CLI,BB,NE,X'01' THEN       if not bb then
         MVC    0(1,R10),=C'0'         output '0'
       ENDIF    ,                    endif
         XPRNT  PG,L'PG              print buffer
         LA     R6,1(R6)             i++
       ENDDO    ,                  enddo i
         L      R13,4(0,R13)       restore previous savearea pointer
         LM     R14,R12,12(R13)    restore previous context
         XR     R15,R15            rc=0
         BR     R14                exit
FIB      DS     32F                Fibonnacci table
BB       DS     X                  flag
PG       DS     CL80               buffer
XDEC     DS     CL12               temp
         YREGS
         END    ZECKEN


PROC Encode(INT x CHAR ARRAY s)
  INT ARRAY fib(22)=
    [1 2 3 5 8 13 21 34 55 89 144 233 377 610
    987 1597 2584 4181 6765 10946 17711 28657]
  INT i
  BYTE append

  IF x=0 THEN
    s(0)=1
    s(1)='0
    RETURN
  FI

  i=21 append=0
  s(0)=0
  WHILE i>=0
  DO
    IF x>=fib(i) THEN
      x==-fib(i)
      s(0)==+1
      s(s(0))='1
      append=1
    ELSEIF append THEN
      s(0)==+1
      s(s(0))='0
    FI
    i==-1
  OD
RETURN

PROC Main()
  INT i
  CHAR ARRAY s(10)

  FOR i=0 TO 20
  DO
    Encode(i,s)
    PrintF("%I -> %S%E",i,s)
  OD
RETURN


with Ada.Text_IO, Ada.Strings.Unbounded;

procedure Print_Zeck is

   function Zeck_Increment(Z: String) return String is
   begin
      if Z="" then
	 return "1";
      elsif Z(Z'Last) = '1' then
	 return Zeck_Increment(Z(Z'First .. Z'Last-1)) & '0';
      elsif Z(Z'Last-1) = '0' then
	 return Z(Z'First .. Z'Last-1) & '1';
      else -- Z has at least two digits and ends with "10"
	 return Zeck_Increment(Z(Z'First .. Z'Last-2)) & "00";
      end if;
   end Zeck_Increment;

   use Ada.Strings.Unbounded;
   Current: Unbounded_String := Null_Unbounded_String;

begin
   for I in 1 .. 20 loop
      Current := To_Unbounded_String(Zeck_Increment(To_String(Current)));
      Ada.Text_IO.Put(To_String(Current) & " ");
   end loop;
end Print_Zeck;


define: #pairs -> ({'hello' -> 1. 'world' -> 2. '!' -> 3. 'another!' -> 3} as: Dictionary).
pairs keysAndValuesDo: [| :key :value |
  inform: '(k, v) = (' ; key printString ; ', ' ; value printString ; ')'
].

pairs keysDo: [| :key |
  inform: '(k, v) = (' ; key printString ; ', ' ; (pairs at: key) printString ; ')'
].

pairs do: [| :value |
  inform: 'value = ' ; value printString
].


|pairs|
pairs := Dictionary
	    from: { 'hello' -> 1. 'world' -> 2. '!' -> 3. 'another!' -> 3 }.

"iterate over keys and values"
pairs keysAndValuesDo: [ :k :v |
    ('(k, v) = (%1, %2)' % { k. v }) displayNl
].

"iterate over keys"
pairs keysDo: [ :key |
    ('key = %1, value = %2' % { key. pairs at: key }) displayNl
].

"iterate over values"
pairs do: [ :value |
    ('value = %1' % { value }) displayNl
].


*       # Create sample table
        t = table()
        t<'cat'> = 'meow'
        t<'dog'> = 'woof'
        t<'pig'> = 'oink'

*       # Convert table to key/value array
        a = convert(t,'array')

*       # Iterate pairs
ploop   i = i + 1; output = a<i,1> ' -> ' a<i,2> :s(ploop)
*       # Iterate keys
kloop   j = j + 1; output = a<j,1> :s(kloop)
*       # Iterate vals
vloop   k = k + 1; output = a<k,2> :s(vloop)
end


doors = arrayBuffer( 101, false )

for pass in [ 0 : doors.len() ]
  for door in [ 0 : doors.len() : pass+1 ]
    doors[ door ] = not doors[ door ]
  end
end

for door in [ 1 : doors.len() ]  // Show Output
  >  "Door ", $door, " is: ", ( doors[ door ] ) ? "open" : "closed"
end


val .mean = f(.x) fold(f{+}, .x) / len(.x)

writeln "  custom: ", .mean([7, 3, 12])
writeln "built-in: ", mean([7, 3, 12])


define average(a::array) => {
	not #a->size ? return 0
	local(x = 0.0)
	with i in #a do => { #x += #i }
	return #x / #a->size
}

average(array(1,2,5,17,7.4)) //6.48


# print some Zeckendorf number representations                             #

# We handle 32-bit numbers, the maximum fibonacci number that can fit in a #
# 32 bit number is F(45)                                                   #

# build a table of 32-bit fibonacci numbers                                #
[ 45 ]INT fibonacci;
fibonacci[ 1 ] := 1;
fibonacci[ 2 ] := 2;
FOR i FROM 3 TO UPB fibonacci DO fibonacci[ i ] := fibonacci[ i - 1 ] + fibonacci[ i - 2 ] OD;

# returns the Zeckendorf representation of n or "?" if one cannot be found #
PROC to zeckendorf = ( INT n )STRING:
     IF n = 0 THEN
        "0"
     ELSE
        STRING result := "";
        INT    f pos  := UPB fibonacci;
        INT    rest   := ABS n;
        # find the first non-zero Zeckendorf digit                        #
        WHILE f pos > LWB fibonacci AND rest < fibonacci[ f pos ] DO
            f pos -:= 1
        OD;
        # if we found a digit, build the representation                   #
        IF f pos >= LWB fibonacci THEN
            # have a digit                                                #
            BOOL skip digit := FALSE;
            WHILE f pos >= LWB fibonacci DO
                IF   rest <= 0 THEN
                    result    +:= "0"
                ELIF skip digit THEN
                    # we used the previous digit                          #
                    skip digit := FALSE;
                    result    +:= "0"
                ELIF rest < fibonacci[ f pos ] THEN
                    # can't use the digit at f pos                        #
                    skip digit := FALSE;
                    result    +:= "0"
                ELSE
                    # can use this digit                                  #
                    skip digit := TRUE;
                    result    +:= "1";
                    rest      -:= fibonacci[ f pos ]
                FI;
                f pos -:= 1
            OD
        FI;
        IF rest = 0 THEN
            # found a representation                                      #
            result
        ELSE
            # can't find a representation                                 #
            "?"
        FI
     FI; # to zeckendorf #

FOR i FROM 0 TO 20 DO
    print( ( whole( i, -3 ), " ", to zeckendorf( i ), newline ) )
OD


--------------------- ZECKENDORF NUMBERS -------------------

-- zeckendorf :: Int -> String
on zeckendorf(n)
    script f
        on |λ|(n, x)
            if n < x then
                [n, 0]
            else
                [n - x, 1]
            end if
        end |λ|
    end script

    if n = 0 then
        {0} as string
    else
        item 2 of mapAccumL(f, n, |reverse|(just of tailMay(fibUntil(n)))) as string
    end if
end zeckendorf

-- fibUntil :: Int -> [Int]
on fibUntil(n)
    set xs to {}
    set limit to n

    script atLimit
        property ceiling : limit
        on |λ|(x)
            (item 2 of x) > (atLimit's ceiling)
        end |λ|
    end script

    script nextPair
        property series : xs
        on |λ|([a, b])
            set nextPair's series to nextPair's series & b
            [b, a + b]
        end |λ|
    end script

    |until|(atLimit, nextPair, {0, 1})
    return nextPair's series
end fibUntil

---------------------------- TEST --------------------------
on run

    intercalate(linefeed, ¬
        map(zeckendorf, enumFromTo(0, 20)))

end run

--------------------- GENERIC FUNCTIONS --------------------

-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
    if m > n then
        set d to -1
    else
        set d to 1
    end if
    set lst to {}
    repeat with i from m to n by d
        set end of lst to i
    end repeat
    return lst
end enumFromTo

-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
    tell mReturn(f)
        set v to startValue
        set lng to length of xs
        repeat with i from 1 to lng
            set v to |λ|(v, item i of xs, i, xs)
        end repeat
        return v
    end tell
end foldl

-- 'The mapAccumL function behaves like a combination of map and foldl;
-- it applies a function to each element of a list, passing an
-- accumulating parameter from left to right, and returning a final
-- value of this accumulator together with the new list.' (see Hoogle)

-- mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
on mapAccumL(f, acc, xs)
    script
        on |λ|(a, x)
            tell mReturn(f) to set pair to |λ|(item 1 of a, x)
            [item 1 of pair, (item 2 of a) & item 2 of pair]
        end |λ|
    end script

    foldl(result, [acc, []], xs)
end mapAccumL

-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map

-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn

-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
    set {dlm, my text item delimiters} to {my text item delimiters, strText}
    set strJoined to lstText as text
    set my text item delimiters to dlm
    return strJoined
end intercalate

-- reverse :: [a] -> [a]
on |reverse|(xs)
    if class of xs is text then
        (reverse of characters of xs) as text
    else
        reverse of xs
    end if
end |reverse|

-- tailMay :: [a] -> Maybe [a]
on tailMay(xs)
    if length of xs > 1 then
        {nothing:false, just:items 2 thru -1 of xs}
    else
        {nothing:true}
    end if
end tailMay

-- until :: (a -> Bool) -> (a -> a) -> a -> a
on |until|(p, f, x)
    set mp to mReturn(p)
    set v to x

    tell mReturn(f)
        repeat until mp's |λ|(v)
            set v to |λ|(v)
        end repeat
    end tell
    return v
end |until|


mata
// Create an associative array
a=asarray_create()
asarray(a,"one",1)
asarray(a,"two",2)

// Loop over entries
loc=asarray_first(a)
do {
	printf("%s %f\n",asarray_key(a,loc),asarray_contents(a,loc))
	loc=asarray_next(a,loc)
} while(loc!=NULL)
end


let myMap = [
	   "hello": 13,
	   "world": 31,
	   "!"    : 71 ]

// iterating over key-value pairs:
for (key, value) in myMap {
    println("key = \(key), value = \(value)")
}


array set myAry {
    # list items here...
}

# Iterate over keys and values
foreach {key value} [array get myAry] {
    puts "$key -> $value"
}

# Iterate over just keys
foreach key [array names myAry] {
    puts "key = $key"
}

# There is nothing for directly iterating over just the values
# Use the keys+values version and ignore the keys


100[$][0 1ø: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\>][$$." ";$["open
"]?~["closed
"]?1+]#                       {loop through doors, print door number and state}


(defun mean (data)
  (/ (lists:sum data)
     (length data)))


total=17
dim nums(total)
for i = 1 to total
    nums(i)=i-1
next

for j = 1 to total
    sum=sum+nums(j)
next
if total=0 then mean=0 else mean=sum/total
print "Arithmetic mean: ";mean


implement Command;

include "sys.m";
sys: Sys;

include "draw.m";

include "sh.m";

init(nil: ref Draw->Context, nil: list of string)
{
	sys = load Sys Sys->PATH;

	a := array[] of {1.0, 2.0, 500.0, 257.0};
	sys->print("mean of a: %f\n", getmean(a));
}

getmean(a: array of real): real
{
	n: real = 0.0;
	for (i := 0; i < len a; i++)
		n += a[i];
	return n / (real len a);
}


Z: function [x][
    if x=0 -> return "0"
    fib: new [2 1]
    n: new x
    while -> n > first fib
          -> insert 'fib 0 fib\0 + fib\1

    result: new ""
    loop fib 'f [
        if? f =< n [
            'result ++ "1"
            'n - f
        ]
        else -> 'result ++ "0"
    ]
    if result\0 = `0` ->
        result: slice result 1 (size result)-1
    return result
]

loop 0..20 'i ->
    print [pad to :string i 3 pad Z i 8]


Fib := NStepSequence(1, 2, 2, 20)
Loop, 21 {
	i := A_Index - 1
	, Out .= i ":`t", n := ""
	Loop, % Fib.MaxIndex() {
		x := Fib.MaxIndex() + 1 - A_Index
		if (Fib[x] <= i)
			n .= 1, i -= Fib[x]
		else
			n .= 0
	}
	Out .= (n ? LTrim(n, "0") : 0) "`n"
}
MsgBox, % Out

NStepSequence(v1, v2, n, k) {
    a := [v1, v2]
	Loop, % k - 2 {
		a[j := A_Index + 2] := 0
		Loop, % j < n + 2 ? j - 1 : n
			a[j] += a[j - A_Index]
	}
	return, a
}


(defvarl h (hash))

(each ((k '(a b c))
       (v '(1 2 3)))
  (set [h k] v))

(dohash (k v h)
  (put-line `@k -> @v`))


typeset -A a=([key1]=value1 [key2]=value2)

# just keys
printf '%s\n' "${!a[@]}"

# just values
printf '%s\n' "${a[@]}"

# keys and values
for key in "${!a[@]}"; do
	printf '%s => %s\n' "$key" "${a[$key]}"
done


using Gee;

void main(){
    // declare HashMap
    var map = new HashMap<string, double?>();

    // set 3 entries
    map["pi"] = 3.14;
    map["e"] = 2.72;
    map["golden"] = 1.62;

    // iterate over (key,value) pair
    foreach (var elem in map.entries){
        string name = elem.key;
        double num = elem.value;

	stdout.printf("%s,%f\n", name, num);
    }

    // iterate over keys
    foreach (string key in map.keys){
	stdout.printf("%s\n", key);
    }

    // iterate over values
    foreach (double num in map.values){
	stdout.printf("%f\n", num);
    }
}


    states := (1..100).toList
    100.times |i| {
      states = states.map |state| { state % (i+1) == 0 ? -state : +state }
    }
    echo("Open doors are " + states.findAll { it < 0 }.map { -it })


-- v can be (2D) point, (3D) vector or list of integers/floats
on mean (v)
    case ilk(v) of
        #point: cnt = 2
        #vector: cnt = 3
        #list: cnt = v.count
        otherwise: return
    end case
    sum = 0
    repeat with i = 1 to cnt
        sum = sum + v[i]
    end repeat
    return float(sum)/cnt
end


average(1,2,3,4,5)  -- 3
average(empty)  -- 0


to average :l
  if empty? :l [output 0]
  output quotient apply "sum :l count :l
end
print average [1 2 3 4]    ; 2.5


For $i = 0 To 20
	ConsoleWrite($i &": "& Zeckendorf($i)&@CRLF)
Next

Func Zeckendorf($int, $Fibarray = "")
	If Not IsArray($Fibarray) Then $Fibarray = Fibonacci($int)
	Local $ret = ""
	For $i = UBound($Fibarray) - 1 To 1 Step -1
		If $Fibarray[$i] > $int And $ret = "" Then ContinueLoop ; dont use Leading  Zeros
		If $Fibarray[$i] > $int Then
			$ret &= "0"
		Else
			If StringRight($ret, 1) <>  "1" Then
				$ret &= "1"
				$int -= $Fibarray[$i]
			Else
				$ret &= "0"
			EndIf
		EndIf
	Next
	If $ret = "" Then $ret = "0"
	Return $ret
EndFunc   ;==>Zeckendorf

Func Fibonacci($max)
	$AList = ObjCreate("System.Collections.ArrayList")
	$AList.add("0")
	$current = 0
	While True
		If $current > 1 Then
			$count = $AList.Count
			$current = $AList.Item($count - 1)
			$current = $current + $AList.Item($count - 2)
		Else
			$current += 1
		EndIf
		$AList.add($current)
		If $current > $max Then ExitLoop
	WEnd
	$Array = $AList.ToArray
	Return $Array
EndFunc   ;==>Fibonacci


Option Explicit
Sub Test()
    Dim h As Object, i As Long, u, v, s
    Set h = CreateObject("Scripting.Dictionary")
    h.Add "A", 1
    h.Add "B", 2
    h.Add "C", 3

    'Iterate on keys
    For Each s In h.Keys
        Debug.Print s
    Next

    'Iterate on values
    For Each s In h.Items
        Debug.Print s
    Next

    'Iterate on both keys and values by creating two arrays
    u = h.Keys
    v = h.Items
    For i = 0 To h.Count - 1
        Debug.Print u(i), v(i)
    Next
End Sub


'instantiate the dictionary object
Set dict = CreateObject("Scripting.Dictionary")

'populate the dictionary or hash table
dict.Add 1,"larry"
dict.Add 2,"curly"
dict.Add 3,"moe"

'iterate key and value pairs
For Each key In dict.Keys
	WScript.StdOut.WriteLine key & " - " & dict.Item(key)
Next


let dict = {"apples": 11, "oranges": 25, "pears": 4}

echo "Iterating over key-value pairs"
for [key, value] in items(dict)
    echo key " => " value
endfor
echo "\n"

echo "Iterating over keys"
for key in keys(dict)
    echo key
endfor
echo "\n"

echo "Iterating over values"
for value in values(dict)
    echo value
endfor


#AppType Console

DIM doors[], n AS INTEGER = 100

FOR DIM i = 1 TO n
	FOR DIM j = i TO n STEP i
		doors[j] = NOT doors[j]
	NEXT
NEXT

FOR i = 1 TO n
	IF doors[i] THEN PRINT "Door ", i, " is open"
NEXT

Pause


:- object(averages).

    :- public(arithmetic/2).

    % fails for empty vectors
    arithmetic([X| Xs], Mean) :-
        sum_and_count([X| Xs], 0, Sum, 0, Count),
        Mean is Sum / Count.

    % use accumulators to make the predicate tail-recursive
    sum_and_count([], Sum, Sum, Count, Count).
    sum_and_count([X| Xs], Sum0, Sum, Count0, Count) :-
        Sum1 is Sum0 + X,
        Count1 is Count0 + 1,
        sum_and_count(Xs, Sum1, Sum, Count1, Count).

:- end_object.


integer MAX_ELEMENTS = 10;
integer MAX_VALUE = 100;
default {
    state_entry() {
        list lst = [];
        integer x = 0;
        for(x=0 ; x<MAX_ELEMENTS ; x++) {
            lst += llFrand(MAX_VALUE);
        }
        llOwnerSay("lst=["+llList2CSV(lst)+"]");
        llOwnerSay("Geometric Mean: "+(string)llListStatistics(LIST_STAT_GEOMETRIC_MEAN, lst));
        llOwnerSay("           Max: "+(string)llListStatistics(LIST_STAT_MAX, lst));
        llOwnerSay("          Mean: "+(string)llListStatistics(LIST_STAT_MEAN, lst));
        llOwnerSay("        Median: "+(string)llListStatistics(LIST_STAT_MEDIAN, lst));
        llOwnerSay("           Min: "+(string)llListStatistics(LIST_STAT_MIN, lst));
        llOwnerSay("     Num Count: "+(string)llListStatistics(LIST_STAT_NUM_COUNT, lst));
        llOwnerSay("         Range: "+(string)llListStatistics(LIST_STAT_RANGE, lst));
        llOwnerSay("       Std Dev: "+(string)llListStatistics(LIST_STAT_STD_DEV, lst));
        llOwnerSay("           Sum: "+(string)llListStatistics(LIST_STAT_SUM, lst));
        llOwnerSay("   Sum Squares: "+(string)llListStatistics(LIST_STAT_SUM_SQUARES, lst));
    }
}


function mean (numlist)
    if type(numlist) ~= 'table' then return numlist end
    num = 0
    table.foreach(numlist,function(i,v) num=num+v end)
    return num / #numlist
end

print (mean({3,1,4,1,5,9}))


      FOR n% = 0 TO 20
        PRINT n% RIGHT$("       " + FNzeckendorf(n%), 8)
      NEXT
      PRINT '"Checking numbers up to 10000..."
      FOR n% = 21 TO 10000
        IF INSTR(FNzeckendorf(n%), "11") STOP
      NEXT
      PRINT "No Zeckendorf numbers contain consecutive 1's"
      END

      DEF FNzeckendorf(n%)
      LOCAL i%, o$, fib%() : DIM fib%(45)
      fib%(0) = 1 : fib%(1) = 1 : i% = 1
      REPEAT
        i% += 1
        fib%(i%) = fib%(i%-1) + fib%(i%-2)
      UNTIL fib%(i%) > n%
      REPEAT
        i% -= 1
        IF n% >= fib%(i%) THEN
          o$ += "1"
          n% -= fib%(i%)
        ELSE
          o$ += "0"
        ENDIF
      UNTIL i% = 1
      = o$


fn main() {
    my_map := {
        "hello": 13,
        "world": 31,
        "!"    : 71 }

    // iterating over key-value pairs:
    for key, value in my_map {
        println("key = $key, value = $value")
    }

    // iterating over keys:
    for key,_ in my_map {
        println("key = $key")
    }

    // iterating over values:
    for _, value in my_map {
        println("value = $value")
    }
}


h <- (table 'a 1 'b 2)
each (key val) table
  prn key " " val


// create a new map with four entries
var capitals = {
    "France": "Paris",
    "Germany": "Berlin",
    "Russia": "Moscow",
    "Spain": "Madrid"
}

// iterate through the map and print out the key/value pairs
for (c in capitals) System.print([c.key, c.value])
System.print()

// iterate though the map and print out just the keys
for (k in capitals.keys) System.print(k)
System.print()

// iterate though the map and print out just the values
for (v in capitals.values) System.print(v)


doors = malloc$ 100u
for uint [0u, sizeof$ doors) with l1 {
  put_byte$ + doors l1 as false byte
}
function void pass(step:uint) {
  location = step
  while <= location sizeof$ doors {
    ac = - + doors location 1u
    put_byte$ ac ~ deref_byte$ ac// true is represented as 255 (0xff)
    location = + location step
  }
}
for uint (0u, sizeof$ doors] with l2 {//range exclusive of 0, inclusive of 100
  pass$ l2
}
count = 1u
for ubyte as doors listubyte with isopen {// list for-each
  if as isopen bool {// cast byte to bool
    puts$ "door "
    putui$ count
    puts$ " is open\n"
  } ;
  count = + count 1u
}
free$ doors


avg(x)
 where
    sum = first(x) fby sum + next(x);
    n = 1 fby n + 1;
    avg = sum / n;
 end


define(`extractdec', `ifelse(eval(`$1%100 < 10'),1,`0',`')eval($1%100)')dnl
define(`fmean', `eval(`($2/$1)/100').extractdec(eval(`$2/$1'))')dnl
define(`mean', `rmean(`$#', [email protected])')dnl
define(`rmean', `ifelse(`$3', `', `fmean($1,$2)',dnl
`rmean($1, eval($2+$3), shift(shift(shift([email protected]))))')')dnl


mean := proc( a :: indexable )
        local   i;
        Normalizer( add( i, i in a ) / numelems( a ) )
end proc:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Zeckendorf
{
    class Program
    {
        private static uint Fibonacci(uint n)
        {
            if (n < 2)
            {
                return n;
            }
            else
            {
                return Fibonacci(n - 1) + Fibonacci(n - 2);
            }
        }

        private static string Zeckendorf(uint num)
        {
            IList<uint> fibonacciNumbers = new List<uint>();
            uint fibPosition = 2;

            uint currentFibonaciNum = Fibonacci(fibPosition);

            do
            {
                fibonacciNumbers.Add(currentFibonaciNum);
                currentFibonaciNum = Fibonacci(++fibPosition);
            } while (currentFibonaciNum <= num);

            uint temp = num;
            StringBuilder output = new StringBuilder();

            foreach (uint item in fibonacciNumbers.Reverse())
            {
                if (item <= temp)
                {
                    output.Append("1");
                    temp -= item;
                }
                else
                {
                    output.Append("0");
                }
            }

            return output.ToString();
        }

        static void Main(string[] args)
        {
            for (uint i = 1; i <= 20; i++)
            {
                string zeckendorfRepresentation = Zeckendorf(i);
                Console.WriteLine(string.Format("{0} : {1}", i, zeckendorfRepresentation));
            }

            Console.ReadKey();
        }
    }
}


// For a class N which implements Zeckendorf numbers:
// I define an increment operation ++()
// I define a comparison operation <=(other N)
// Nigel Galloway October 22nd., 2012
#include <iostream>
class N {
private:
  int dVal = 0, dLen;
public:
  N(char const* x = "0"){
    int i = 0, q = 1;
    for (; x[i] > 0; i++);
    for (dLen = --i/2; i >= 0; i--) {
      dVal+=(x[i]-48)*q;
      q*=2;
  }}
  const N& operator++() {
    for (int i = 0;;i++) {
      if (dLen < i) dLen = i;
      switch ((dVal >> (i*2)) & 3) {
        case 0: dVal += (1 << (i*2)); return *this;
        case 1: dVal += (1 << (i*2)); if (((dVal >> ((i+1)*2)) & 1) != 1) return *this;
        case 2: dVal &= ~(3 << (i*2));
  }}}
  const bool operator<=(const N& other) const {return dVal <= other.dVal;}
  friend std::ostream& operator<<(std::ostream&, const N&);
};
N operator "" N(char const* x) {return N(x);}
std::ostream &operator<<(std::ostream &os, const N &G) {
  const static std::string dig[] {"00","01","10"}, dig1[] {"","1","10"};
  if (G.dVal == 0) return os << "0";
  os << dig1[(G.dVal >> (G.dLen*2)) & 3];
  for (int i = G.dLen-1; i >= 0; i--) os << dig[(G.dVal >> (i*2)) & 3];
  return os;
}


include c:\cxpl\stdlib;
char Dict(10,10);
int  Entries;

proc AddEntry(Letter, Greek);   \Insert entry into associative array
char Letter, Greek;
[Dict(Entries,0):= Letter;
StrCopy(Greek, @Dict(Entries,1));
Entries:= Entries+1;            \(limit checks ignored for simplicity)
];

int I;
[Entries:= 0;
AddEntry(^A, "alpha");
AddEntry(^D, "delta");
AddEntry(^B, "beta");
AddEntry(^C, "gamma");
for I:= 0 to Entries-1 do
    [ChOut(0, Dict(I,0));  ChOut(0, ^ );  Text(0, @Dict(I,1));  CrLf(0)];
]


var d=Dictionary("A","alpha","D","delta", "B","beta", "C", "gamma");
d.keys.pump(Console.print,fcn(k){String(k,",")})
d.values.apply("toUpper").println();
d.makeReadOnly();  // can only iterate over k,v pairs if read only
foreach k,v in (d){print(k,":",v,"; ")}


/*Arithmetic Mean of a large number of Integers
  - or - solve a very large constraint matrix
         over 1 million rows and columns
  Nigel_Galloway
  March 18th., 2008.
*/

param e := 20;
set Sample := {1..2**e-1};

var Mean;
var E{z in Sample};

/* sum of variances is zero */
zumVariance: sum{z in Sample} E[z] = 0;

/* Mean + variance[n] = Sample[n] */
variances{z in Sample}: Mean + E[z] = z;

solve;

printf "The arithmetic mean of the integers from 1 to %d is %f\n", 2**e-1, Mean;

end;


function meanValue = findmean(setOfValues)
   meanValue = mean(setOfValues);
end


(def fibs (lazy-cat [1 1] (map + fibs (rest fibs))))

(defn z [n]
  (if (zero? n)
    "0"
    (let [ps (->> fibs (take-while #(<= % n)) rest reverse)
          fz (fn [[s n] p]
                (if (>= n p)
                  [(conj s 1) (- n p)]
                  [(conj s 0) n]))]
      (->> ps (reduce fz [[] n]) first (apply str)))))

(doseq [n (range 0 21)] (println n (z n)))


% Get list of distinct Fibonacci numbers up to N
fibonacci = proc (n: int) returns (array[int])
    list: array[int] := array[int]$[]
    a: int := 1
    b: int := 2
    while a <= n do
        array[int]$addh(list,a)
        a, b := b, a+b
    end
    return(list)
end fibonacci

% Find the Zeckendorf representation of N
zeckendorf = proc (n: int) returns (string) signals (negative)
    if n<0 then signal negative end
    if n=0 then return("0") end

    fibs: array[int] := fibonacci(n)
    result: array[char] := array[char]$[]

    while ~array[int]$empty(fibs) do
        fib: int := array[int]$remh(fibs)
        if fib <= n then
            n := n - fib
            array[char]$addh(result,'1')
        else
            array[char]$addh(result,'0')
        end
    end
    return(string$ac2s(result))
end zeckendorf

% Print the Zeckendorf representations of 0 to 20
start_up = proc ()
    po: stream := stream$primary_output()
    for i: int in int$from_to(0,20) do
        stream$putright(po, int$unparse(i), 2)
        stream$puts(po, ": ")
        stream$putl(po, zeckendorf(i))
    end
end start_up


(defun zeckendorf (n)
   "returns zeckendorf integer of n (see OEIS A003714)"
   (let ((fib '(2 1)))
	;; extend Fibonacci sequence long enough
	(loop while (<= (car fib) n) do
	      (push (+ (car fib) (cadr fib)) fib))
	(loop with r = 0 for f in fib do
	      (setf r (* 2 r))
	      (when (>= n f) (setf n (- n f))
			     (incf r))
	      finally (return r))))

;;; task requirement
(loop for i from 0 to 20 do
      (format t "~2D: ~2R~%" i (zeckendorf i)))


load("descriptive");
mean([2, 7, 11, 17]);


fn mean data =
(
    total = 0
    for i in data do
    (
        total += i
    )
    if data.count == 0 then 0 else total as float/data.count
)

print (mean #(3, 1, 4, 1, 5, 9))


:- module arithmetic_mean.
:- interface.

:- import_module io.

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

:- implementation.

:- import_module float, list, require.

main(!IO) :-
    io.print_line(mean([1.0, 2.0, 3.0, 4.0, 5.0]), !IO).

:- func mean(list(float)) = float.

mean([]) = func_error("mean: emtpy list").
mean(Ns @ [_ | _]) = foldl((+), Ns, 0.0) / float(length(Ns)).

:- end_module arithmetic_mean.


(((0 (+) reduce) (size /)) cleave) :mean
(2 3 5) mean print


def zeckendorf(n)
  return 0 if n.zero?
  fib = [1, 2]
  while fib[-1] < n; fib << fib[-2] + fib[-1] end
  digit = ""
  fib.reverse_each do |f|
    if f <= n
      digit, n = digit + "1", n - f
    else
      digit += "0"
    end
  end
  digit.to_i
end

(0..20).each { |i| puts "%3d: %8d" % [i, zeckendorf(i)] }


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

void main() {
    size_t
    .max
    .iota
    .filter!q{ !(a & (a >> 1)) }
    .take(21)
    .binaryReverseArgs!writefln("%(%b\n%)");
}


: toggle ( c-addr -- )  \ toggle the byte at c-addr
    dup [email protected] 1 xor swap c! ;

100  1+ ( 1-based indexing ) constant ndoors
create doors  ndoors allot

: init ( -- )  doors ndoors erase ;  \ close all doors

: pass ( n -- )  \ toggle every nth door
    ndoors over do
        doors i + toggle
    dup ( n ) +loop drop ;

: run ( -- )  ndoors 1 do  i pass  loop ;
: display ( -- )  \ display open doors
    ndoors 1 do  doors i + [email protected] if  i .  then loop cr ;

init run display


arr = [ 1, 3, 7, 8, 9, 1 ]

avg = function(arr)
    avgNum = 0
    for num in arr
        avgNum = avgNum + num
    end for
    return avgNum / arr.len
end function

print avg(arr)


PROCEDURE  Avg;

VAR     avg             : REAL;

BEGIN
   avg := sx / n;
   InOut.WriteString ("Average = ");
   InOut.WriteReal (avg, 8, 2);
   InOut.WriteLn
END Avg;


;; special fib's starting with 1 2 3 5 ...
(define (fibonacci n)
    (+ (fibonacci (1- n)) (fibonacci (- n 2))))
(remember 'fibonacci #(1 2))

(define-constant Φ (// (1+ (sqrt 5)) 2))
(define-constant logΦ (log Φ))
;; find i : fib(i) >= n
(define (iFib n)
   (floor (// (log (+ (* n Φ) 0.5)) logΦ)))

;; left trim zeroes
(string-delimiter "")
(define (zeck->string digits)
        (if (!= 0 (first digits))
            (string-join digits "")
            (zeck->string (rest digits))))

(define (Zeck n)
        (cond
        (( < n 0) "no negative zeck")
        ((inexact? n) "no floating zeck")
        ((zero? n) "0")
        (else (zeck->string
                (for/list ((s (reverse (take fibonacci (iFib n)))))
                (if ( > s n) 0
                    (begin (-= n s) 1 )))))))


import system'routines;
import system'collections;
import system'text;
import extensions;
extension op
{
    fibonacci()
    {
        if (self < 2)
        {
            ^ self
        }
        else
        {
            ^ (self - 1).fibonacci() + (self - 2).fibonacci()
        };
    }

    zeckendorf()
    {
        var fibonacciNumbers := new List<int>();

        int num := self;
        int fibPosition := 2;
        int currentFibonaciNum := fibPosition.fibonacci();

        while (currentFibonaciNum <= num)
        {
            fibonacciNumbers.append:currentFibonaciNum;

            fibPosition := fibPosition + 1;
            currentFibonaciNum := fibPosition.fibonacci()
        };

        auto output := new TextBuilder();
        int temp := num;

        fibonacciNumbers.sequenceReverse().forEach:(item)
        {
            if (item <= temp)
            {
                output.write("1");
                temp := temp - item
            }
            else
            {
                output.write("0")
            }
        };

        ^ output.Value
    }
}

public program()
{
    for(int i := 1, i <= 20, i += 1)
    {
        console.printFormatted("{0} : {1}",i,i.zeckendorf()).writeLine()
    };

    console.readChar()
}


program doors
    implicit none
    integer, allocatable :: door(:)
    character(6), parameter :: s(0:1) = [character(6) :: "closed", "open"]
    integer :: i, n

    print "(A)", "Number of doors?"
    read *, n
    allocate (door(n))
    door = 1
    do i = 1, n
        door(i:n:i) = 1 - door(i:n:i)
        print "(A,G0,2A)", "door ", i, " is ", s(door(i))
    end do
end program


MEAN(X)
 ;X is assumed to be a list of numbers separated by "^"
 QUIT:'$DATA(X) "No data"
 QUIT:X="" "Empty Set"
 NEW S,I
 SET S=0,I=1
 FOR  QUIT:I>$L(X,"^")  SET S=S+$P(X,"^",I),I=I+1
 QUIT (S/$L(X,"^"))


def sum(lst)
        sum = 0
        for n in lst
                sum += n
        end
        return sum
end

def average(x)
        return sum(x) / len(x)
end


using System;
using System.Console;
using Nemerle.Collections;

module Mean
{
    ArithmeticMean(x : list[int]) : double
    {
        |[] => 0.0
        |_  =>(x.FoldLeft(0, _+_) :> double) / x.Length
    }

    Main() : void
    {
        WriteLine("Mean of [1 .. 10]: {0}", ArithmeticMean($[1 .. 10]));
    }
}


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

launchSample()
return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method arithmeticMean(vv = Vector) public static signals DivideException returns Rexx
  sum = 0
  n_ = Rexx
  loop n_ over vv
    sum = sum + n_
    end n_
  mean = sum / vv.size()

  return mean

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method launchSample() public static
  TRUE_  = 1 == 1
  FALSE_ = \TRUE_
  tracing = FALSE_
  vectors = getSampleData()
  loop v_ = 0 to vectors.length - 1
    say 'Average of:' vectors[v_].toString()
    do
      say '          =' arithmeticMean(vectors[v_])
    catch dex = DivideException
      say 'Caught "Divide By Zero"; bypassing...'
      if tracing then dex.printStackTrace()
    catch xex = RuntimeException
      say 'Caught unspecified run-time exception; bypassing...'
      if tracing then xex.printStackTrace()
    end
    say
    end v_
  return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method getSampleData() private static returns Vector[]
  seed = 1066
  rng = Random(seed)
  vectors =[ -
    Vector(Arrays.asList([Rexx 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])), -
    Vector(), -
    Vector(Arrays.asList([Rexx rng.nextInt(seed), rng.nextInt(seed), rng.nextInt(seed), rng.nextInt(seed), rng.nextInt(seed), rng.nextInt(seed)])), -
    Vector(Arrays.asList([Rexx rng.nextDouble(), rng.nextDouble(), rng.nextDouble(), rng.nextDouble(), rng.nextDouble(), rng.nextDouble(), rng.nextDouble()])), -
    Vector(Arrays.asList([Rexx '1.0', '2.0', 3.0])), -
    Vector(Arrays.asList([Rexx '1.0', 'not a number', 3.0])) -
    ]
  return vectors


defmodule Zeckendorf do
  def number do
    Stream.unfold(0, fn n -> zn_loop(n) end)
  end

  defp zn_loop(n) do
    bin = Integer.to_string(n, 2)
    if String.match?(bin, ~r/11/), do: zn_loop(n+1), else: {bin, n+1}
  end
end

Zeckendorf.number |> Enum.take(21) |> Enum.with_index
|> Enum.each(fn {zn, i} -> IO.puts "#{i}: #{zn}" end)


let fib = Seq.unfold (fun (x, y) -> Some(x, (y, x + y))) (1,2)

let zeckendorf n =
    if n = 0 then ["0"]
    else
        let folder k state =
            let (n, z) = (fst state), (snd state)
            if n >= k then (n - k, "1" :: z)
            else (n, "0" :: z)
        let fb = fib |> Seq.takeWhile (fun i -> i<=n) |> Seq.toList
        snd (List.foldBack folder fb (n, []))
        |> List.rev

for i in 0 .. 20 do printfn "%2d: %8s" i (String.concat "" (zeckendorf i))


USING: formatting kernel locals make math sequences ;

:: fib<= ( n -- seq )
    1 2 [ [ dup n <= ] [ 2dup + [ , ] 2dip ] while drop , ]
    { } make ;

:: zeck ( n -- str )
    0 :> s! n fib<= <reversed>
    [ dup s + n <= [ s + s! 49 ] [ drop 48 ] if ] "" map-as ;

21 <iota> [ dup zeck "%2d: %6s\n" printf ] each


program OneHundredIsOpen;

const
  DoorCount = 100;

var
  IsOpen: array[1..DoorCount] of boolean;
  Door, Jump: integer;

begin
  // Close all doors
  for Door := 1 to DoorCount do
    IsOpen[Door] := False;
  // Iterations
  for Jump := 1 to DoorCount do
  begin
    Door := Jump;
    repeat
      IsOpen[Door] := not IsOpen[Door];
      Door := Door + Jump;
    until Door > DoorCount;
  end;
  // Show final status
  for Door := 1 to DoorCount do
  begin
    Write(Door, ' ');
    if IsOpen[Door] then
      WriteLn('open')
    else
      WriteLn('closed');
  end;
  // Wait for <enter>
  Readln;
end.


(define (Mean Lst)
   (if (empty? Lst)
      0
      (/ (apply + Lst) (length Lst))))

 (Mean (sequence 1 1000))-> 500
 (Mean '()) -> 0


import strutils

proc mean(xs: openArray[float]): float =
  for x in xs:
    result += x
  result = result / float(xs.len)

var v = @[1.0, 2.0, 2.718, 3.0, 3.142]
for i in 0..5:
  echo "mean of first ", v.len, " = ", formatFloat(mean(v), precision = 0)
  if v.len > 0: v.setLen(v.high)


: fib<= ( n -- n )
    >r 0 1 BEGIN dup [email protected] <= WHILE  tuck +  REPEAT  drop rdrop ;

: z. ( n -- )
   dup fib<= dup . -
   BEGIN ?dup WHILE
      dup fib<= dup [char] + emit space . -
   REPEAT ;

: tab  9 emit ;

: zeckendorf ( -- )
    21 0 DO
        cr i 2 .r tab i z.
    LOOP ;


' version 17-10-2016
' compile with: fbc -s console

#Define max 92 ' max for Fibonacci number

Dim Shared As ULongInt fib(max)

fib(0) = 1
fib(1) = 1

For x As Integer = 2 To max
  fib(x) = fib(x-1) + fib(x-2)
Next

Function num2zeck(n As Integer) As String

If n < 0 Then
  Print "Error: no negative numbers allowed"
  Beep : Sleep 5000,1 : End
End If

If n < 2 Then Return Str(n)

  Dim As String zeckendorf

  For x As Integer = max To 1 Step -1
    If fib(x) <= n Then
      zeckendorf = zeckendorf + "1"
      n = n - fib(x)
    Else
      zeckendorf = zeckendorf + "0"
    End If
  Next

  return LTrim(zeckendorf, "0") ' get rid of leading zeroes
End Function

' ------=< MAIN >=------

Dim As Integer x, e
Dim As String zeckendorf
Print "number       zeckendorf"

For x = 0 To 200000

  zeckendorf = num2zeck(x)
  If x <= 20 Then Print x, zeckendorf

  ' check for two consecutive Fibonacci numbers
  If InStr(zeckendorf, "11") <> 0 Then
    Print " Error: two consecutive Fibonacci numbers "; x, zeckendorf
    e = e +1
  End If
Next

Print
If e = 0 Then
  Print " No Zeckendorf numbers with two consecutive Fibonacci numbers found"
Else
  Print e; " error(s) found"
End If

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


' version 27-10-2016
' compile with: fbc -s console

#Define max_doors 100

Dim As ULong c, n, n1, door(1 To max_doors)

' toggle, at start all doors are closed (0)
' 0 = door closed, 1 = door open
For n = 1 To max_doors
    For n1 = n To max_doors Step n
        door(n1) = 1 - door(n1)
    Next
Next

' count the doors that are open (1)
Print "doors that are open nr: ";
For n = 1 To max_doors
    If door(n) = 1 Then
        Print n; " ";
        c = c + 1
    End If
Next

Print : Print
Print "There are " + Str(c) + " doors open"

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


[ [ , len 1 - at ! ] len 3 - times swap , ] 'map ; ( a Lisp like map, to sum the stack )
[ len 'n ; [ + ] 0 n swap-at map n / ] 'avg ;

1 2 3 4 5 avg .
=> 3
3.4 2.3 .01 2.0 2.1 avg .
=> 1.9619999999999997


MODULE AvgMean;
IMPORT Out;
CONST MAXSIZE = 10;
PROCEDURE Avg(a: ARRAY OF REAL; items: INTEGER): REAL;
VAR
	i: INTEGER;
	total: REAL;
BEGIN
	total := 0.0;
	FOR i := 0 TO LEN(a) -  1 DO
		total := total + a[i]
	END;
	RETURN total/LEN(a)
END Avg;
VAR
	ary: ARRAY MAXSIZE OF REAL;
BEGIN
	ary[0] := 10.0;
	ary[1] := 11.01;
	ary[2] := 12.02;
	ary[3] := 13.03;
	ary[4] := 14.04;
	ary[5] := 15.05;
	ary[6] := 16.06;
	ary[7] := 17.07;
	ary[8] := 18.08;
	ary[9] := 19.09;
	Out.Fixed(Avg(ary),4,2);Out.Ln
END AvgMean.


package main

import "fmt"

func main() {
    for i := 0; i <= 20; i++ {
        fmt.Printf("%2d %7b\n", i, zeckendorf(i))
    }
}

func zeckendorf(n int) int {
    // initial arguments of fib0 = 1 and fib1 = 1 will produce
    // the Fibonacci sequence {1, 2, 3,..} on the stack as successive
    // values of fib1.
    _, set := zr(1, 1, n, 0)
    return set
}

func zr(fib0, fib1, n int, bit uint) (remaining, set int) {
    if fib1 > n {
        return n, 0
    }
    // recurse.
    // construct sequence on the way in, construct ZR on the way out.
    remaining, set = zr(fib1, fib0+fib1, n, bit+1)
    if fib1 <= remaining {
        set |= 1 << bit
        remaining -= fib1
    }
    return
}


import Data.Bits
import Numeric

zeckendorf = map b $ filter ones [0..] where
	ones :: Int -> Bool
	ones x = 0 == x .&. (x `shiftR` 1)
	b x = showIntAtBase 2 ("01"!!) x ""

main = mapM_ putStrLn $ take 21 zeckendorf


fib=: 3 : 0 " 0
 mp=. +/ .*
 {.{: mp/ mp~^:(I.|.#:y) 2 2$0 1 1 1x
)

phi=: -:1+%:5

fi =: 3 : 'n - y<fib n=. 0>.(1=y)-~>.(phi^.%:5)+phi^.y'

fsum=: 3 : 0
 z=. 0$r=. y
 while. 3<r do.
  m=. fib fi r
  z=. z,m
  r=. r-m
 end.
 z,r$~(*r)+.0=y
)

Filter=: (#~`)(`:6)

' '&~:[email protected]:":@:#:@:#[email protected]:((|. fib 2+i.8) e. fsum)&.>i.3 7
┌──────┬──────┬──────┬──────┬──────┬──────┬──────┐
│0     │1     │10    │100   │101   │1000  │1001  │
├──────┼──────┼──────┼──────┼──────┼──────┼──────┤
│1010  │10000 │10001 │10010 │10100 │10101 │100000│
├──────┼──────┼──────┼──────┼──────┼──────┼──────┤
│100001│100010│100100│100101│101000│101001│101010│
└──────┴──────┴──────┴──────┴──────┴──────┴──────┘


# Set doors to empty list
set doors

# Initialize doors arrays
for i in (seq 100)
    set doors[$i] 0
end

for i in (seq 100)
    set j $i
    while test $j -le 100
        # Logical not on doors
        set doors[$j] (math !$doors[$j])
        set j (math $j + $i)
    end
end

# Print every door
for i in (seq (count $doors))
    echo -n "$i "
    if test $doors[$i] -eq 0
        echo closed
    else
        echo open
    end
end


function : native : PrintAverage(values : FloatVector) ~ Nil {
  values->Average()->PrintLine();
}


let mean_floats = function
  | [] -> 0.
  | xs -> List.fold_left (+.) 0. xs /. float_of_int (List.length xs)

let mean_ints xs = mean_floats (List.map float_of_int xs)


function m = omean(l)
  if ( numel(l) == 0 )
    m = 0;
  else
    m = mean(l);
  endif
endfunction

disp(omean([]));
disp(omean([1,2,3]));


import java.util.*;

class Zeckendorf
{
  public static String getZeckendorf(int n)
  {
    if (n == 0)
      return "0";
    List<Integer> fibNumbers = new ArrayList<Integer>();
    fibNumbers.add(1);
    int nextFib = 2;
    while (nextFib <= n)
    {
      fibNumbers.add(nextFib);
      nextFib += fibNumbers.get(fibNumbers.size() - 2);
    }
    StringBuilder sb = new StringBuilder();
    for (int i = fibNumbers.size() - 1; i >= 0; i--)
    {
      int fibNumber = fibNumbers.get(i);
      sb.append((fibNumber <= n) ? "1" : "0");
      if (fibNumber <= n)
        n -= fibNumber;
    }
    return sb.toString();
  }

  public static void main(String[] args)
  {
    for (int i = 0; i <= 20; i++)
      System.out.println("Z(" + i + ")=" + getZeckendorf(i));
  }
}


(() => {
    'use strict';

    const main = () =>
        unlines(
            map(n => concat(zeckendorf(n)),
                enumFromTo(0, 20)
            )
        );

    // zeckendorf :: Int -> String
    const zeckendorf = n => {
        const go = (n, x) =>
            n < x ? (
                Tuple(n, '0')
            ) : Tuple(n - x, '1')
        return 0 < n ? (
            snd(mapAccumL(
                go, n,
                reverse(fibUntil(n))
            ))
        ) : ['0'];
    };

    // fibUntil :: Int -> [Int]
    const fibUntil = n =>
        cons(1, takeWhile(x => n >= x,
            map(snd, iterateUntil(
                tpl => n <= fst(tpl),
                tpl => {
                    const x = snd(tpl);
                    return Tuple(x, x + fst(tpl));
                },
                Tuple(1, 2)
            ))));

    // GENERIC FUNCTIONS ----------------------------

    // Tuple (,) :: a -> b -> (a, b)
    const Tuple = (a, b) => ({
        type: 'Tuple',
        '0': a,
        '1': b,
        length: 2
    });

    // concat :: [[a]] -> [a]
    // concat :: [String] -> String
    const concat = xs =>
        0 < xs.length ? (() => {
            const unit = 'string' !== typeof xs[0] ? (
                []
            ) : '';
            return unit.concat.apply(unit, xs);
        })() : [];

    // cons :: a -> [a] -> [a]
    const cons = (x, xs) =>
        Array.isArray(xs) ? (
            [x].concat(xs)
        ) : (x + xs);

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

    // fst :: (a, b) -> a
    const fst = tpl => tpl[0];

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

    // map :: (a -> b) -> [a] -> [b]
    const map = (f, xs) => xs.map(f);

    // 'The mapAccumL function behaves like a combination of map and foldl;
    // it applies a function to each element of a list, passing an accumulating
    // parameter from left to right, and returning a final value of this
    // accumulator together with the new list.' (See Hoogle)

    // mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
    const mapAccumL = (f, acc, xs) =>
        xs.reduce((a, x, i) => {
            const pair = f(a[0], x, i);
            return Tuple(pair[0], a[1].concat(pair[1]));
        }, Tuple(acc, []));

    // reverse :: [a] -> [a]
    const reverse = xs =>
        'string' !== typeof xs ? (
            xs.slice(0).reverse()
        ) : xs.split('').reverse().join('');

    // snd :: (a, b) -> b
    const snd = tpl => tpl[1];

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

    // takeWhile :: (a -> Bool) -> [a] -> [a]
    // takeWhile :: (Char -> Bool) -> String -> String
    const takeWhile = (p, xs) => {
        const lng = xs.length;
        return 0 < lng ? xs.slice(
            0,
            until(
                i => i === lng || !p(xs[i]),
                i => 1 + i,
                0
            )
        ) : [];
    };

    // unlines :: [String] -> String
    const unlines = xs => xs.join('\n');

    // until :: (a -> Bool) -> (a -> a) -> a -> a
    const until = (p, f, x) => {
        let v = x;
        while (!p(v)) v = f(v);
        return v;
    };

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


doors = new array[[101], false]
for pass=1 to 100
   for door=pass to 100 step pass
      [email protected] = ! [email protected]

print["Open doors:  "]
for door=1 to 100
   if [email protected]
      print["$door "]


: avg ( x -- avg )
   x sum
   x size dup ifZero: [ 2drop null ] else: [ >float / ]
;


call testAverage .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
call testAverage .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11)
call testAverage .array~of(10, 20, 30, 40, 50, -100, 4.7, -11e2)
call testAverage .array~new

::routine testAverage
  use arg numbers
  say "numbers =" numbers~toString("l", ", ")
  say "average =" average(numbers)
  say

::routine average
  use arg numbers
  -- return zero for an empty list
  if numbers~isempty then return 0

  sum = 0
  do number over numbers
      sum += number
  end
  return sum/numbers~items


declare
  fun {Mean Xs}
     {FoldL Xs Number.'+' 0.0} / {Int.toFloat {Length Xs}}
  end
in
  {Show {Mean [3. 1. 4. 1. 5. 9.]}}


def zeckendorf:
  def fibs($n):
    # input: [f(i-2), f(i-1)]
    [1,1] | [recurse(select(.[1] < $n) | [.[1], add]) | .[1]] ;

  # Emit an array of 0s and 1s corresponding to the Zeckendorf encoding
  # $f should be the relevant Fibonacci numbers in increasing order.
  def loop($f):
    [ recurse(. as [$n, $ix]
              | select( $ix > -1 )
              | $f[$ix] as $next
              | if $n >= $next
	        then [$n - $next, $ix-1, 1]
                else [$n, $ix-1, 0]
                end )
      | .[2] // empty ]
    # remove any superfluous leading 0:
    # remove leading 0 if any unless length==1
    | if length>1 and .[0] == 0 then .[1:] else . end ;

  # state: [$n, index_in_fibs, digit ]
  fibs(.) as $f
  | [., ($f|length)-1]
  | loop($f)
  | join("") ;


function zeck(n)
    n <= 0 && return 0
    fib = [2,1]; while fib[1] < n unshift!(fib,sum(fib[1:2])) end
    dig = Int[]; for f in fib f <= n ? (push!(dig,1); n = n-f;) : push!(dig,0) end
    return dig[1] == 0 ? dig[2:end] : dig
end


include ..\Utilitys.tlhy

:listos
    %i$ "" !i$
    len [ get tostr $i$ chain !i$ ] for drop
    $i$
;

:Zeckendorf %n !n
    %i 0 !i %c 0 !c

    [
        $i 8 itob listos
        "11" find not (
            [ ( $c ":" 9 tochar ) lprint tonum ? $c 1 + !c ]
            [drop]
        ) if
        $i 1 + !i
    ]
    [$c $n >] until
;

20 Zeckendorf

nl "End " input


// version 1.0.6

const val LIMIT = 46  // to stay within range of signed 32 bit integer
val fibs = fibonacci(LIMIT)

fun fibonacci(n: Int): IntArray {
    if (n !in 2..LIMIT) throw IllegalArgumentException("n must be between 2 and $LIMIT")
    val fibs = IntArray(n)
    fibs[0] = 1
    fibs[1] = 1
    for (i in 2 until n) fibs[i] = fibs[i - 1] + fibs[i - 2]
    return fibs
}

fun zeckendorf(n: Int): String {
    if (n < 0) throw IllegalArgumentException("n must be non-negative")
    if (n < 2) return n.toString()
    var lastFibIndex = 1
    for (i in 2..LIMIT)
        if (fibs[i] > n) {
            lastFibIndex = i - 1
            break
        }
    var nn = n - fibs[lastFibIndex--]
    val zr = StringBuilder("1")
    for (i in lastFibIndex downTo 1)
        if (fibs[i] <= nn) {
            zr.append('1')
            nn -= fibs[i]
        } else {
            zr.append('0')
        }
    return zr.toString()
}

fun main(args: Array<String>) {
    println(" n   z")
    for (i in 0..20) println("${"%2d".format(i)} : ${zeckendorf(i)}")
}


for i <- 1..100
  r = foldl1( \a, b -> a xor b, [(a|i) | a <- 1..100] )
  println( i + ' ' + (if r then 'open' else 'closed') )


Program Mean;

  function DoMean(vector: array of double): double;
  var
    sum: double;
    i, len: integer;
  begin
    sum := 0;
    len := length(vector);
    if len > 0 then
      begin
      for i := low(vector) to high(vector) do
	sum := sum + vector[i];
      sum := sum / len;
      end;
     DoMean := sum;
  end;

const
  vector: array [3..8] of double = (3.0, 1.0, 4.0, 1.0, 5.0, 9.0);
var
  i: integer;
begin
  writeln('Calculating the arithmetic mean of a series of numbers:');
  write('Numbers: [ ');
  for i := low(vector) to high(vector) do
    write (vector[i]:3:1, ' ');
  writeln (']');
  writeln('Mean: ', DoMean(vector):10:8);
end.


samples = 20
call zecklist samples

print "Decimal","Zeckendorf"
for n = 0 to samples
  print n, zecklist$(n)
next n

Sub zecklist inDEC
  dim zecklist$(inDEC)
  do
    bin$ = dec2bin$(count)
    if instr(bin$,"11") = 0 then
      zecklist$(found) = bin$
      found = found + 1
    end if
    count = count+1
  loop until found = inDEC + 1
End sub

function dec2bin$(inDEC)
  do
    bin$ = str$(inDEC mod 2) + bin$
    inDEC = int(inDEC/2)
  loop until inDEC = 0
  dec2bin$ = bin$
end function


-- Return the distinct Fibonacci numbers not greater than 'n'
on fibsUpTo (n)
    fibList = []
    last = 1
    current = 1
    repeat while current <= n
        fibList.add(current)
        nxt = last + current
        last = current
        current = nxt
    end repeat
    return fibList
end

-- Return the Zeckendorf representation of 'n'
on zeckendorf (n)
    fib = fibsUpTo(n)
    zeck = ""
    repeat with pos = fib.count down to 1
        if n >= fib[pos] then
            zeck = zeck & "1"
            n = n - fib[pos]
        else
            zeck = zeck & "0"
        end if
    end repeat
    if zeck = "" then return "0"
    return zeck
end


// Little Man Computer, for Rosetta Code.
// Writes Zeckendorf representations of numbers 0..20.
// Works with Peter Higginson's LMC simulator, except that
//   user must intervene manually to capture all the output.
         LDA c0       // initialize to N = 0
loop     STA N
         OUT          // write N
         LDA equals   // then equals sign
         OTC
         BRA wr_zeck  // then Zeckendorf rep
return   LDA space    // then space
         OTC
         LDA N        // done maximum N?
         SUB N_max
         BRZ halt     // yes, halt
         LDA N        // no, inc N and loop back
         ADD c1
         BRA loop
halt     HLT
c0       DAT 0
N_max    DAT 20
equals   DAT 61
space    DAT 32

// Routine to write Zeckendorf representation of number stored in N.
// Since LMC doesn't support subroutines, returns with "BRA return".
wr_zeck  LDA N
         SUB c1
         BRP phase_1
// N = 0, special case
         LDA ascii_0
         OTC
         BRA done
// N > 0. Phase 1: find largest Fibonacci number <= N
phase_1  STA res      // res := N - 1
         LDA c1       // initialize Fibonacci terms
         STA a
         STA b
loop_1   LDA res      // here res = N - a (easy proof)
         SUB b        // is next Fibonacci a + b > N?
         BRP next_fib // no, continue Fibonacci
         BRA phase_2  // yes, on to phase 2
next_fib STA res      // res := res - b
         LDA a        // (a, b) := (a + b, a)
         ADD b
         STA a
         SUB b
         STA b
         BRA loop_1   // loop to test new (a, b)
// Phase 2: get Zeckendorf digits by winding Fibonacci back
phase_2  LDA ascii_1  // first digit must be 1
         OTC
loop_2   LDA a        // done when wound back to a = 1
         SUB c1
         BRZ done
         LDA res      // decide next Zeckendorf digit
         SUB b        // 0 if res < b, 1 if res >= b
         BRP dig_is_1
         LDA ascii_0
         BRA wr_dig
dig_is_1 STA res      // res := res - b
         LDA ascii_1
wr_dig   OTC          // write Zeckendorf digit 0 or 1
         LDA a        // (a, b) := (b, a - b)
         SUB b
         STA b
         LDA a
         SUB b
         STA a
         BRA loop_2   // loop to test new (a, b)
done     BRA return
N        DAT
res      DAT
a        DAT
b        DAT
c1       DAT 1
ascii_0  DAT 48
ascii_1  DAT 49
// end


; return the (N+1)th Fibonacci number (1,2,3,5,8,13,...)
to fib m
  local "n
  make "n sum :m 1
  if [lessequal? :n 0] [output difference fib sum :n 2 fib sum :n 1]
  global "_fib
  if [not name? "_fib] [
    make "_fib [1 1]
  ]
  local "length
  make "length count :_fib
  while [greater? :n :length] [
    make "_fib (lput (sum (last :_fib) (last (butlast :_fib))) :_fib)
    make "length sum :length 1
  ]
  output item :n :_fib
end

; return the binary Zeckendorf representation of a nonnegative number
to zeckendorf n
  if [less? :n 0] [(throw "error [Number must be nonnegative.])]
  (local "i "f "result)
  make "i :n
  make "f fib :i
  while [less? :f :n] [make "i sum :i 1 make "f fib :i]

  make "result "||
  while [greater? :i 0] [
    ifelse [greaterequal? :n :f] [
      make "result lput 1 :result
      make "n difference :n :f
    ] [
      if [not empty? :result] [
        make "result lput 0 :result
      ]
    ]
    make "i difference :i 1
    make "f fib :i
  ]
  if [equal? :result "||] [
    make "result 0
  ]
  output :result
end

type zeckendorf 0
repeat 20 [
  type word "| | zeckendorf repcount
]
print []
bye


let main(n: i32): [n]bool =
  loop is_open = replicate n false for i < n do
    let js = map (*i+1) (iota n)
    let flips = map (\j ->
                       if j < n
                       then unsafe !is_open[j]
                       else true -- Doesn't matter.
                    ) js
    in scatter is_open js flips


sub avg {
  @_ or return 0;
  my $sum = 0;
  $sum += $_ foreach @_;
  return $sum/@_;
}

print avg(qw(3 1 4 1 5 9)), "\n";


with javascript_semantics
function mean(sequence s)
    if length(s)=0 then return 0 end if
    return sum(s)/length(s)
end function

? mean({1, 2, 5, -5, -9.5, 3.14159})


1 2 5 -5 -9.5 3.14159 stklen tolist
len swap sum swap / print


-- Return the distinct Fibonacci numbers not greater than 'n'
function fibsUpTo (n)
    local fibList, last, current, nxt = {}, 1, 1
    while current <= n do
        table.insert(fibList, current)
        nxt = last + current
        last = current
        current = nxt
    end
    return fibList
end

-- Return the Zeckendorf representation of 'n'
function zeckendorf (n)
    local fib, zeck = fibsUpTo(n), ""
    for pos = #fib, 1, -1 do
        if n >= fib[pos] then
            zeck = zeck .. "1"
            n = n - fib[pos]
        else
            zeck = zeck .. "0"
        end
    end
    if zeck == "" then return "0" end
    return zeck
end

-- Main procedure
print(" n\t| Zeckendorf(n)")
print(string.rep("-", 23))
for n = 0, 20 do
    print(" " .. n, "| " .. zeckendorf(n))
end


zeckendorf[0] = 0;
zeckendorf[n_Integer] :=
  10^(# - 1) + zeckendorf[n - Fibonacci[# + 1]] &@
   LengthWhile[
    Fibonacci /@
     Range[2, [email protected][GoldenRatio, n [email protected]]], # <= n &];
zeckendorf /@ Range[0, 20]


import strformat, strutils

proc z(n: Natural): string =
  if n == 0: return "0"
  var fib = @[2,1]
  var n = n
  while fib[0] < n: fib.insert(fib[0] + fib[1])
  for f in fib:
    if f <= n:
      result.add '1'
      dec n, f
    else:
      result.add '0'
  if result[0] == '0':
    result = result[1..result.high]

for i in 0 .. 20:
  echo &"{i:>3} {z(i):>8}"


include "NSLog.incl"

NSInteger door, square = 1, increment = 3

for door = 1 to 100
  if ( door == square )
    NSLog( @"Door %ld is open.", door )
    square += increment : increment += 2
  else
    NSLog( @"Door %ld is closed.", door )
  end if
next

HandleEvents


$nums = array(3, 1, 4, 1, 5, 9);
if ($nums)
    echo array_sum($nums) / count($nums), "\n";
else
    echo "0\n";


(de mean (Lst)
   (if (atom Lst)
      0
      (/ (apply + Lst) (length Lst)) ) )


program ZeckendorfRep_RC;

{$mode objfpc}{$H+}

uses SysUtils;

// Return Zeckendorf representation of the passed-in cardinal.
function ZeckRep( C : cardinal) : string;
var
  a, b, rem : cardinal;
  j, nrDigits: integer;
begin
  // Case C = 0 has to be treated specially
  if (C = 0) then begin
    result := '0';
    exit;
  end;
  // Find largest Fibonacci number not exceeding C
  a := 1;
  b := 1;
  nrDigits := 1;
  rem := C - 1;
  while (rem >= b) do begin
    dec( rem, b);
    inc( a, b);
    b := a - b;
    inc( nrDigits);
  end;
  // Fill in digits by reversing Fibonacci back to start
  SetLength( result, nrDigits);
  j := 1;
  result[j] := '1';
  for j := 2 to nrDigits do begin
    if (rem >= b) then begin
      dec( rem, b);
      result[j] := '1';
    end
    else result[j] := '0';
    b := a - b;
    dec( a, b);
  end;
//  Assert((a = 1) and (b = 1)); // optional check
end;

// Main routine
var
  C : cardinal;
begin
  for C := 1 to 20 do
    WriteLn( SysUtils.Format( '%2d: %s', [C, ZeckRep(C)]));
end.


READ x,y,z
PRINT "Open doors: ";x;" ";
CYCLE
    z=x+y
    PRINT z;" ";
    x=z
    y=y+2
REPEAT UNTIL z>=100
DATA 1,3,0
END


To run:
Start up.
Demonstrate finding the arithmetic mean.
Wait for the escape key.
Shut down.

An entry is a thing with a fraction.
A list is some entries.
A sum is a fraction.
A mean is a fraction.

To demonstrate finding the arithmetic mean:
Create an example list.
Write "A list: " then the example list on the console.
Find a mean of the example list.
Write "The list's mean: " then the mean on the console.
Destroy the example list.

To add a fraction to a list:
Allocate memory for an entry.
Put the fraction into the entry's fraction.
Append the entry to the list.

To create an example list:
Add 1/1 to the example list.
Add 2/1 to the example list.
Add 5-1/3 to the example list.
Add 7-1/2 to the example list.

To find a sum of a list:
Put 0 into the sum.
Get an entry from the list.
Loop.
If the entry is nil, exit.
Add the entry's fraction to the sum.
Put the entry's next into the entry.
Repeat.

To find a mean of a list:
Find a sum of the list.
Put the sum divided by the list's count into the mean.

To convert a list to a string:
Get an entry from the list.
Loop.
If the entry is nil, break.
Append the entry's fraction to the string.
If the entry's next is not nil, append ", " to the string.
Put the entry's next into the entry.
Repeat.


define mean(v);
    lvars n = length(v), i, s = 0;
    if n = 0 then
        return(0);
    else
        for i from 1 to n do
            s + v(i) -> s;
        endfor;
    endif;
    return(s/n);
enddefine;


/findmean{
/x exch def
/sum 0 def
/i 0 def
x length 0 eq
{}
{
x length{
/sum sum x i get add def
/i i 1 add def
}repeat
/sum sum x length div def
}ifelse
sum ==
}def


function mean ($x) {
    if ($x.Count -eq 0) {
        return 0
    } else {
        $sum = 0
        foreach ($i in $x) {
            $sum += $i
        }
        return $sum / $x.Count
    }
}


my @fib;

sub fib {
  my $n = shift;
  return 1 if $n < 2;
  return $fib[$n] //= fib($n-1)+fib($n-2);
}

sub zeckendorf {
  my $n = shift;
  return "0" unless $n;
  my $i = 1;
  $i++ while fib($i) <= $n;
  my $z = '';
  while( --$i ) {
    $z .= "0", next if fib( $i ) > $n;
    $z .= "1";
    $n -= fib( $i );
  }
  return $z;
}

printf "%4d: %8s\n", $_, zeckendorf($_) for 0..20;


function zeckendorf(integer n)
integer r = 0, c
sequence fib = {1,1}
    while fib[$]<n do
        fib &= fib[$] + fib[$-1]
    end while
    for i=length(fib) to 2 by -1 do
        c = n>=fib[i]
        r += r+c
        n -= c*fib[i]
    end for
    return r
end function

for i=0 to 20 do
    printf(1,"%2d: %7b\n",{i,zeckendorf(i)})
end for


Public Sub Main()
Dim bDoor As New Boolean[101]
Dim siCount1, siCount2, siStart As Short

For siCount1 = 1 To 100
  Inc siStart
  For siCount2 = siStart To 100 Step siCount1
    bDoor[siCount2] = Not bDoor[siCount2]
  Next
Next

For siCount1 = 1 To 100
  If bDoor[siCount1] Then Print siCount1;;
Next

End


float mean(float[] arr) {
  float out = 0;
  for (float n : arr) {
    out += n;
  }
  return out / arr.length;
}


mean(List, Mean) :-
    length(List, Length),
    sumlist(List, Sum),
    Mean is Sum / Length.


Procedure.d mean(List number())
  Protected sum=0

  ForEach number()
    sum + number()
  Next
  ProcedureReturn sum / ListSize(number())
  ; Depends on programm if zero check needed, returns nan on division by zero
EndProcedure


def Zeckendorf  /# n -- #/
    0 var i 0 var c 1 1 2 tolist var pattern
    true
    while
        i 8 int>bit reverse
        pattern find
        not if
            c print ":\t" print print nl
            dup c == if
                false
            else
                c 1 + var c
                true
            endif
        endif
        i 1 + var i
    endwhile
    drop
enddef

20 Zeckendorf


go =>
  foreach(Num in 0..20)
    zeckendorf_cp(Num,X,F),
    Nums = [F[I] : I in 1..X.length, X[I] = 1],
    printf("%2d %6s %w\n",Num, rep(X),Nums),
  end,
  nl.

zeckendorf_cp(Num, X,F) =>
  F = get_fibs(Num).reverse(),
  N = F.length,
  X = new_list(N),
  X :: 0..1,

  % From the task description:
  % """
  % For a true Zeckendorf number there is the added restriction that
  % no two consecutive Fibonacci numbers can be used which leads to
  % the former unique solution.
  % """
  foreach(I in 2..N)
    X[I-1] #= 1 #=> X[I] #= 0
  end,

  scalar_product(F,X,Num),

  solve([ff,split],X).

%
% Fibonacci numbers
%
table
fib(0) = 0.
fib(1) = 1.
fib(N) = fib(N-1) + fib(N-2).

%
% Remove leading 0's and stringify it
%
rep(X) = Str =>
  First = 1,
  if X.length > 1, X[First] = 0 then
    while (X[First] == 0)
      First := First + 1
    end
  end,
  Str = [X[I].to_string() : I in First..X.length].join('').

%
% Return a list of fibs <= N
%
get_fibs(N) = Fibs =>
  I = 2,
  Fib = fib(I),
  Fibs1 = [Fib],
  while (Fib < N)
    I := I + 1,
    Fib := fib(I),
    Fibs1 := Fibs1 ++ [Fib]
  end,
  Fibs = Fibs1.


from math import fsum
def average(x):
    return fsum(x)/float(len(x)) if x else 0
print (average([0,0,3,1,4,1,5,9,0,0]))
print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))


  [ $ 'bigrat.qky' loadfile ] now!

  [ [] swap times
    [ 20001 random 10000 -
      n->v 100 n->v v/
      join nested join ] ]   is makevector   (   --> [   )

  [ witheach
      [ unpack
        2 point$ echo$
        i 0 > if
          [ say ", " ] ] ]   is echodecs      ( [ -->     )

  [ dup size n->v rot
    0 n->v rot
    witheach
      [ unpack v+ ]
    2swap v/ ]               is arithmean    ( [ --> n/d )

  [ 5 makevector

    say "Internal representation of a randomly generated vector" cr
    say "of five rational numbers. They are distributed between" cr
    say "-100.00 and +100.00 and are multiples of 0.01."
    cr cr dup echo cr cr
    say "Shown as decimal fractions."
    cr cr dup echodecs cr cr

    arithmean

    say "Arithmetic mean of vector as a decimal fraction to" cr
    say "5 places after the point, as a rounded proper" cr
    say "fraction with the denominator not exceeding 10, and" cr
    say "finally as a vulgar fraction without rounding." cr cr
    2dup 5 point$ echo$
    say ", "
    2dup proper 10 round improper
    proper$ echo$
    say ", "
    vulgar$ echo$ cr cr

    say "The same, but with a vector of 9973 rational numbers," cr
    say "20 decimal places and a denominator not exceeding 100." cr cr

    9973 makevector arithmean

    2dup 20 point$ echo$
    say ", "
    2dup proper 100 round improper
    proper$ echo$
    say ", "
    vulgar$ echo$ cr ]       is demonstrate  (   -->     )


(de fib (N)
   (let Fibs (1 1)
      (while (>= N (+ (car Fibs) (cadr Fibs)))
         (push 'Fibs (+ (car Fibs) (cadr Fibs))) )
      (uniq Fibs) ) )

(de zecken1 (N)
   (make
      (for I (fib N)
         (if (> I N)
            (link 0)
            (link 1)
            (dec 'N I) ) ) ) )

(de zecken2 (N)
   (make
      (when (=0 N) (link 0))
      (for I (fib N)
         (when (<= I N)
            (link I)
            (dec 'N I) ) ) ) )

(for (N 0 (> 21 N) (inc N))
   (tab (2 4 6 2 -10)
      N
      " -> "
      (zecken1 N)
      "  "
      (glue " + " (zecken2 N)) ) )

(bye)