\def\genfibolist#1{% #creates the fibo list which sum>=#1
	\let\fibolist\empty\def\targetsum{#1}\def\fibosum{0}%
	\genfibolistaux1,1\relax
}
\def\genfibolistaux#1,#2\relax{%
	\ifnum\fibosum<\targetsum\relax
		\edef\fibosum{\number\numexpr\fibosum+#2}%
		\edef\fibolist{#2,\fibolist}%
		\edef\tempfibo{\noexpand\genfibolistaux#2,\number\numexpr#1+#2\relax\relax}%
		\expandafter\tempfibo
	\fi
}
\def\zeckendorf#1{\expandafter\zeckendorfaux\fibolist,\relax#1\relax\relax0}
\def\zeckendorfaux#1,#2\relax#3\relax#4\relax#5{%
	\ifx\relax#2\relax
		#4%
	\else
		\ifnum#3<#1
			\edef\temp{#2\relax#3\relax#4\ifnum#5=1 0\fi\relax#5}%
		\else
			\edef\temp{#2\relax\number\numexpr#3-#1\relax\relax#41\relax1}%
		\fi
		\expandafter\expandafter\expandafter\zeckendorfaux\expandafter\temp
	\fi
}
\newcount\ii
\def\listzeckendorf#1{%
	\genfibolist{#1}%
	\ii=0
	\loop
		\ifnum\ii<#1
		\advance\ii1
		\number\ii: \zeckendorf\ii\endgraf
	\repeat
}
\listzeckendorf{20}% any integer accepted
\bye


function Get-ZeckendorfNumber ( $N )
    {
    #  Calculate relevant portation of Fibonacci series
    $Fib = @( 1, 1 )
    While ( $Fib[-1] -lt $N ) { $Fib += $Fib[-1] + $Fib[-2] }

    #  Start with 0
    $ZeckendorfNumber = 0

    #  For each number in the relevant portion of Fibonacci series
    For ( $i = $Fib.Count - 1; $i -gt 0; $i-- )
        {
        #  If Fibonacci number is less than or equal to remainder of N
        If ( $Fib[$i] -le $N )
            {
            #  Double Z number and add 1 (equivalent to adding a '1' to the end of a binary number)
            $ZeckendorfNumber = $ZeckendorfNumber * 2 + 1
            #  Reduce N by Fibonacci number, skip next Fibonacci number
            $N -= $Fib[$i--]
            }
        #  If were aren't finished yet, double Z number
        #  (equivalent to adding a '0' to the end of a binary number)
        If ( $i ) { $ZeckendorfNumber *= 2 }
        }
    return $ZeckendorfNumber
    }


omean <- function(v) {
  m <- mean(v)
  ifelse(is.na(m), 0, m)
}


multi mean([]){ Failure.new('mean on empty list is not defined') }; # Failure-objects are lazy exceptions
multi mean (@a) { ([+] @a) / @a }


Procedure.s zeck(n.i)
  Dim f.i(1) : Define i.i=1, o$
  f(0)=1 : f(1)=1
  While f(i)<n
    i+1 : ReDim f(ArraySize(f())+1) : f(i)=f(i-1)+f(i-2)
  Wend
  For i=i To 1 Step -1
    If n>=f(i) : o$+"1" : n-f(i) : Else : o$+"0" : EndIf
  Next
  If Len(o$)>1 : o$=LTrim(o$,"0") : EndIf
  ProcedureReturn o$
EndProcedure

Define n.i, t$
OpenConsole("Zeckendorf number representation")
PrintN(~"\tNr.\tZeckendorf")
For n=0 To 20
  t$=zeck(n)
  If FindString(t$,"11")
    PrintN("Error: n= "+Str(n)+~"\tZeckendorf= "+t$)
    Break
  Else
    PrintN(~"\t"+RSet(Str(n),3," ")+~"\t"+RSet(t$,7," "))
  EndIf
Next
Input()


def fib():
    memo = [1, 2]
    while True:
        memo.append(sum(memo))
        yield memo.pop(0)

def sequence_down_from_n(n, seq_generator):
    seq = []
    for s in seq_generator():
        seq.append(s)
        if s >= n: break
    return seq[::-1]

def zeckendorf(n):
    if n == 0: return [0]
    seq = sequence_down_from_n(n, fib)
    digits, nleft = [], n
    for s in seq:
        if s <= nleft:
            digits.append(1)
            nleft -= s
        else:
            digits.append(0)
    assert nleft == 0, 'Check all of n is accounted for'
    assert sum(x*y for x,y in zip(digits, seq)) == n, 'Assert digits are correct'
    while digits[0] == 0:
        # Remove any zeroes padding L.H.S.
        digits.pop(0)
    return digits

n = 20
print('Fibonacci digit multipliers: %r' % sequence_down_from_n(n, fib))
for i in range(n + 1):
    print('%3i: %8s' % (i, ''.join(str(d) for d in zeckendorf(i))))


func Doors(door_count:int) -> void :
  var doors : Array
  doors.resize(door_count)

  # Note : Initialization is not necessarily mandatory (by default values are false)
  # Intentionally left here
  for i in door_count :
    doors[i] = false

  # do visits
  for i in door_count :
    for j in range(i,door_count,i+1) :
      doors[j] = not doors[j]

  # print results
  var results : String = ""
  for i in door_count :
    results += str(i+1) + " " if doors[i] else ""
  print("Doors open : %s" % [results] )

# calling the function from the _ready function
func _ready() -> void :
  Doors(100)


rebol [
    Title: "Arithmetic Mean (Average)"
    URL: http://rosettacode.org/wiki/Average/Arithmetic_mean
]

average: func [v /local sum][
	if empty? v [return 0]

	sum: 0
	forall v [sum: sum + v/1]
	sum / length? v
]

; Note precision loss as spread increased.

print [mold x: [] "->" average x]
print [mold x: [3 1 4 1 5 9] "->" average x]
print [mold x: [1000 3 1 4 1 5 9 -1000] "->" average x]
print [mold x: [1e20 3 1 4 1 5 9 -1e20] "->" average x]


Red ["Arithmetic mean"]

print average []
print average [2 3 5]


let arr = [3, 8, 4, 1, 5, 12]

let num = Js.Array.length(arr)
let tot = Js.Array.reduce(\"+", 0, arr)
let mean = float_of_int(tot) /. float_of_int(num)

Js.log(Js.Float.toString(mean))


  [ 2 base put
    echo
    base release ]        is binecho ( n -->   )

  [ 0 swap ' [ 2 1 ]
    [ 2dup 0 peek < iff
        [ behead drop ]
        done
      dup 0 peek
      over 1 peek
      + swap join again ]
    witheach
      [ rot 1 << unrot
        2dup < iff drop
        else
          [ -
            dip
              [ 1 | ] ] ]
    drop ]                is n->z    ( n --> z )

  [ 0 temp put
    1 1 rot
    [ dup while
      dup 1 & if
        [ over
          temp tally ]
      1 >>
      dip [ tuck + ]
      again ]
    2drop drop
    temp take ]           is z->n    ( z --> n )

   21 times
    [ i^ dup echo
      say " -> "
      n->z dup binecho
      say " -> "
      z->n echo cr ]


zeckendorf <- function(number) {

  # Get an upper limit on Fibonacci numbers needed to cover number
  indexOfFibonacciNumber <- function(n) {
    if (n < 1) {
      2
    } else {
      Phi <- (1 + sqrt(5)) / 2
      invertClosedFormula <- log(n * sqrt(5)) / log(Phi)
      ceiling(invertClosedFormula)
    }
  }

  upperLimit <- indexOfFibonacciNumber(number)

  # Return the sequence as digits, sorted descending
  fibonacciSequenceDigits <- function(n) {
    fibGenerator <- function(f, ...) { c(f[2], sum(f)) }
    fibSeq <- Reduce(fibGenerator, 1:n, c(0,1), accumulate=TRUE)

    fibNums <- unlist(lapply(fibSeq, head, n=1))

    # drop last F0 and F1 and reverse sequence
    rev(fibNums[-2:-1])
  }

  digits <- fibonacciSequenceDigits(upperLimit)

  isInNumber <- function(digit) {
    if (number >= digit) {
      number <<- number - digit
      1
    } else {
      0
    }
  }

  zeckSeq <- Map(isInNumber, digits)

  # drop leading 0 and convert to String
  gsub("^0+1", "1", paste(zeckSeq, collapse=""))
}

print(unlist(lapply(0:20, zeckendorf)))


#lang racket (require math)

(define (fibs n)
  (reverse
   (for/list ([i (in-naturals 2)] #:break (> (fibonacci i) n))
     (fibonacci i))))

(define (zechendorf n)
  (match/values
   (for/fold ([n n] [xs '()]) ([f (fibs n)])
     (if (> f n)
         (values n       (cons 0 xs))
         (values (- n f) (cons 1 xs))))
   [(_ xs) (reverse xs)]))

(for/list ([n 21])
  (list n (zechendorf n)))


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

multi zeckendorf(0) { '0' }
multi zeckendorf($n is copy) {
    constant FIBS = (1,2, *+* ... *).cache;
    [~] map {
        $n -= $_ if my $digit = $n >= $_;
        +$digit;
    }, reverse FIBS ...^ * > $n;
}


// 100 doors problem
// Author: Sinuhe masan (2019)
init

	// 100 elements array of boolean type
	doors:bool[100]

	for var i = 1 to 100
		doors[i] = false  // set all doors closed

	for var i = 1 to 100
		j:int = i
		while j <= 100 do
			doors[j] = not doors[j]
			j = j + i

	print("Doors open: ")
	for var i = 1 to 100
		if doors[i]
			stdout.printf ("%d ", i)


/*REXX program finds the averages/arithmetic mean of several lists (vectors) or CL input*/
parse arg @.1; if @.1=''  then do;   #=6                         /*vector from the C.L.?*/
                               @.1 =   10 9 8 7 6 5 4 3 2 1
                               @.2 =   10 9 8 7 6 5 4 3 2 1 0 0 0 0  .11
                               @.3 =  '10 20 30 40 50  -100  4.7  -11e2'
                               @.4 =  '1 2 3 4  five  6 7 8 9  10.1.  ±2'
                               @.5 =  'World War I  &  World War II'
                               @.6 =                             /*  ◄─── a null value. */
                               end
                          else #=1                               /*number of CL vectors.*/
     do j=1  for #
     say '       numbers = '   @.j
     say '       average = '   avg(@.j)
     say copies('═', 79)
     end   /*t*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
avg: procedure;  parse arg x;     #=words(x)                      /*#:  number of items.*/
     if #==0  then return  'N/A: ───[null vector.]'               /*No words? Return N/A*/
     $=0
          do k=1  for #;      _=word(x,k)                         /*obtain a number.    */
          if datatype(_,'N')  then do;  $=$+_;  iterate;   end    /*if numeric, then add*/
          say left('',40) "***error***  non-numeric: " _;  #=#-1  /*error; adjust number*/
          end   /*k*/

     if #==0  then return  'N/A: ───[no numeric values.]'         /*No nums?  Return N/A*/
     return $ / #                                                 /*return the average. */


nums = [1,2,3,4,5,6,7,8,9,10]
sum = 0
see "Average = " + average(nums) + nl

func average numbers
     for i = 1 to len(numbers)
         sum = sum + nums[i]
     next
     return sum/len(numbers)


/* REXX ***************************************************************
* 11.10.2012 Walter Pachl
**********************************************************************/
fib='13 8 5 3 2 1'
Do i=6 To 1 By -1                   /* Prepare Fibonacci Numbers     */
  Parse Var fib f.i fib             /* f.1 ... f.7                   */
  End
Do n=0 To 20                        /* for all numbers in the task   */
  m=n                               /* copy of number                */
  r=''                              /* result for n                  */
  Do i=6 To 1 By -1                 /* loop through numbers          */
    If m>=f.i Then Do               /* f.i must be used              */
      r=r||1                        /* 1 into result                 */
      m=m-f.i                       /* subtract                      */
      End
    Else                            /* f.i is larger than the rest   */
      r=r||0                        /* 0 into result                 */
    End
  r=strip(r,'L','0')                /* strip leading zeros           */
  If r='' Then r='0'                /* take care of 0                */
  Say right(n,2)':  'right(r,6)     /* show result                   */
  End


# Project : Zeckendorf number representation

see "0 0" + nl
for n = 1 to 20
     see "" + n + " " + zeckendorf(n) + nl
next

func zeckendorf(n)
       fib = list(45)
       fib[1] = 1
       fib[2] = 1
       i = 2
       o = ""
       while fib[i] <= n
               i = i + 1
               fib[i] = fib[i-1] + fib[i-2]
       end
       while i != 2
               i = i - 1
               if n >= fib[i]
                   o = o + "1"
                   n = n - fib[i]
               else
                   o = o + "0"
               ok
        end
        return o


def zeckendorf
  return to_enum(__method__) unless block_given?
  x = 0
  loop do
    bin = x.to_s(2)
    yield bin unless bin.include?("11")
    x += 1
  end
end

zeckendorf.take(21).each_with_index{|x,i| puts "%3d: %8s"% [i, x]}


100` *=0=>d                      $$ create vector 1..100, create bit pattern d, marking all equal to 0
:for (1..100[.s]){               $$ loop s from 1 to 100
  d^(100` %s *=0 )=>d;}          $$ d = d xor (bit pattern of vector 1..100 % s)
d                                $$ output d


1 2 3 5 7
AMEAN
   << DEPTH DUP 'N' STO ->LIST ΣLIST N / >>
3.6


def mean(nums)
  nums.sum(0.0) / nums.size
end

nums = [3, 1, 4, 1, 5, 9]
nums.size.downto(0) do |i|
  ary = nums[0,i]
  puts "array size #{ary.size} : #{mean(ary)}"
end


print "Gimme the number in the array:";input numArray
dim value(numArray)
for i = 1 to numArray
    value(i) = i * 1.5
next

for i = 1 to total
    totValue = totValue +value(numArray)
next
if totValue <> 0 then mean = totValue/numArray
print "The mean is: ";mean


def zNum( n:BigInt ) : String = {

  if( n == 0 ) return "0"	// Short-circuit this and return zero if we were given zero

  val v = n.abs

  val fibs : Stream[BigInt] = { def series(i:BigInt,j:BigInt):Stream[BigInt] = i #:: series(j, i+j); series(1,0).tail.tail.tail }

  def z( v:BigInt ) : List[BigInt] = if(v == 0) List() else {val m = fibs(fibs.indexWhere(_>v) - 1); m :: z(v-m)}

  val zv = z(v)

  // Walk the list of fibonacci numbers from the number that matches the most significant down to 1,
  // if the zeckendorf matchs then yield '1' otherwise '0'
  val s = (for( i <- (fibs.indexWhere(_==zv(0)) to 0 by -1) ) yield {

    if( zv.contains(fibs(i))) "1" else "0"

  }).mkString

  if( n < 0 ) "-" + s		// Using a negative-sign instead of twos-complement
  else s
}

// A little test...
(0 to 20) foreach( i => print( zNum(i) + "\n" ) )


(import (rnrs))

(define (getFibList maxNum n1 n2 fibs)
  (if (> n2 maxNum)
      fibs
      (getFibList maxNum n2 (+ n1 n2) (cons n2 fibs))))

(define (getZeckendorf num)
  (if (<= num 0)
      "0"
      (let ((fibs (getFibList num 1 2 (list 1))))
        (getZeckString "" num fibs))))

(define (getZeckString zeck num fibs)
  (let* ((curFib (car fibs))
         (placeZeck (>= num curFib))
         (outString (string-append zeck (if placeZeck "1" "0")))
         (outNum (if placeZeck (- num curFib) num)))
    (if (null? (cdr fibs))
        outString
        (getZeckString outString outNum (cdr fibs)))))

(let loop ((i 0))
  (when (<= i 20)
    (for-each
      (lambda (item)
        (display item))
      (list "Z(" i "):\t" (getZeckendorf i)))
    (newline)
    (loop (+ i 1))))


var doors,a,i;
//Sets up the array for all of the doors.
for (i = 1; i<=100; i += 1)
    {
    doors[i]=0;
    }

//This first for loop goes through and passes the interval down to the next for loop.
for (i = 1; i <= 100; i += 1;)
    {
    //This for loop opens or closes the doors and uses the interval(if interval is 2 it only uses every other etc..)
    for (a = 0; a <= 100; a += i;)
        {
        //Opens or closes a door.
        doors[a] = !doors[a];
        }
    }
open_doors = '';

//This for loop goes through the array and checks for open doors.
//If the door is open it adds it to the string then displays the string.
for (i = 1; i <= 100; i += 1;)
    {
    if (doors[i] == 1)
        {
        open_doors += "Door Number "+string(i)+" is open#";
        }
    }
show_message(open_doors);
game_end();


class VECOPS is
  mean(v:VEC):FLT is
    m ::= 0.0;
    loop m := m + v.aelt!; end;
    return m / v.dim.flt;
  end;
end;

class MAIN is
  main is
    v ::= #VEC(|1.0, 5.0, 7.0|);
    #OUT + VECOPS::mean(v) + "\n";
  end;
end;


def mean(s: Seq[Int]) = s.foldLeft(0)(_+_) / s.size


(define (mean l)
  (if (null? l)
      0
      (/ (apply + l) (length l))))


func fib(n) is cached {
    n < 2 ? 1
          : (fib(n-1) + fib(n-2))
}

func zeckendorf(n) {
    n == 0 && return '0'
    var i = 1
    ++i while (fib(i) <= n)
    gather {
        while (--i > 0) {
            var f = fib(i)
            f > n ? (take '0')
                  : (take '1'; n -= f)
        }
    }.join
}

for n (0..20) {
    printf("%4d: %8s\n", n, zeckendorf(n))
}


BEGIN
   INTEGER N, F0, F1, F2, D;
   N := 20;
   COMMENT CALCULATE D FROM ANY GIVEN N ;
   F1 := 1; F2 := 2; F0 := F1 + F2; D := 2;
   WHILE F0 < N DO BEGIN
      F1 := F2; F2 := F0; F0 := F1 + F2; D := D + 1;
   END;
   BEGIN
      COMMENT Sinclair ZX81 BASIC Solution ;
      TEXT Z1, S1;
      INTEGER I, J, Z;
      INTEGER ARRAY F(1:D);                  !  10 dim f(6) ;
      F(1) := 1;                             !  20 let f(1)=1 ;
      F(2) := 2;                             !  30 let f(2)=2 ;
      FOR I := 3 STEP 1 UNTIL D DO BEGIN     !  40 for i=3 to 6 ;
         F(I) := F(I-2) + F(I-1);            !  50 let f(i)=f(i-2)+f(i-1) ;
      END;                                   !  60 next i ;
      FOR I := 0 STEP 1 UNTIL N DO BEGIN     !  70 for i=0 to 20 ;
         Z1 :- "";                           !  80 let z$="" ;
         S1 :- " ";                          !  90 let s$=" " ;
         Z := I;                             ! 100 let z=i ;
         FOR J := D STEP -1 UNTIL 1 DO BEGIN ! 110 for j=6 to 1 step -1 ;
            IF J=1 THEN S1 :- "0";           ! 120 if j=1 then let s$="0" ;
            IF NOT (Z<F(J)) THEN BEGIN       ! 130 if z<f(j) then goto 180 ;
               Z1 :- Z1 & "1";               ! 140 let z$=z$+"1" ;
               Z := Z-F(J);                  ! 150 let z=z-f(j) ;
               S1 :- "0";                    ! 160 let s$="0" ;
            END ELSE                         ! 170 goto 190 ;
               Z1 :- Z1 & S1;                ! 180 let z$=z$+s$ ;
         END;                                ! 190 next j ;
         OUTINT(I, 0); OUTCHAR(' ');         ! 200 print i ; !" "; !;
         IF I<10 THEN OUTCHAR(' ');          ! 210 if i<10 then print " "; !;
         OUTTEXT(Z1); OUTIMAGE;              ! 220 print z$ ;
      END;                                   ! 230 next i ;
   END;
END


val zeckList = fn from => fn to =>

 let
  open IntInf

 val rec npow = fn n => fn 0 => fromInt 1 | m => n* (npow n (m-1)) ;

 val fib = fn 0 => 1 | 1 => 1 | n => let   val rec fb = fn x => fn y => fn 1=>y | n=> fb y (x+y) (n-1)  in
        fb 0 1  n
     end;

 val argminfi =  fn n =>                                          (* lowest k with fibonacci number over n *)
   let
      val rec afb = fn k => if fib k > n then k else afb (k+1)
   in
      afb 0
   end;

 val Zeck = fn n =>
   let
      val rec calzk = fn (0,z) => (0,z)
                       | (n,z) => let  val k =  argminfi n  in
                                     calzk ( n - fib (k-1) , z + (npow 10 (k-3) ) )
				  end
   in
      #2 (calzk (n,0))
  end

 in
     List.tabulate (toInt ( to - from) ,
                    fn i:Int.int => ( from + (fromInt i),
	            Zeck ( from + (fromInt i) )))
end;


package main

import "fmt"

func main() {
    doors := [100]bool{}

    // the 100 passes called for in the task description
    for pass := 1; pass <= 100; pass++ {
        for door := pass-1; door < 100; door += pass {
            doors[door] = !doors[door]
        }
    }

    // one more pass to answer the question
    for i, v := range doors {
        if v {
            fmt.Print("1")
        } else {
            fmt.Print("0")
        }

        if i%10 == 9 {
            fmt.Print("\n")
        } else {
            fmt.Print(" ")
        }

    }
}


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

const array float: numVector is [] (1.0, 2.0, 3.0, 4.0, 5.0);

const func float: mean (in array float: numbers) is func
  result
    var float: result is 0.0;
  local
    var float: total is 0.0;
    var float: num is 0.0;
  begin
    if length(numbers) <> 0 then
      for num range numbers do
        total +:= num;
      end for;
      result := total / flt(length(numbers));
    end if;
  end func;

const proc: main is func
  begin
    writeln(mean(numVector));
  end func;


put the average of [12,92,-17,66,128]

put average(empty)


package require Tcl 8.5

# Generates the Fibonacci sequence (starting at 1) up to the largest item that
# is no larger than the target value. Could use tricks to precompute, but this
# is actually a pretty cheap linear operation.
proc fibseq target {
    set seq {}; set prev 1; set fib 1
    for {set n 1;set i 1} {$fib <= $target} {incr n} {
	for {} {$i < $n} {incr i} {
	    lassign [list $fib [incr fib $prev]] prev fib
	}
	if {$fib <= $target} {
	    lappend seq $fib
	}
    }
    return $seq
}

# Produce the given Zeckendorf number.
proc zeckendorf n {
    # Special case: only value that begins with 0
    if {$n == 0} {return 0}
    set zs {}
    foreach f [lreverse [fibseq $n]] {
	lappend zs [set z [expr {$f <= $n}]]
	if {$z} {incr n [expr {-$f}]}
    }
    return [join $zs ""]
}


For x = 0 to 20                        ' Print Zeckendorf numbers 0 - 20
  Print x,
  Push x : Gosub _Zeckendorf           ' get Zeckendorf number repres.
  Print                                ' terminate line
Next

End

_Fibonacci
  Push Tos()                           ' duplicate TOS()
  @(0) = 0                             ' This function returns the
  @(1) = 1                             ' Fibonacci number which is smaller
                                       ' or equal to TOS()
  Do While @(1) < Tos() + 1
     Push (@(1))
     @(1) = @(0) + @(1)                ' get next Fibonacci number
     @(0) = Pop()
  Loop                                 ' loop if not exceeded TOS()

  Gosub _Drop                          ' clear TOS()
  Push @(0)                            ' return Fibonacci number
Return

_Zeckendorf
  GoSub _Fibonacci                     ' This function breaks TOS() up
  Print Tos();                         ' into its Zeckendorf components
  Push -(Pop() - Pop())                ' first digit is always there
                                       ' the remainder to resolve
  Do While Tos()                       ' now go for the next digits
    GoSub _Fibonacci
    Print " + ";Tos();                 ' print the next digit
    Push -(Pop() - Pop())
  Loop

  Gosub _Drop                          ' clear TOS()
Return                                 ' and return

_Drop
  If Pop()%1 = 0 Then Return           ' This function clears TOS()


Private Function zeckendorf(ByVal n As Integer) As Integer
    Dim r As Integer: r = 0
    Dim c As Integer
    Dim fib As New Collection
    fib.Add 1
    fib.Add 1
    Do While fib(fib.Count) < n
        fib.Add fib(fib.Count - 1) + fib(fib.Count)
    Loop
    For i = fib.Count To 2 Step -1
        c = n >= fib(i)
        r = r + r - c
        n = n + c * fib(i)
    Next i
    zeckendorf = r
End Function

Public Sub main()
    Dim i As Integer
    For i = 0 To 20
        Debug.Print Format(i, "@@"); ":"; Format(WorksheetFunction.Dec2Bin(zeckendorf(i)), "@@@@@@@")
    Next i
End Sub


[|:list| (list reduce: #+ `er ifEmpty: [0]) / (list isEmpty ifTrue: [1] ifFalse: [list size])] applyWith: #(3 1 4 1 5 9).
[|:list| (list reduce: #+ `er ifEmpty: [0]) / (list isEmpty ifTrue: [1] ifFalse: [list size])] applyWith: {}.


| numbers |

numbers := #(1 2 3 4 5 6 7 8).
(numbers isEmpty
    ifTrue:[0]
    ifFalse: [
         (numbers inject: 0 into: [:sumSoFar :eachElement | sumSoFar + eachElement]) / numbers size ]
) displayNl.


        define('avg(a)i,sum') :(avg_end)
avg     i = i + 1; sum = sum + a<i> :s(avg)
        avg = 1.0 * sum / prototype(a) :(return)
avg_end

*       # Fill arrays
        str = '1 2 3 4 5 6 7 8 9 10'; arr = array(10)
loop    i = i + 1; str len(p) span('0123456789') . arr<i> @p :s(loop)
        empty = array(1) ;* Null vector

*       # Test and display
        output = '[' str '] -> ' avg(arr)
        output = '[ ] -> ' avg(empty)
end


Function Zeckendorf(n)
	num = n
	Set fibonacci = CreateObject("System.Collections.Arraylist")
	fibonacci.Add 1 : fibonacci.Add 2
	i = 1
	Do While fibonacci(i) < num
		fibonacci.Add fibonacci(i) + fibonacci(i-1)
		i = i + 1
	Loop
	tmp = ""
	For j = fibonacci.Count-1 To 0 Step -1
		If fibonacci(j) <= num And (tmp = "" Or Left(tmp,1) <> "1") Then
			tmp = tmp & "1"
			num = num - fibonacci(j)
		Else
			tmp = tmp & "0"
		End If
	Next
	Zeckendorf = CLng(tmp)
End Function

'testing the function
For k = 0 To 20
	WScript.StdOut.WriteLine k & ": " & Zeckendorf(k)
Next


fn main() {
    for i := 0; i <= 20; i++ {
        println("${i:2} ${zeckendorf(i):7b}")
    }
}

fn 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
}

fn zr(fib0 int, fib1 int, n int, bit u32) (int, int) {
    mut set := 0
    mut remaining := 0
    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 remaining, set
}


import "/fmt" for Fmt

var LIMIT = 46  // to stay within range of signed 32 bit integer

var fibonacci = Fn.new { |n|
    if (n < 2 || n > LIMIT) Fiber.abort("n must be between 2 and %(LIMIT)")
    var fibs = List.filled(n, 1)
    for (i in 2...n) fibs[i] = fibs[i - 1] + fibs[i - 2]
    return fibs
}

var fibs = fibonacci.call(LIMIT)

var zeckendorf = Fn.new { |n|
    if (n < 0) Fiber.abort("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
        }
    }
    n = n - fibs[lastFibIndex]
    lastFibIndex = lastFibIndex - 1
    var zr = "1"
    for (i in lastFibIndex..1) {
        if (fibs[i] <= n) {
            zr = zr + "1"
            n = n - fibs[i]
        } else {
            zr = zr + "0"
        }
    }
    return zr
}

System.print(" n   z")
for (i in 0..20) Fmt.print("$2d : $s", i, zeckendorf.call(i))


uses java.util.Arrays

var doors = new boolean[100]
Arrays.fill( doors, false )

for( pass in 1..100 ) {
    var counter = pass-1
    while( counter < 100 ) {
        doors[counter] = !doors[counter]
        counter += pass
  }
}

for( door in doors index i ) {
    print( "door ${i+1} is ${door ? 'open' : 'closed'}" )
}


CREATE TABLE "numbers" ("datapoint" INTEGER);

INSERT INTO "numbers" SELECT rownum FROM tab;

SELECT SUM("datapoint")/COUNT(*)  FROM "numbers";


fun mean_reals [] = 0.0
  | mean_reals xs = foldl op+ 0.0 xs / real (length xs);

val mean_ints = mean_reals o (map real);


func meanDoubles(s: [Double]) -> Double {
  return s.reduce(0, +) / Double(s.count)
}
func meanInts(s: [Int]) -> Double {
  return meanDoubles(s.map{Double($0)})
}


include c:\cxpl\codes;          \intrinsic 'code' declarations

proc Zeckendorf(N);             \Display Zeckendorf number (N <= 20)
int N;
int Fib, LZ, I;
[Fib:= [1, 2, 3, 5, 8, 13];     \Fibonacci sequence
LZ:= true;                      \suppress leading zeros
for I:= 5 downto 1 do
        [if N >= Fib(I) then [N:= N-Fib(I);  ChOut(0, ^1);  LZ:= false]
        else ChOut(0, if LZ then ^  else ^0);
        ];
ChOut(0, N+^0);                 \output final digit, which can be 0
];

int N;
[for N:= 0 to 20 do
        [if N<10 then ChOut(0,^ );  IntOut(0, N);  Text(0, ": ");
        Zeckendorf(N);  CrLf(0);
        ];
]


sub Zeckendorf(n)
	local i, n$, c

	do
		n$ = bin$(i)
		if not instr(n$,"11") then
			print c,":\t",n$
			if c = n break
			c = c + 1
		end if
		i = i + 1
	loop
end sub

Zeckendorf(20)


    // return powers (0|1) of fib sequence (1,2,3,5,8...) that sum to n
fcn zeckendorf(n){ //-->String of 1s & 0s, no consecutive 1's
   if(n<=0) return("0");
   fibs:=fcn(ab){ ab.append(ab.sum()).pop(0) }.fp(L(1,2));
   (0).pump(*,List,fibs,'wrap(fib){ if(fib>n)Void.Stop else fib })
   .reverse()
   .pump(String,fcn(fib,rn){
      if(fib>rn.value)"0" else { rn.set(rn.value-fib); "1" } }.fp1(Ref(n)))
}


doors = [false] * 100
(0..99).each {
   it.step(100, it + 1) {
      doors[it] ^= true
   }
}
(0..99).each {
   println("Door #${it + 1} is ${doors[it] ? 'open' : 'closed'}.")
}


package require Tcl 8.5
proc mean args {
    if {[set num [llength $args]] == 0} {return 0}
    expr {[tcl::mathop::+ {*}$args] / double($num)}
}
mean 3 1 4 1 5 9 ;# ==> 3.8333333333333335


Define rcmean(nums) = when(dim(nums) = 0, 0, mean(nums))


: mean dup empty? [drop 0] [dup [+] foldl1 swap length /] branch ;

[3 1 4 1 5 9] mean


10 DIM A(100)
20 FOR OFFSET = 1 TO 100
30      FOR I = 0 TO 100 STEP OFFSET
40              A(I) = A(I) + 1
50      NEXT I
60 NEXT OFFSET
70 ' Print "opened" doors
80 FOR I = 1 TO 100
90      IF A(I) MOD 2 = 1 THEN PRINT I
100 NEXT I


function mean(numbersArr)
{
    let arrLen = numbersArr.length;
    if (arrLen > 0) {
        let sum: number = 0;
        for (let i of numbersArr) {
            sum += i;
        }
        return sum/arrLen;
    }
    else return "Not defined";
}

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


echo "`cat f | paste -sd+ | bc -l` / `cat f | wc -l`" | bc -l


term() {
   b=$1;res=$2
   echo "scale=5;$res+$b" | bc
}

sum() {
  (read B; res=$1;
  test -n "$B" && (term $B $res) || (term 0 $res))
}

fold() {
  func=$1
  (while read a ; do
      fold $func | $func $a
  done)
}

mean() {
  tee >(wc -l > count) | fold sum | xargs echo "scale=5;(1/" $(cat count) ") * " | bc
}

(echo 3; echo 1; echo 4) | mean


#
# arithmetic mean
#

decl int<> input
decl int i
for (set i 1) (< i (size args)) (inc i)
        append (int args<i>) input
end for

out (/ (+ input) (size input)) endl console


#define ARRAY_ELEMENTS 100
PROCEDURE Main()
   LOCAL aDoors := Array( ARRAY_ELEMENTS )
   LOCAL i, j

   AFill( aDoors, .F. )
   FOR i := 1 TO ARRAY_ELEMENTS
      FOR j := i TO ARRAY_ELEMENTS STEP i
         aDoors[ j ] = ! aDoors[ j ]
      NEXT
   NEXT
   AEval( aDoors, {|e, n| QQout( Padl(n,3) + " is " + Iif(aDoors[n], "*open*", "closed" ) + "|" ), Iif( n%5 == 0, Qout(), e:=NIL) } )
   RETURN


#import nat
#import flo

mean = ~&?\0.! div^/plus:-0. float+ length

#cast %e

example = mean <5.,3.,-2.,6.,-4.>


[mean
   [sum 0 [+] fold].
   dup sum
   swap size [[1 <] [1]] when /
].


double arithmetic(double[] list){
	double mean;
	double sum = 0;

	if (list.length == 0)
		return 0.0;
	foreach(double number in list){
		sum += number;
	} // foreach

	mean = sum / list.length;

	return mean;
} // end arithmetic mean

public static void main(){
	double[] test = {1.0, 2.0, 5.0, -5.0, 9.5, 3.14159};
	double[] zero_len = {};

	double mean = arithmetic(test);
	double mean_zero = arithmetic(zero_len);

	stdout.printf("%s\n", mean.to_string());
	stdout.printf("%s\n", mean_zero.to_string());
}


data Door
  = Open
  | Closed
  deriving (Eq, Show)

toggle :: Door -> Door
toggle Open = Closed
toggle Closed = Open

toggleEvery :: Int -> [Door] -> [Door]
toggleEvery k = zipWith toggleK [1 ..]
  where
    toggleK n door
      | n `mod` k == 0 = toggle door
      | otherwise = door

run :: Int -> [Door]
run n = foldr toggleEvery (replicate n Closed) [1 .. n]

main :: IO ()
main = print $ filter ((== Open) . snd) $ zip [1 ..] (run 100)


Private Function mean(v() As Double, ByVal leng As Integer) As Variant
    Dim sum As Double, i As Integer
    sum = 0: i = 0
    For i = 0 To leng - 1
        sum = sum + vv
    Next i
    If leng = 0 Then
        mean = CVErr(xlErrDiv0)
    Else
        mean = sum / leng
    End If
End Function
Public Sub main()
    Dim v(4) As Double
    Dim i As Integer, leng As Integer
    v(0) = 1#
    v(1) = 2#
    v(2) = 2.178
    v(3) = 3#
    v(4) = 3.142
    For leng = 5 To 0 Step -1
        Debug.Print "mean[";
        For i = 0 To leng - 1
            Debug.Print IIf(i, "; " & v(i), "" & v(i));
        Next i
        Debug.Print "] = "; mean(v, leng)
    Next leng
End Sub


Function mean(arr)
	size = UBound(arr) + 1
	mean = 0
	For i = 0 To UBound(arr)
		mean = mean + arr(i)
	Next
	mean = mean/size
End Function

'Example
WScript.Echo mean(Array(3,1,4,1,5,9))


#1 = 0			// Sum
#2 = 0			// Count
BOF
While(!At_EOF) {
    #1 += Num_Eval(SIMPLE)
    #2++
    Line(1, ERRBREAK)
}
if (#2) { #1 /= #2 }
Num_Type(#1)


class RosettaDemo
{
    static public function main()
    {
        findOpenLockers(100);
    }

    static function findOpenLockers(n : Int)
    {
        var i = 1;

        while((i*i) <= n)
        {
            Sys.print(i*i + "\n");
            i++;
        }
    }
}


function Mean(lst)
    if empty(a:lst)
        throw "Empty"
    endif
    let sum = 0.0
    for i in a:lst
        let sum += i
    endfor
    return sum / len(a:lst)
endfunction


import math
import arrays

fn main() {
    for v in [
        []f64{},                         // mean returns ok = false
        [math.inf(1), math.inf(1)], // answer is +Inf

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

        [f64(3), 1, 4, 1, 5, 9],

        [f64(10), 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11],
        [f64(10), 20, 30, 40, 50, -100, 4.7, -11e2],
    ] {
        println("Vector: $v")
        m := arrays.fold(v, 0.0, fn(r f64, v f64) f64 { return r+v })/v.len
        println("Mean of $v.len numbers is $m\n")
    }
}


let s => import 'stream';
let a => import 'arrays';

let mean nums =>
  a.stream nums
  -> s.reduce [0; 0] (@ s p n => [+ (a.at p 0) 1; + (a.at p 1) n])
  -> (@ s p => / (a.at p 1) (a.at p 0));


REAL :: n=100, open=1, door(n)

door = 1 - open ! = closed
DO i = 1, n
  DO j = i, n, i
    door(j) = open - door(j)
  ENDDO
ENDDO
DLG(Text=door, TItle=SUM(door)//" doors open")


@let {
  ; using a fork (sum divided-by length)
  mean1 @(@sum / #)

  ; using a function with a named argument
  mean2 &a / @sum a #a

  [[
    !mean1 [3 1 4 1 5 9 2]
    !mean2 [3 1 4 1 5 9 2]
  ]]
}


class Arithmetic {
    static mean(arr) {
        if (arr.count == 0) Fiber.abort("Length must be greater than zero")
        return arr.reduce(Fn.new{ |x,y| x+y }) / arr.count
    }
}
Arithmetic.mean([1,2,3,4,5]) // 3


(defun mean (v)
    (if (= (vector-length v) 0)
        nil
        (let ((l (vector->list v)))
            (/ (apply + l) (length l)))))


code CrLf=9;
code real RlOut=48;

func real Mean(A, N);
real A;  int N;
real S;  int I;
[if N=0 then return 0.0;
S:= 0.0;
for I:= 0 to N-1 do
        S:= S+A(I);
return S/float(N);
]; \Mean

real Test;
[Test:= [1.0, 2.0, 5.0, -5.0, 9.5, 3.14159];
RlOut(0, Mean(Test, 6));  CrLf(0);
]


U8 is_open[100];
U8 pass = 0, door = 0;

/* do the 100 passes */
for (pass = 0; pass < 100; ++pass)
  for (door = pass; door < 100; door += pass + 1)
    is_open[door] = !is_open[door];

/* output the result */
for (door = 0; door < 100; ++door)
  if (is_open[door])
    Print("Door #%d is open.\n", door + 1);
  else
    Print("Door #%d is closed.\n", door + 1);


|^
=/  doors=(list ?)  (reap 100 %.n)
=/  passes=(list (list ?))  (turn (gulf 1 100) pass-n)
|-
?~  passes  doors
$(doors (toggle doors i.passes), passes t.passes)
++  pass-n
  |=  [email protected]
  (turn (gulf 1 100) |=([email protected] =((mod k n) 0)))
++  toggle
  |=  [a=(list ?) b=(list ?)]
  =|  c=(list ?)
  |-
  ?:  |(?=(~ a) ?=(~ b))  (flop c)
  $(a t.a, b t.b, c [=((mix i.a i.b) 1) c])
--


func mean(x) {
    if(is_void(x)) return 0;
    return x(*)(avg);
}


fcn mean(a,b,c,etc){ z:=vm.arglist; z.reduce('+,0.0)/z.len() }
mean(3,1,4,1,5,9);  //-->3.83333
mean(); //-->Exception thrown: MathError(NaN (Not a number))


program: average
  case: 1
    input: [2,3,10]
    output: 5
  case: 2
    input: [7,11]
    output: 9


#! /bin/sh
exec huginn --no-argv -E "${0}"
#! huginn

import Algorithms as algo;

main() {
        doorCount = 100;
        doors = [].resize( doorCount, false );

        for ( pass : algo.range( doorCount ) ) {
                i = 0;
                step = pass + 1;
                while ( i < doorCount ) {
                        doors[i] = ! doors[i];
                        i += step;
                }
        }

        for ( i : algo.range( doorCount ) ) {
                if ( doors[i] ) {
                        print( "door {} is open\n".format( i ) );
                }
        }
        return ( 0 );
}


module Averages;
type
	Vector = array {math} * of real;

	procedure ArithmeticMean(x: Vector): real;
	begin
		(* sum is a predefined function for mathematical arrays *)
		return sum(x)
	end ArithmeticMean;
var
	x: Vector;

begin
	x := new Vector(4);
	x := [1.0, 2.3, 3.2, 2.1, 5.3];
	write("arithmetic mean: ");writeln(ArithmeticMean(x):10:2)
end Averages.


(setv doors (* [False] 100))

(for [pass (range (len doors))]
  (for [i (range pass (len doors) (inc pass))]
    (assoc doors i (not (get doors i)))))

(for [i (range (len doors))]
  (print (.format "Door {} is {}."
    (inc i)
    (if (get doors i) "open" "closed"))))


software {
	var doors = len(100)

	for pass over [1, 100]
		var door = pass - 1
		loop door < len(doors) {
			doors[door] = doors[door]/0
			door += pass
		}
	end

	for door,isopen in doors
		if isopen
			print("Door ",door+1,": open")
		end
	end
	print("All other doors are closed")
}


procedure main()
    door := table(0)    # default value of entries is 0
    every pass := 1 to 100 do
        every door[i := pass to 100 by pass] := 1 - door[i]

    every write("Door ", i := 1 to 100, " is ", if door[i] = 1 then "open" else "closed")
end


import Data.Vect

-- Creates list from 0 to n (not including n)
upTo : (m : Nat) -> Vect m (Fin m)
upTo Z = []
upTo (S n) = 0 :: (map FS (upTo n))

data DoorState = DoorOpen | DoorClosed

toggleDoor : DoorState -> DoorState
toggleDoor DoorOpen = DoorClosed
toggleDoor DoorClosed = DoorOpen

isOpen : DoorState -> Bool
isOpen DoorOpen = True
isOpen DoorClosed = False

initialDoors : Vect 100 DoorState
initialDoors = fromList $ map (\_ => DoorClosed) [1..100]

iterate : (n : Fin m) -> Vect m DoorState -> Vect m DoorState
iterate n doors {m} =
  map (\(idx, doorState) =>
          if ((S (finToNat idx)) `mod` (S (finToNat n))) == Z
              then toggleDoor doorState
              else doorState)
      (zip (upTo m) doors)

-- Returns all doors left open at the end
solveDoors : List (Fin 100)
solveDoors =
  findIndices isOpen $ foldl (\doors,val => iterate val doors) initialDoors (upTo 100)

main : IO ()
main = print $ map (\n => S (finToNat n)) solveDoors


Hallway is a room.

A toggle door is a kind of thing.
A toggle door can be open or closed. It is usually closed.
A toggle door has a number called the door number.
Understand the door number property as referring to a toggle door.
Rule for printing the name of a toggle door: say "door #[door number]".

There are 100 toggle doors.

When play begins (this is the initialize doors rule):
	let the next door number be 1;
	repeat with D running through toggle doors:
		now the door number of D is the next door number;
		increment the next door number.

To toggle (D - open toggle door): now D is closed.
To toggle (D - closed toggle door): now D is open.

When play begins (this is the solve puzzle rule):
	let the door list be the list of toggle doors;
	let the door count be the number of entries in the door list;
	repeat with iteration running from 1 to 100:
		let N be the iteration;
		while N is less than the door count:
			toggle entry N in the door list;
			increase N by the iteration;
	say "Doors left open: [list of open toggle doors].";
	end the story.


MAIN
    DEFINE
        i, pass SMALLINT,
        doors ARRAY[100] OF SMALLINT

    FOR i = 1 TO 100
        LET doors[i] = FALSE
    END FOR

    FOR pass = 1 TO 100
        FOR i = pass TO 100 STEP pass
            LET doors[i] = NOT doors[i]
        END FOR
    END FOR

    FOR i = 1 TO 100
        IF doors[i]
          THEN DISPLAY i USING "Door <<& is open"
          ELSE DISPLAY i USING "Door <<& is closed"
        END IF
    END FOR
END MAIN


doors := List clone
100 repeat(doors append(false))
for(i,1,100,
    for(x,i,100, i, doors atPut(x - 1, doors at(x - 1) not))
)
doors foreach(i, x, if(x, "Door #{i + 1} is open" interpolate println))


NDoors = Origin mimic

NDoors Toggle = Origin mimic do(
  initialize = method(toggled?, @toggled? = toggled?)
  toggle! = method(@toggled? = !toggled?. self)
)

NDoors Doors = Origin mimic do(
  initialize = method(n,
    @n = n
    @doors = {} addKeysAndValues(1..n, (1..n) map(_, NDoors Toggle mimic(false)))
  )
  numsToToggle = method(n, for(x <- ([email protected]), (x % n) zero?, x))
  toggleThese = method(nums, nums each(x, @doors[x] = @doors at(x) toggle))
  show = method(@doors filter:dict(value toggled?) keys sort println)
)

; Test code
x = NDoors Doors mimic(100)
(1..100) each(n, x toggleThese(x numsToToggle(n)))
x show


theory Scratch
  imports Main
begin

section‹100 Doors›

  datatype doorstate = Open | Closed

  fun toggle :: "doorstate ⇒ doorstate" where
    "toggle Open   = Closed"
  | "toggle Closed = Open"

  fun walk :: "('a ⇒ 'a) ⇒ nat ⇒ nat ⇒ 'a list ⇒ 'a list" where
    "walk f _     _       []     = []"
  | "walk f every 0       (x#xs) = (f x) # walk f every every xs"
  | "walk f every (Suc n) (x#xs) = x # walk f every n xs"

  text‹Example: \<^const>‹toggle› every second door. (second = 1, because of 0 indexing)›
  lemma "walk toggle 1 1 [Open, Open, Open, Open, Open, Open] =
                         [Open, Closed, Open, Closed, Open, Closed]" by code_simp

  text‹Example: \<^const>‹toggle› every third door.›
  lemma "walk toggle 2 2 [Open, Open, Open, Open, Open, Open] =
                         [Open, Open, Closed, Open, Open, Closed]" by code_simp

  text‹Walking each door is essentially the same as the common \<^const>‹map› function.›
  lemma "walk f 0 0 xs = map f xs"
    by(induction xs) (simp)+

  lemma walk_beginning:
    "walk f every n xs = (walk f every n (take (Suc n) xs)) @ (walk f every every (drop (Suc n) xs))"
    by(induction f every n xs rule:walk.induct) (simp)+

  text‹A convenience definition to take the off-by-one into account and setting the starting position.›
  definition visit_every :: "('a ⇒ 'a) ⇒ nat ⇒ 'a list ⇒ 'a list" where
    "visit_every f every xs ≡ walk f (every - 1) (every - 1) xs"

  fun iterate :: "nat ⇒ (nat ⇒ 'a ⇒ 'a) ⇒ nat ⇒ 'a ⇒ 'a" where
    "iterate 0       _ _ a = a"
  | "iterate (Suc i) f n a = iterate i f (Suc n) (f n a)"

  text‹The 100 doors problem.›
  definition "onehundred_doors ≡ iterate 100 (visit_every toggle) 1 (replicate 100 Closed)"

  lemma "onehundred_doors =
    [Open, Closed, Closed, Open, Closed, Closed, Closed,
     Closed, Open, Closed, Closed, Closed, Closed, Closed,
     Closed, Open, Closed, Closed, Closed, Closed, Closed,
     Closed, Closed, Closed, Open, Closed, Closed, Closed,
     Closed, Closed, Closed, Closed, Closed, Closed, Closed,
     Open, Closed, Closed, Closed, Closed, Closed, Closed,
     Closed, Closed, Closed, Closed, Closed, Closed, Open,
     Closed, Closed, Closed, Closed, Closed, Closed, Closed,
     Closed, Closed, Closed, Closed, Closed, Closed, Closed,
     Open, Closed, Closed, Closed, Closed, Closed, Closed,
     Closed, Closed, Closed, Closed, Closed, Closed, Closed,
     Closed, Closed, Closed, Open, Closed, Closed, Closed,
     Closed, Closed, Closed, Closed, Closed, Closed, Closed,
     Closed, Closed, Closed, Closed, Closed, Closed, Closed,
     Closed, Open]" by code_simp

  text‹Filtering for the open doors, we get the same result as the Haskell implementation.›
  lemma
    "[(i, door) ← enumerate 1 onehundred_doors. door = Open] =
     [(1,Open),(4,Open),(9,Open),(16,Open),(25,Open),(36,Open),(49,Open),(64,Open),(81,Open),(100,Open)]"
    by code_simp

section‹Equivalence to Haskell Implementation›
text‹
We will now present an alternative implementation, which is similar to the Haskell implementation
on 🌐‹https://rosettacode.org/wiki/100_doors#Haskell›. We will prove, that the two behave the same;
in general, not just for a fixed set of 100 doors.
›

  definition map_every_start :: "('a ⇒ 'a) ⇒ nat ⇒ nat ⇒ 'a list ⇒ 'a list" where
    "map_every_start f every start xs ≡
      map (λ(i, x). if i mod every = 0 then f x else x) (enumerate start xs)"

  definition visit_every_alt :: "('a ⇒ 'a) ⇒ nat ⇒ 'a list ⇒ 'a list" where
    "visit_every_alt f every xs ≡ map_every_start f every 1 xs"

  text‹Essentially, \<^term>‹start› and \<^term>‹start mod every› behave the same.›
  lemma map_every_start_cycle:
    "map_every_start f every (start + k*every) xs = map_every_start f every start xs"
    proof(induction xs arbitrary: start)
      case Nil
      show "map_every_start f every (start + k * every) [] = map_every_start f every start []"
        by(simp add: map_every_start_def)
    next
      case (Cons x xs)
      from Cons.IH[of "Suc start"]
        show "map_every_start f every (start + k * every) (x # xs) =
              map_every_start f every start (x # xs)"
        by(simp add: map_every_start_def)
    qed
  corollary map_every_start_cycle_zero:
    "map_every_start f every every xs = map_every_start f every 0 xs"
    using map_every_start_cycle[where k=1 and start=0, simplified] by blast

  lemma map_every_start_fst_zero:
    "map_every_start f every 0 (x # xs) = f x # map_every_start f every (Suc 0) xs"
    by(simp add: map_every_start_def)

  text‹
  The first \<^term>‹n› elements are not processed by \<^term>‹f›,
  as long as \<^term>‹n› is less than the \<^term>‹every› cycle.
  ›
  lemma map_every_start_skip_first: "Suc n < every ⟹
         map_every_start f every (every - (Suc n)) (x # xs) =
         x # map_every_start f every (every - n) xs"
    by(simp add: map_every_start_def Suc_diff_Suc)

  lemma map_every_start_append:
    "map_every_start f n s (ds1 @ ds2) =
     map_every_start f n s ds1 @ map_every_start f n (s + length ds1) ds2"
    by(simp add: map_every_start_def enumerate_append_eq)

  text‹
  The \<^const>‹walk› function and \<^const>‹map_every_start› behave the same,
  as long as the starting \<^term>‹n› is less than the \<^term>‹every› cycle,
  because \<^const>‹walk› allows pushing the start arbitrarily far and
  \<^const>‹map_every_start› only allows deferring the start within
  the \<^term>‹every› cycle.
  This generalization is needed to strengthen the induction hypothesis
  for the proof.
  ›
  lemma walk_eq_map_every_start:
    "n ≤ every ⟹ walk f every n xs = map_every_start f (Suc every) (Suc every - n) xs"
    proof(induction xs arbitrary: n)
      case Nil
      show "walk f every n [] = map_every_start f (Suc every) (Suc every - n) []"
        by(simp add: map_every_start_def)
    next
      case (Cons x xs)
      then show "walk f every n (x # xs) = map_every_start f (Suc every) (Suc every - n) (x # xs)"
      proof(cases n)
        case 0
        with Cons.IH show ?thesis
          by(simp add: map_every_start_cycle_zero map_every_start_fst_zero)
      next
        case (Suc n2)
        with Cons.prems map_every_start_skip_first[of n2 "Suc every"] have
          "map_every_start f (Suc every) (Suc every - Suc n2) (x # xs) =
           x # map_every_start f (Suc every) (Suc every - n2) xs"
          by fastforce
        with Suc Cons show ?thesis
          by(simp)
      qed
    qed

  corollary walk_eq_visit_every_alt:
    "walk f every every xs = visit_every_alt f (Suc every) xs"
    unfolding visit_every_alt_def
    using walk_eq_map_every_start by fastforce

  text‹
  Despite their very different implementations, our alternative visit function behaves the same
  as our original visit function.
  Text the theorem includes \<^term>‹Suc every› to express that we exclude \<^term>‹every = 0›.
  ›
  theorem visit_every_eq_visit_every_alt:
    "visit_every f (Suc every) xs = visit_every_alt f (Suc every) xs"
    unfolding visit_every_def
    using walk_eq_visit_every_alt by fastforce

  text‹Also, the \<^const>‹iterate› function we implemented above can be implemented by a simple \<^const>‹fold›.›
  lemma fold_upt_helper: assumes n_geq_1: "Suc 0 ≤ n"
    shows "fold f [Suc s..<n + s] (f s xs) = fold f [s..<n + s] xs"
  proof -
    from n_geq_1 have "[s..<n + s] = s#[Suc s..<n + s]" by (simp add: Suc_le_lessD upt_rec)
    from this have "fold f [s..<n + s] xs = fold f (s#[Suc s..<n + s]) xs" by simp
    also have "fold f (s#[Suc s..<n + s]) xs = fold f [Suc s..<n + s] (f s xs)" by(simp)
    ultimately show ?thesis by simp
  qed

  theorem iterate_eq_fold: "iterate n f s xs = fold f [s ..< n+s] xs"
  proof(induction n arbitrary: s xs)
    case 0
    then show "iterate 0 f s xs = fold f [s..<0 + s] xs" by simp
  next
    case (Suc n)
    from Suc show "iterate (Suc n) f s xs = fold f [s..<Suc n + s] xs"
      by(simp add: fold_upt_helper not_less_eq_eq)
  qed

section‹Efficient Implementation›
text ‹
As noted on this page, the only doors that remain open are those whose numbers are perfect squares.
Yet, rosettacode does not want us to take this shortcut, since we want to compare implementations
across programming languages. But we can prove that our code computes the same result as reporting
all doors with a perfect square number as open:
›
  theorem "[(i, door) ← enumerate 1 onehundred_doors. door = Open] =
           [(i*i, Open). i ← [1..<11]]"
    by code_simp
end


(def doors (seq [_ :range [0 100]] false))

(loop [pass :range [0 100]
       door :range [pass 100 (inc pass)]]
  (put doors door (not (doors door))))

(print "open doors: " ;(seq [i :range [0 100] :when (doors i)] (string (inc i) " ")))


class HundredDoors {
    public static void main(String[] args) {
        boolean[] doors = new boolean[101];

        for (int i = 1; i < doors.length; i++) {
            for (int j = i; j < doors.length; j += i) {
                doors[j] = !doors[j];
            }
        }

        for (int i = 1; i < doors.length; i++) {
            if (doors[i]) {
                System.out.printf("Door %d is open.%n", i);
            }
        }
    }
}


var doors=[];
for (var i=0;i<100;i++)
    doors[i]=false;
for (var i=1;i<=100;i++)
    for (var i2=i-1,g;i2<100;i2+=i)
        doors[i2]=!doors[i2];
for (var i=1;i<=100;i++)
    console.log("Door %d is %s",i,doors[i-1]?"open":"closed")


# Solution for n doors:
def doors(n):

  def print:
    . as $doors
    | range(1; length+1)
    | if $doors[.] then "Door \(.) is open" else empty end;

    [range(n+1)|null] as $doors
  | reduce range(1; n+1) as $run
      ( $doors; reduce range($run; n+1; $run ) as $door
                  ( .; .[$door] = (.[$door] | not) ) )
  | print ;


doors = falses(100)
for a in 1:100, b in a:a:100
    doors[b] = !doors[b]
end
for a = 1:100
    println("Door $a is " * (doors[a] ? "open." : "closed."))
end


include ..\Utilitys.tlhy

%n 100 !n
0 $n repeat

$n [dup sqrt int dup * over
== ( [1 swap set] [drop] ) if] for

$n [ ( "The door " over  " is " ) lprint get ( ["OPEN"] ["closed"] ) if print nl] for

( "Time elapsed: " msec " seconds" ) lprint nl

pstack
" " input


fun oneHundredDoors(): List<Int> {
    val doors = BooleanArray(100, { false })
    for (i in 0..99) {
        for (j in i..99 step (i + 1)) {
            doors[j] = !doors[j]
        }
    }
    return doors
        .mapIndexed { i, b -> i to b }
        .filter { it.second }
        .map { it.first + 1 }
}


range InitialDoor from 1 to 100 step 1
| extend DoorsVisited=range(InitialDoor, 100, InitialDoor)
| mvexpand DoorVisited=DoorsVisited to typeof(int)
| summarize VisitCount=count() by DoorVisited
| project Door=DoorVisited, IsOpen=(VisitCount % 2) == 1


var .doors = arr 100, false

for .i of .doors {
    for .j = .i; .j <= len(.doors); .j += .i {
        .doors[.j] = not .doors[.j]
    }
}

writeln wherekeys .doors


1) unoptimized version

{def doors
 {A.new
  {S.map {lambda {} false} {S.serie 1 100}}}}
-> doors

{def toggle
 {lambda {:i :a}
  {let { {_ {A.set! :i {not {A.get :i :a}} :a} }}}}}
-> toggle

{S.map {lambda {:b}
 {S.map {lambda {:i} {toggle :i {doors}}}
  {S.serie :b 99 {+ :b 1}}}}
   {S.serie 0 99}}
->

{S.replace \s by space in
 {S.map {lambda {:i} {if {A.get :i {doors}} then {+ :i 1} else}}
  {S.serie 0 99}}}

-> 1 4 9 16 25 36 49 64 81 100

2.2) optimized version

{S.replace \s by space in
 {S.map {lambda {:i}
         {let { {:root {sqrt :i}} }
              {if {= :root {round :root}}
               then {* :root :root}
               else}}}
        {S.serie 1 100}}}

-> 1 4 9 16 25 36 49 64 81 100


loop(100) => {^
	local(root = math_sqrt(loop_count))
	local(state = (#root == math_ceil(#root) ? 'open' | 'closed'))
	#state != 'closed' ? 'Door ' + loop_count + ': ' + #state + '
'
^}


use 'format importAllSigils.

doors := Object clone.
doors missing := { False. }.
doors check := {
  self slot ($1 ordinal).
}.
doors toggle := {
  self slot ($1 ordinal) = self slot ($1 ordinal) not.
}.
1 upto 101 do {
  takes '[i].
  local 'j = i.
  while { j <= 100. } do {
    doors toggle (j).
    j = j + i.
  }.
}.
$stdout printf: ~fmt "The open doors are: ~A", 1 upto 101 filter { doors check. } to (Array).


to doors
	;Problem 100 Doors
	;Lhogho

	for "p [1 100]
	[
		make :p "false
	]

	for "a [1 100 1]
	[
		for "b [:a 100 :a]
		[
			if :b < 101
			[
				make :b not thing :b
			]
		]
	]

	for "c [1 100]
	[
		if thing :c
		[
			(print "door :c "is "open)
		]
	]
end

doors


dim doors(100)
for pass = 1 to 100
    for door = pass to 100 step pass
        doors(door) = not(doors(door))
    next door
next pass
print "open doors ";
for door = 1 to 100
    if doors(door) then print door;"  ";
next door


var doors = List.fill(100, false)

for i in 0...99:
    for j in i...99 by i + 1:
        doors[j] = !doors[j]

# The type must be specified since the list starts off empty.
var open_doors: List[Integer] = []

doors.each_index{|i|
    if doors[i]:
        open_doors.push(i + 1)
}

print($"Open doors: ^(open_doors)")


on mouseUp
   repeat with tStep = 1 to 100
      repeat with tDoor = tStep to 100 step tStep
         put not tDoors[tDoor] into tDoors[tDoor]
      end repeat
      if tDoors[tStep] then put "Door " & tStep & " is open" & cr after tList
   end repeat
   set the text of field "Doors" to tList
end mouseUp


to doors
;Problem 100 Doors
;FMSLogo
;lrcvs 2010

make "door (vector 100 1)
for [p 1 100][setitem :p :door 0]

for [a 1 100 1][for [b :a 100 :a][make "x item :b :door
	                          ifelse :x  = 0 [setitem :b :door 1][setitem :b :door 0] ] ]

for [c 1 100][make "y item :c :door
	      ifelse :y = 0 [pr (list :c "Close)] [pr (list :c "Open)] ]
end


HAI 1.3

I HAS A doors ITZ A BUKKIT
IM IN YR hallway UPPIN YR door TIL BOTH SAEM door AN 100
    doors HAS A SRS door ITZ FAIL BTW, INISHULIZE ALL TEH DOORZ AS CLOZD
IM OUTTA YR hallway

IM IN YR hallway UPPIN YR pass TIL BOTH SAEM pass AN 100
    I HAS A door ITZ pass
    IM IN YR passer
        doors'Z SRS door R NOT doors'Z SRS door
        door R SUM OF door AN SUM OF pass AN 1
        DIFFRINT door AN SMALLR OF door AN 99, O RLY?
            YA RLY, GTFO
        OIC
    IM OUTTA YR passer
IM OUTTA YR hallway

IM IN YR printer UPPIN YR door TIL BOTH SAEM door AN 100
    VISIBLE "Door #" SUM OF door AN 1 " is "!
    doors'Z SRS door, O RLY?
        YA RLY, VISIBLE "open."
        NO WAI, VISIBLE "closed."
    OIC
IM OUTTA YR printer

KTHXBYE


local is_open = {}

for pass = 1,100 do
    for door = pass,100,pass do
        is_open[door] = not is_open[door]
    end
end

for i,v in next,is_open do
    print ('Door '..i..':',v and 'open' or 'close')
end


Module Doors100 {
      Dim Doors(1 to 100)
      For i=1 to 100
            For j=i to 100 step i
                  Doors(j)~
            Next j
      Next i
      DispAll()
      ' optimization
      Dim Doors(1 to 100)=False
      For i=1 to 10
            Doors(i**2)=True
      Next i
      Print
      DispAll()
      Sub DispAll()
            Local i
            For i=1 to 100
                  if Doors(i) then print i,
            Next i
            Print
      End Sub
}
Doors100


            NORMAL MODE IS INTEGER
            DIMENSION OPEN(100)
            PRINT COMMENT $ $

          R MAKE SURE ALL DOORS ARE CLOSED AT BEGINNING
            THROUGH CLOSE, FOR DOOR=1, 1, DOOR.G.100
CLOSE       OPEN(DOOR) = 0

          R MAKE 100 PASSES
            THROUGH TOGGLE, FOR PASS=1, 1, PASS.G.100
            THROUGH TOGGLE, FOR DOOR=PASS, PASS, DOOR.G.100
TOGGLE      OPEN(DOOR) = 1 - OPEN(DOOR)

          R PRINT THE DOORS THAT ARE OPEN
            THROUGH SHOW, FOR DOOR=1, 1, DOOR.G.100
SHOW        WHENEVER OPEN(DOOR).E.1, PRINT FORMAT ISOPEN, DOOR

            VECTOR VALUES ISOPEN = $5HDOOR ,I3,S1,8HIS OPEN.*$
            END OF PROGRAM


NDoors := proc( N :: posint )
        # Initialise, using 0 to represent "closed"
        local pass, door, doors := Array( 1 .. N, 'datatype' = 'integer'[ 1 ] );
        # Now do N passes
        for pass from 1 to N do
                for door from pass by pass while door <= N do
                        doors[ door ] := 1 - doors[ door ]
                end do
        end do;
        # Output
        for door from 1 to N do
                printf( "Door %d is %s.\n", door, `if`( doors[ door ] = 0, "closed", "open" ) )
        end do;
        # Since this is a printing routine, return nothing.
        NULL
end proc:


n=100;
tmp=ConstantArray[-1,n];
Do[tmp[[i;;;;i]]*=-1;,{i,n}];
Do[Print["door ",i," is ",If[tmp[[i]]==-1,"closed","open"]],{i,1,Length[tmp]}]


doors(n) := block([v], local(v),
  v: makelist(true, n),
  for i: 2 thru n do
  for j: i step i thru n do v[j]: not v[j],
  sublist_indices(v, 'identity));


doorsOpen = for i in 1 to 100 collect false

for pass in 1 to 100 do
(
    for door in pass to 100 by pass do
    (
        doorsOpen[door] = not doorsOpen[door]
    )
)

for i in 1 to doorsOpen.count do
(
    format ("Door % is open?: %\n") i doorsOpen[i]
)


:- module doors.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module bitmap, bool, list, string, int.

:- func doors = bitmap.
doors = bitmap.init(100, no).

:- pred walk(int, bitmap, bitmap).
:- mode walk(in, bitmap_di, bitmap_uo) is det.
walk(Pass, !Doors) :-
    walk(Pass, Pass, !Doors).

:- pred walk(int, int, bitmap, bitmap).
:- mode walk(in, in, bitmap_di, bitmap_uo) is det.
walk(At, By, !Doors) :-
    ( if bitmap.in_range(!.Doors, At - 1) then
        bitmap.unsafe_flip(At - 1, !Doors),
        walk(At + By, By, !Doors)
    else
        true
    ).

:- pred report(bitmap, int, io, io).
:- mode report(bitmap_di, in, di, uo) is det.
report(Doors, N, !IO) :-
    ( if is_set(Doors, N - 1) then
        State = "open"
    else
        State = "closed"
    ),
    io.format("door #%d is %s\n",
        [i(N), s(State)], !IO).

main(!IO) :-
    list.foldl(walk, 1 .. 100, doors, Doors),
    list.foldl(report(Doors), 1 .. 100, !IO).


boolean doors[];
for i = 1 upto 100: doors[i] := false; endfor
for i = 1 upto 100:
  for j = 1 step i until 100:
    doors[j] := not doors[j];
  endfor
endfor
for i = 1 upto 100:
  message decimal(i) & " " & if doors[i]: "open" else: "close" fi;
endfor
end


For offset = 1 To 100
  For i = 0 To 100 Step offset
    a[i] = a[i] + 1
  EndFor
EndFor
' Print "opened" doors
For i = 1 To 100
  If math.Remainder(a[i], 2) = 1 Then
    TextWindow.WriteLine(i)
  EndIf
EndFor


d = {}
for p in range(1, 100)
    for t in range(p, 100, p)
        if d.hasIndex(t) then d.remove t else d.push t
    end for
end for

print d.indexes.sort


.data
  doors:     .space 100
  num_str:   .asciiz "Number "
  comma_gap: .asciiz " is "
  newline:   .asciiz "\n"

.text
main:
# Clear all the cells to zero
  li $t1, 100
  la $t2, doors
clear_loop:
  sb $0, ($t2)
  add $t2, $t2, 1
  sub $t1, $t1, 1
  bnez $t1, clear_loop

# Now start the loops
  li $t0, 1         # This will the the step size
  li $t4, 1         # just an arbitrary 1
loop1:
  move $t1, $t0      # Counter
  la $t2, doors      # Current pointer
  add $t2, $t2, $t0
  addi $t2, $t2, -1
loop2:
  lb $t3, ($t2)
  sub $t3, $t4, $t3
  sb $t3, ($t2)
  add $t1, $t1, $t0
  add $t2, $t2, $t0
  ble $t1, 100, loop2

  addi $t0, $t0, 1
  ble $t0, 100, loop1

  # Now display everything
  la $t0, doors
  li $t1, 1
loop3:
  li $v0, 4
  la $a0, num_str
  syscall

  li $v0, 1
  move $a0, $t1
  syscall

  li $v0, 4
  la $a0, comma_gap
  syscall

  li $v0, 1
  lb $a0, ($t0)
  syscall

  li $v0, 4,
  la $a0, newline
  syscall

  addi $t0, $t0, 1
  addi $t1, $t1, 1
  bne $t1, 101 loop3


T Zeckendorf
   Int dLen
   dVal = 0

   F (x = ‘0’)
      V q = 1
      V i = x.len - 1
      .dLen = i I/ 2
      L i >= 0
         .dVal = .dVal + (x[i].code - ‘0’.code) * q
         q = q * 2
         i = i - 1

   F a(n)
      V i = n
      L
         I .dLen < i
            .dLen = i
         V j = (.dVal >> (i * 2)) [&] 3
         I j == 0 | j == 1
            R
         I j == 2
            I (.dVal >> ((i + 1) * 2) [&] 1) != 1
               R
            .dVal = .dVal + (1 << (i * 2 + 1))
            R
         I j == 3
            V temp = 3 << (i * 2)
            temp = temp (+) -1
            .dVal = .dVal [&] temp
            .b((i + 1) * 2)
         i = i + 1

   F b(pos)
      I pos == 0
         .inc()
         R
      I (.dVal >> pos) [&] 1 == 0
         .dVal = .dVal + (1 << pos)
         .a(Int(pos / 2))
         I pos > 1
            .a(Int(pos / 2) - 1)
      E
         V temp = 1 << pos
         temp = temp (+) -1
         .dVal = .dVal [&] temp
         .b(pos + 1)
         .b(pos - (I pos > 1 {2} E 1))

   F c(pos)
      I (.dVal >> pos) [&] 1 == 1
         V temp = 1 << pos
         temp = temp (+) -1
         .dVal = .dVal [&] temp
         R
      .c(pos + 1)
      I pos > 0
         .b(pos - 1)
      E
         .inc()

   F inc() -> N
      .dVal = .dVal + 1
      .a(0)

   F +(rhs)
      V copy = (.)
      V rhs_dVal = rhs.dVal
      V limit = (rhs.dLen + 1) * 2
      L(gn) 0 .< limit
         I ((rhs_dVal >> gn) [&] 1) == 1
            copy.b(gn)
      R copy

   F -(rhs)
      V copy = (.)
      V rhs_dVal = rhs.dVal
      V limit = (rhs.dLen + 1) * 2
      L(gn) 0 .< limit
         I (rhs_dVal >> gn) [&] 1 == 1
            copy.c(gn)
      L (((copy.dVal >> ((copy.dLen * 2) [&] 31)) [&] 3) == 0) | (copy.dLen == 0)
         copy.dLen = copy.dLen - 1
      R copy

   F *(rhs)
      V na = copy(rhs)
      V nb = copy(rhs)
      V nr = Zeckendorf()
      V dVal = .dVal
      L(i) 0 .< (.dLen + 1) * 2
         I ((dVal >> i) [&] 1) > 0
            nr = nr + nb
         V nt = copy(nb)
         nb = nb + na
         na = copy(nt)
      R nr

   F String()
      V dig = [‘00’, ‘01’, ‘10’]
      V dig1 = [‘’, ‘1’, ‘10’]

      I .dVal == 0
         R ‘0’
      V idx = (.dVal >> ((.dLen * 2) [&] 31)) [&] 3
      String sb = dig1[idx]
      V i = .dLen - 1
      L i >= 0
         idx = (.dVal >> (i * 2)) [&] 3
         sb ‘’= dig[idx]
         i = i - 1
      R sb

print(‘Addition:’)
V g = Zeckendorf(‘10’)
g = g + Zeckendorf(‘10’)
print(g)
g = g + Zeckendorf(‘10’)
print(g)
g = g + Zeckendorf(‘1001’)
print(g)
g = g + Zeckendorf(‘1000’)
print(g)
g = g + Zeckendorf(‘10101’)
print(g)
print()

print(‘Subtraction:’)
g = Zeckendorf(‘1000’)
g = g - Zeckendorf(‘101’)
print(g)
g = Zeckendorf(‘10101010’)
g = g - Zeckendorf(‘1010101’)
print(g)
print()

print(‘Multiplication:’)
g = Zeckendorf(‘1001’)
g = g * Zeckendorf(‘101’)
print(g)
g = Zeckendorf(‘101010’)
g = g + Zeckendorf(‘101’)
print(g)


import java.util.ArrayList

class Door
	:state

	def initialize
		@state=false
	end

	def closed?; [email protected]; end
	def open?; @state; end

	def close; @state=false; end
	def open; @state=true; end

	def toggle
		if closed?
			open
		else
			close
		end
	end

	def toString; Boolean.toString(@state); end
end

doors=ArrayList.new
1.upto(100) do
    doors.add(Door.new)
end

1.upto(100) do |multiplier|
    index = 0
    doors.each do |door|
        Door(door).toggle if (index+1)%multiplier == 0
        index += 1
    end
end

i = 0
doors.each do |door|
    puts "Door #{i+1} is #{door}."
    i+=1
end


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

int inv(int a) {
    return a ^ -1;
}

struct Zeckendorf {
    int dVal, dLen;
};

void a(struct Zeckendorf *self, int n) {
    void b(struct Zeckendorf *, int); // forward declare

    int i = n;
    while (true) {
        if (self->dLen < i) self->dLen = i;
        int j = (self->dVal >> (i * 2)) & 3;
        switch (j) {
        case 0:
        case 1:
            return;
        case 2:
            if (((self->dVal >> ((i + 1) * 2)) & 1) != 1) return;
            self->dVal += 1 << (i * 2 + 1);
            return;
        case 3:
            self->dVal = self->dVal & inv(3 << (i * 2));
            b(self, (i + 1) * 2);
            break;
        default:
            break;
        }
        i++;
    }
}

void b(struct Zeckendorf *self, int pos) {
    void increment(struct Zeckendorf *); // forward declare

    if (pos == 0) {
        increment(self);
        return;
    }
    if (((self->dVal >> pos) & 1) == 0) {
        self->dVal += 1 << pos;
        a(self, pos / 2);
        if (pos > 1) a(self, pos / 2 - 1);
    } else {
        self->dVal = self->dVal & inv(1 << pos);
        b(self, pos + 1);
        b(self, pos - (pos > 1 ? 2 : 1));
    }
}

void c(struct Zeckendorf *self, int pos) {
    if (((self->dVal >> pos) & 1) == 1) {
        self->dVal = self->dVal & inv(1 << pos);
        return;
    }
    c(self, pos + 1);
    if (pos > 0) {
        b(self, pos - 1);
    } else {
        increment(self);
    }
}

struct Zeckendorf makeZeckendorf(char *x) {
    struct Zeckendorf z = { 0, 0 };
    int i = strlen(x) - 1;
    int q = 1;

    z.dLen = i / 2;
    while (i >= 0) {
        z.dVal += (x[i] - '0') * q;
        q *= 2;
        i--;
    }

    return z;
}

void increment(struct Zeckendorf *self) {
    self->dVal++;
    a(self, 0);
}

void addAssign(struct Zeckendorf *self, struct Zeckendorf rhs) {
    int gn;
    for (gn = 0; gn < (rhs.dLen + 1) * 2; gn++) {
        if (((rhs.dVal >> gn) & 1) == 1) {
            b(self, gn);
        }
    }
}

void subAssign(struct Zeckendorf *self, struct Zeckendorf rhs) {
    int gn;
    for (gn = 0; gn < (rhs.dLen + 1) * 2; gn++) {
        if (((rhs.dVal >> gn) & 1) == 1) {
            c(self, gn);
        }
    }
    while ((((self->dVal >> self->dLen * 2) & 3) == 0) || (self->dLen == 0)) {
        self->dLen--;
    }
}

void mulAssign(struct Zeckendorf *self, struct Zeckendorf rhs) {
    struct Zeckendorf na = rhs;
    struct Zeckendorf nb = rhs;
    struct Zeckendorf nr = makeZeckendorf("0");
    struct Zeckendorf nt;
    int i;

    for (i = 0; i < (self->dLen + 1) * 2; i++) {
        if (((self->dVal >> i) & 1) > 0) addAssign(&nr, nb);
        nt = nb;
        addAssign(&nb, na);
        na = nt;
    }

    *self = nr;
}

void printZeckendorf(struct Zeckendorf z) {
    static const char *const dig[3] = { "00", "01", "10" };
    static const char *const dig1[3] = { "", "1", "10" };

    if (z.dVal == 0) {
        printf("0");
        return;
    } else {
        int idx = (z.dVal >> (z.dLen * 2)) & 3;
        int i;

        printf(dig1[idx]);
        for (i = z.dLen - 1; i >= 0; i--) {
            idx = (z.dVal >> (i * 2)) & 3;
            printf(dig[idx]);
        }
    }
}

int main() {
    struct Zeckendorf g;

    printf("Addition:\n");
    g = makeZeckendorf("10");
    addAssign(&g, makeZeckendorf("10"));
    printZeckendorf(g);
    printf("\n");
    addAssign(&g, makeZeckendorf("10"));
    printZeckendorf(g);
    printf("\n");
    addAssign(&g, makeZeckendorf("1001"));
    printZeckendorf(g);
    printf("\n");
    addAssign(&g, makeZeckendorf("1000"));
    printZeckendorf(g);
    printf("\n");
    addAssign(&g, makeZeckendorf("10101"));
    printZeckendorf(g);
    printf("\n\n");

    printf("Subtraction:\n");
    g = makeZeckendorf("1000");
    subAssign(&g, makeZeckendorf("101"));
    printZeckendorf(g);
    printf("\n");
    g = makeZeckendorf("10101010");
    subAssign(&g, makeZeckendorf("1010101"));
    printZeckendorf(g);
    printf("\n\n");

    printf("Multiplication:\n");
    g = makeZeckendorf("1001");
    mulAssign(&g, makeZeckendorf("101"));
    printZeckendorf(g);
    printf("\n");
    g = makeZeckendorf("101010");
    addAssign(&g, makeZeckendorf("101"));
    printZeckendorf(g);
    printf("\n");

    return 0;
}


var %d = $str(0 $+ $chr(32),100), %m = 1
while (%m <= 100) {
  var %n = 1
  while ($calc(%n * %m) <= 100) {
    var %d = $puttok(%d,$iif($gettok(%d,$calc(%n * %m),32),0,1),$calc(%n * %m),32)
    inc %n
  }
  inc %m
}
echo -ag All Doors (Boolean): %d
var %n = 1
while (%n <= $findtok(%d,1,0,32)) {
  var %t = %t $findtok(%d,1,%n,32)
  inc %n
}
echo -ag Open Door Numbers: %t


using System;
using System.Text;

namespace ZeckendorfArithmetic {
    class Zeckendorf : IComparable<Zeckendorf> {
        private static readonly string[] dig = { "00", "01", "10" };
        private static readonly string[] dig1 = { "", "1", "10" };

        private int dVal = 0;
        private int dLen = 0;

        public Zeckendorf() : this("0") {
            // empty
        }

        public Zeckendorf(string x) {
            int q = 1;
            int i = x.Length - 1;
            dLen = i / 2;
            while (i >= 0) {
                dVal += (x[i] - '0') * q;
                q *= 2;
                i--;
            }
        }

        private void A(int n) {
            int i = n;
            while (true) {
                if (dLen < i) dLen = i;
                int j = (dVal >> (i * 2)) & 3;
                switch (j) {
                    case 0:
                    case 1:
                        return;
                    case 2:
                        if (((dVal >> ((i + 1) * 2)) & 1) != 1) return;
                        dVal += 1 << (i * 2 + 1);
                        return;
                    case 3:
                        int temp = 3 << (i * 2);
                        temp ^= -1;
                        dVal = dVal & temp;
                        B((i + 1) * 2);
                        break;
                }
                i++;
            }
        }

        private void B(int pos) {
            if (pos == 0) {
                Inc();
                return;
            }
            if (((dVal >> pos) & 1) == 0) {
                dVal += 1 << pos;
                A(pos / 2);
                if (pos > 1) A(pos / 2 - 1);
            }
            else {
                int temp = 1 << pos;
                temp ^= -1;
                dVal = dVal & temp;
                B(pos + 1);
                B(pos - (pos > 1 ? 2 : 1));
            }
        }

        private void C(int pos) {
            if (((dVal >> pos) & 1) == 1) {
                int temp = 1 << pos;
                temp ^= -1;
                dVal = dVal & temp;
                return;
            }
            C(pos + 1);
            if (pos > 0) {
                B(pos - 1);
            }
            else {
                Inc();
            }
        }

        public Zeckendorf Inc() {
            dVal++;
            A(0);
            return this;
        }

        public Zeckendorf Copy() {
            Zeckendorf z = new Zeckendorf {
                dVal = dVal,
                dLen = dLen
            };
            return z;
        }

        public void PlusAssign(Zeckendorf other) {
            for (int gn = 0; gn < (other.dLen + 1) * 2; gn++) {
                if (((other.dVal >> gn) & 1) == 1) {
                    B(gn);
                }
            }
        }

        public void MinusAssign(Zeckendorf other) {
            for (int gn = 0; gn < (other.dLen + 1) * 2; gn++) {
                if (((other.dVal >> gn) & 1) == 1) {
                    C(gn);
                }
            }
            while ((((dVal >> dLen * 2) & 3) == 0) || (dLen == 0)) {
                dLen--;
            }
        }

        public void TimesAssign(Zeckendorf other) {
            Zeckendorf na = other.Copy();
            Zeckendorf nb = other.Copy();
            Zeckendorf nt;
            Zeckendorf nr = new Zeckendorf();
            for (int i = 0; i < (dLen + 1) * 2; i++) {
                if (((dVal >> i) & 1) > 0) {
                    nr.PlusAssign(nb);
                }
                nt = nb.Copy();
                nb.PlusAssign(na);
                na = nt.Copy();
            }
            dVal = nr.dVal;
            dLen = nr.dLen;
        }

        public int CompareTo(Zeckendorf other) {
            return dVal.CompareTo(other.dVal);
        }

        public override string ToString() {
            if (dVal == 0) {
                return "0";
            }

            int idx = (dVal >> (dLen * 2)) & 3;
            StringBuilder sb = new StringBuilder(dig1[idx]);
            for (int i = dLen - 1; i >= 0; i--) {
                idx = (dVal >> (i * 2)) & 3;
                sb.Append(dig[idx]);
            }
            return sb.ToString();
        }
    }

    class Program {
        static void Main(string[] args) {
            Console.WriteLine("Addition:");
            Zeckendorf g = new Zeckendorf("10");
            g.PlusAssign(new Zeckendorf("10"));
            Console.WriteLine(g);
            g.PlusAssign(new Zeckendorf("10"));
            Console.WriteLine(g);
            g.PlusAssign(new Zeckendorf("1001"));
            Console.WriteLine(g);
            g.PlusAssign(new Zeckendorf("1000"));
            Console.WriteLine(g);
            g.PlusAssign(new Zeckendorf("10101"));
            Console.WriteLine(g);
            Console.WriteLine();

            Console.WriteLine("Subtraction:");
            g = new Zeckendorf("1000");
            g.MinusAssign(new Zeckendorf("101"));
            Console.WriteLine(g);
            g = new Zeckendorf("10101010");
            g.MinusAssign(new Zeckendorf("1010101"));
            Console.WriteLine(g);
            Console.WriteLine();

            Console.WriteLine("Multiplication:");
            g = new Zeckendorf("1001");
            g.TimesAssign(new Zeckendorf("101"));
            Console.WriteLine(g);
            g = new Zeckendorf("101010");
            g.PlusAssign(new Zeckendorf("101"));
            Console.WriteLine(g);
        }
    }
}


MCSKIP "WITH" NL
"" 100 doors
MCINS %.
MCSKIP MT,<>
"" Doors represented by P1-P100, 0 is closed
MCPVAR 100
"" Set P variables to 0
MCDEF ZEROPS WITHS NL AS <MCSET T1=1
%L1.MCSET PT1=0
MCSET T1=T1+1
MCGO L1 UNLESS T1 EN 101
>
ZEROPS
"" Generate door state
MCDEF STATE WITHS () AS <MCSET T1=%A1.
MCGO L1 UNLESS T1 EN 0
closed<>MCGO L0
%L1.open>
"" Main macro - no arguments
"" T1 is pass number
"" T2 is door number
MCDEF DOORS WITHS NL
AS <MCSET T1=1
"" pass loop
%L1.MCGO L4 IF T1 GR 100
"" door loop
MCSET T2=T1
%L2.MCGO L3 IF T2 GR 100
MCSET PT2=1-PT2
MCSET T2=T2+T1
MCGO L2
%L3.MCSET T1=T1+1
MCGO L1
%L4."" now output the result
MCSET T1=1
%L5.door %T1. is STATE(%PT1.)
MCSET T1=T1+1
MCGO L5 UNLESS T1 GR 100
>
"" Do it
DOORS


MODULE Doors;
IMPORT InOut;

TYPE State = (Closed, Open);
TYPE List = ARRAY [1 .. 100] OF State;

VAR
  Doors: List;
  I, J:  CARDINAL;

BEGIN
  FOR I := 1 TO 100 DO
    FOR J := 1 TO 100 DO
      IF J MOD I = 0 THEN
        IF Doors[J] = Closed THEN
          Doors[J] := Open
        ELSE
          Doors[J] := Closed
        END
      END
    END
  END;

  FOR I := 1 TO 100 DO
    InOut.WriteCard(I, 3);
    InOut.WriteString(' is ');

    IF Doors[I] = Closed THEN
      InOut.WriteString('Closed.')
    ELSE
      InOut.WriteString('Open.')
    END;

    InOut.WriteLn
  END
END Doors.


// For a class N which implements Zeckendorf numbers:
// I define an increment operation ++()
// I define a comparison operation <=(other N)
// I define an addition operation +=(other N)
// I define a subtraction operation -=(other N)
// Nigel Galloway October 28th., 2012
#include <iostream>
enum class zd {N00,N01,N10,N11};
class N {
private:
  int dVal = 0, dLen;
  void _a(int i) {
    for (;; i++) {
      if (dLen < i) dLen = i;
      switch ((zd)((dVal >> (i*2)) & 3)) {
        case zd::N00: case zd::N01: return;
        case zd::N10: if (((dVal >> ((i+1)*2)) & 1) != 1) return;
                      dVal += (1 << (i*2+1)); return;
        case zd::N11: dVal &= ~(3 << (i*2)); _b((i+1)*2);
  }}}
  void _b(int pos) {
    if (pos == 0) {++*this; return;}
    if (((dVal >> pos) & 1) == 0) {
      dVal += 1 << pos;
      _a(pos/2);
      if (pos > 1) _a((pos/2)-1);
      } else {
      dVal &= ~(1 << pos);
      _b(pos + 1);
      _b(pos - ((pos > 1)? 2:1));
  }}
  void _c(int pos) {
    if (((dVal >> pos) & 1) == 1) {dVal &= ~(1 << pos); return;}
    _c(pos + 1);
    if (pos > 0) _b(pos - 1); else ++*this;
    return;
  }
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++() {dVal += 1; _a(0); return *this;}
  const N& operator+=(const N& other) {
    for (int GN = 0; GN < (other.dLen + 1) * 2; GN++) if ((other.dVal >> GN) & 1 == 1) _b(GN);
    return *this;
  }
  const N& operator-=(const N& other) {
    for (int GN = 0; GN < (other.dLen + 1) * 2; GN++) if ((other.dVal >> GN) & 1 == 1) _c(GN);
    for (;((dVal >> dLen*2) & 3) == 0 or dLen == 0; dLen--);
    return *this;
  }
  const N& operator*=(const N& other) {
    N Na = other, Nb = other, Nt, Nr;
    for (int i = 0; i <= (dLen + 1) * 2; i++) {
      if (((dVal >> i) & 1) > 0) Nr += Nb;
      Nt = Nb; Nb += Na; Na = Nt;
    }
    return *this = Nr;
  }
  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;
}


import std.stdio;

int inv(int a) {
    return a ^ -1;
}

class Zeckendorf {
    private int dVal;
    private int dLen;

    private void a(int n) {
        auto i = n;
        while (true) {
            if (dLen < i) dLen = i;
            auto j = (dVal >> (i * 2)) & 3;
            switch(j) {
                case 0:
                case 1:
                    return;
                case 2:
                    if (((dVal >> ((i + 1) * 2)) & 1) != 1) return;
                    dVal += 1 << (i * 2 + 1);
                    return;
                case 3:
                    dVal = dVal & (3 << (i * 2)).inv();
                    b((i + 1) * 2);
                    break;
                default:
                    assert(false);
            }
            i++;
        }
    }

    private void b(int pos) {
        if (pos == 0) {
            this++;
            return;
        }
        if (((dVal >> pos) & 1) == 0) {
            dVal += 1 << pos;
            a(pos / 2);
            if (pos > 1) a(pos / 2 - 1);
        } else {
            dVal = dVal & (1 << pos).inv();
            b(pos + 1);
            b(pos - (pos > 1 ? 2 : 1));
        }
    }

    private void c(int pos) {
        if (((dVal >> pos) & 1) == 1) {
            dVal = dVal & (1 << pos).inv();
            return;
        }
        c(pos + 1);
        if (pos > 0) {
            b(pos - 1);
        } else {
            ++this;
        }
    }

    this(string x = "0") {
        int q = 1;
        int i = x.length - 1;
        dLen = i / 2;
        while (i >= 0) {
            dVal += (x[i] - '0') * q;
            q *= 2;
            i--;
        }
    }

    auto opUnary(string op : "++")() {
        dVal += 1;
        a(0);
        return this;
    }

    void opOpAssign(string op : "+")(Zeckendorf rhs) {
        foreach (gn; 0..(rhs.dLen + 1) * 2) {
            if (((rhs.dVal >> gn) & 1) == 1) {
                b(gn);
            }
        }
    }

    void opOpAssign(string op : "-")(Zeckendorf rhs) {
        foreach (gn; 0..(rhs.dLen + 1) * 2) {
            if (((rhs.dVal >> gn) & 1) == 1) {
                c(gn);
            }
        }
        while ((((dVal >> dLen * 2) & 3) == 0) || (dLen == 0)) {
            dLen--;
        }
    }

    void opOpAssign(string op : "*")(Zeckendorf rhs) {
        auto na = rhs.dup;
        auto nb = rhs.dup;
        Zeckendorf nt;
        auto nr = "0".Z;
        foreach (i; 0..(dLen + 1) * 2) {
            if (((dVal >> i) & 1) > 0) nr += nb;
            nt = nb.dup;
            nb += na;
            na = nt.dup;
        }
        dVal = nr.dVal;
        dLen = nr.dLen;
    }

    void toString(scope void delegate(const(char)[]) sink) const {
        if (dVal == 0) {
            sink("0");
            return;
        }
        sink(dig1[(dVal >> (dLen * 2)) & 3]);
        foreach_reverse (i; 0..dLen) {
            sink(dig[(dVal >> (i * 2)) & 3]);
        }
    }

    Zeckendorf dup() {
        auto z = "0".Z;
        z.dVal = dVal;
        z.dLen = dLen;
        return z;
    }

    enum dig = ["00", "01", "10"];
    enum dig1 = ["", "1", "10"];
}

auto Z(string val) {
    return new Zeckendorf(val);
}

void main() {
    writeln("Addition:");
    auto g = "10".Z;
    g += "10".Z;
    writeln(g);
    g += "10".Z;
    writeln(g);
    g += "1001".Z;
    writeln(g);
    g += "1000".Z;
    writeln(g);
    g += "10101".Z;
    writeln(g);
    writeln();

    writeln("Subtraction:");
    g = "1000".Z;
    g -= "101".Z;
    writeln(g);
    g = "10101010".Z;
    g -= "1010101".Z;
    writeln(g);
    writeln();

    writeln("Multiplication:");
    g = "1001".Z;
    g *= "101".Z;
    writeln(g);
    g = "101010".Z;
    g += "101".Z;
    writeln(g);
}


MODULE Doors EXPORTS Main;

IMPORT IO, Fmt;

TYPE State = {Closed, Open};
TYPE List = ARRAY [1..100] OF State;

VAR doors := List{State.Closed, ..};

BEGIN
  FOR i := 1 TO 100 DO
    FOR j := FIRST(doors) TO LAST(doors) DO
      IF j MOD i = 0 THEN
        IF doors[j] = State.Closed THEN
          doors[j] := State.Open;
        ELSE
          doors[j] := State.Closed;
        END;
      END;
    END;
  END;

  FOR i := FIRST(doors) TO LAST(doors) DO
    IO.Put(Fmt.Int(i) & " is ");
    IF doors[i] = State.Closed THEN
      IO.Put("Closed.\n");
    ELSE
      IO.Put("Open.\n");
    END;
  END;
END Doors.


import extensions;

const dig = new string[]{"00","01","10"};
const dig1 = new string[]{"","1","10"};

sealed struct ZeckendorfNumber
{
    int dVal;
    int dLen;

    clone()
        = ZeckendorfNumber.newInternal(dVal,dLen);

    cast n(string s)
    {
        int i := s.Length - 1;
        int q := 1;

        dLen := i / 2;
        dVal := 0;

        while (i >= 0)
        {
            dVal += ((intConvertor.convert(s[i]) - 48) * q);
            q *= 2;

            i -= 1
        }
    }

    internal readContent(ref int val, ref int len)
    {
        val := dVal;
        len := dLen;
    }

    private a(int n)
    {
        int i := n;

        while (true)
        {
            if (dLen < i)
            {
                dLen := i
            };

            int v := (dVal $shr (i * 2)) && 3;
            v =>
                0 { ^ self }
                1 { ^ self }
                2 {
                    ifnot ((dVal $shr ((i + 1) * 2)).allMask:1)
                    {
                        ^ self
                    };

                    dVal += (1 $shl (i*2 + 1));

                    ^ self
                }
                3 {
                    int tmp := 3 $shl (i * 2);
                    tmp := tmp.xor(-1);
                    dVal := dVal && tmp;

                    self.b((i+1)*2)
                };

            i += 1
        }
    }

    inc()
    {
        dVal += 1;
        self.a(0)
    }

    private b(int pos)
    {
        if (pos == 0) { ^ self.inc() };

        ifnot((dVal $shr pos).allMask:1)
        {
            dVal += (1 $shl pos);
            self.a(pos / 2);
            if (pos > 1) { self.a((pos / 2) - 1) }
        }
        else
        {
            dVal := dVal && (1 $shl pos).Inverted;
            self.b(pos + 1);
            int arg := pos - ((pos > 1) ? 2 : 1);
            self.b(/*pos - ((pos > 1) ? 2 : 1)*/arg)
        }
    }

    private c(int pos)
    {
        if ((dVal $shr pos).allMask:1)
        {
            int tmp := 1 $shl pos;
            tmp := tmp.xor(-1);

            dVal := dVal && tmp;

            ^ self
        };

        self.c(pos + 1);

        if (pos > 0)
        {
            self.b(pos - 1)
        }
        else
        {
            self.inc()
        }
    }

    internal constructor sum(ZeckendorfNumber n, ZeckendorfNumber m)
    {
        int mVal := 0;
        int mLen := 0;

        n.readContent(ref dVal, ref dLen);
        m.readContent(ref mVal, ref mLen);

        for(int GN := 0, GN < (mLen + 1) * 2, GN += 1)
        {
            if ((mVal $shr GN).allMask:1)
            {
                self.b(GN)
            }
        }
    }

    internal constructor difference(ZeckendorfNumber n, ZeckendorfNumber m)
    {
        int mVal := 0;
        int mLen := 0;

        n.readContent(ref dVal, ref dLen);
        m.readContent(ref mVal, ref mLen);

        for(int GN := 0, GN < (mLen + 1) * 2, GN += 1)
        {
            if ((mVal $shr GN).allMask:1)
            {
                self.c(GN)
            }
        };

        while (((dVal $shr (dLen*2)) && 3) == 0 || dLen == 0)
        {
            dLen -= 1
        }
    }

    internal constructor product(ZeckendorfNumber n, ZeckendorfNumber m)
    {
        n.readContent(ref dVal, ref dLen);

        ZeckendorfNumber Na := m;
        ZeckendorfNumber Nb := m;
        ZeckendorfNumber Nr := 0n;
        ZeckendorfNumber Nt := 0n;

        for(int i := 0, i < (dLen + 1) * 2, i += 1)
        {
            if (((dVal $shr i) && 1) > 0)
            {
                Nr += Nb
            };
            Nt := Nb;
            Nb += Na;
            Na := Nt
        };

        Nr.readContent(ref dVal, ref dLen);
    }

    internal constructor newInternal(int v, int l)
    {
        dVal := v;
        dLen := l
    }

    string toPrintable()
    {
        if (dVal == 0)
            { ^ "0" };

        string s := dig1[(dVal $shr (dLen * 2)) && 3];
        int i := dLen - 1;
        while (i >= 0)
        {
            s := s + dig[(dVal $shr (i * 2)) && 3];

            i-=1
        };

        ^ s
    }

    add(ZeckendorfNumber n)
        = ZeckendorfNumber.sum(self, n);

    subtract(ZeckendorfNumber n)
        = ZeckendorfNumber.difference(self, n);

    multiply(ZeckendorfNumber n)
        = ZeckendorfNumber.product(self, n);
}

public program()
{
    console.printLine("Addition:");
    var n := 10n;

    n += 10n;
    console.printLine(n);
    n += 10n;
    console.printLine(n);
    n += 1001n;
    console.printLine(n);
    n += 1000n;
    console.printLine(n);
    n += 10101n;
    console.printLine(n);

    console.printLine("Subtraction:");
    n := 1000n;
    n -= 101n;
    console.printLine(n);
    n := 10101010n;
    n -= 1010101n;
    console.printLine(n);

    console.printLine("Multiplication:");
    n := 1001n;
    n *= 101n;
    console.printLine(n);
    n := 101010n;
    n += 101n;
    console.printLine(n)
}


package main

import (
    "fmt"
    "strings"
)

var (
    dig  = [3]string{"00", "01", "10"}
    dig1 = [3]string{"", "1", "10"}
)

type Zeckendorf struct{ dVal, dLen int }

func NewZeck(x string) *Zeckendorf {
    z := new(Zeckendorf)
    if x == "" {
        x = "0"
    }
    q := 1
    i := len(x) - 1
    z.dLen = i / 2
    for ; i >= 0; i-- {
        z.dVal += int(x[i]-'0') * q
        q *= 2
    }
    return z
}

func (z *Zeckendorf) a(i int) {
    for ; ; i++ {
        if z.dLen < i {
            z.dLen = i
        }
        j := (z.dVal >> uint(i*2)) & 3
        switch j {
        case 0, 1:
            return
        case 2:
            if ((z.dVal >> (uint(i+1) * 2)) & 1) != 1 {
                return
            }
            z.dVal += 1 << uint(i*2+1)
            return
        case 3:
            z.dVal &= ^(3 << uint(i*2))
            z.b((i + 1) * 2)
        }
    }
}

func (z *Zeckendorf) b(pos int) {
    if pos == 0 {
        z.Inc()
        return
    }
    if ((z.dVal >> uint(pos)) & 1) == 0 {
        z.dVal += 1 << uint(pos)
        z.a(pos / 2)
        if pos > 1 {
            z.a(pos/2 - 1)
        }
    } else {
        z.dVal &= ^(1 << uint(pos))
        z.b(pos + 1)
        temp := 1
        if pos > 1 {
            temp = 2
        }
        z.b(pos - temp)
    }
}

func (z *Zeckendorf) c(pos int) {
    if ((z.dVal >> uint(pos)) & 1) == 1 {
        z.dVal &= ^(1 << uint(pos))
        return
    }
    z.c(pos + 1)
    if pos > 0 {
        z.b(pos - 1)
    } else {
        z.Inc()
    }
}

func (z *Zeckendorf) Inc() {
    z.dVal++
    z.a(0)
}

func (z1 *Zeckendorf) PlusAssign(z2 *Zeckendorf) {
    for gn := 0; gn < (z2.dLen+1)*2; gn++ {
        if ((z2.dVal >> uint(gn)) & 1) == 1 {
            z1.b(gn)
        }
    }
}

func (z1 *Zeckendorf) MinusAssign(z2 *Zeckendorf) {
    for gn := 0; gn < (z2.dLen+1)*2; gn++ {
        if ((z2.dVal >> uint(gn)) & 1) == 1 {
            z1.c(gn)
        }
    }

    for z1.dLen > 0 && ((z1.dVal>>uint(z1.dLen*2))&3) == 0 {
        z1.dLen--
    }
}

func (z1 *Zeckendorf) TimesAssign(z2 *Zeckendorf) {
    na := z2.Copy()
    nb := z2.Copy()
    nr := new(Zeckendorf)
    for i := 0; i <= (z1.dLen+1)*2; i++ {
        if ((z1.dVal >> uint(i)) & 1) > 0 {
            nr.PlusAssign(nb)
        }
        nt := nb.Copy()
        nb.PlusAssign(na)
        na = nt.Copy()
    }
    z1.dVal = nr.dVal
    z1.dLen = nr.dLen
}

func (z *Zeckendorf) Copy() *Zeckendorf {
    return &Zeckendorf{z.dVal, z.dLen}
}

func (z1 *Zeckendorf) Compare(z2 *Zeckendorf) int {
    switch {
    case z1.dVal < z2.dVal:
        return -1
    case z1.dVal > z2.dVal:
        return 1
    default:
        return 0
    }
}

func (z *Zeckendorf) String() string {
    if z.dVal == 0 {
        return "0"
    }
    var sb strings.Builder
    sb.WriteString(dig1[(z.dVal>>uint(z.dLen*2))&3])
    for i := z.dLen - 1; i >= 0; i-- {
        sb.WriteString(dig[(z.dVal>>uint(i*2))&3])
    }
    return sb.String()
}

func main() {
    fmt.Println("Addition:")
    g := NewZeck("10")
    g.PlusAssign(NewZeck("10"))
    fmt.Println(g)
    g.PlusAssign(NewZeck("10"))
    fmt.Println(g)
    g.PlusAssign(NewZeck("1001"))
    fmt.Println(g)
    g.PlusAssign(NewZeck("1000"))
    fmt.Println(g)
    g.PlusAssign(NewZeck("10101"))
    fmt.Println(g)

    fmt.Println("\nSubtraction:")
    g = NewZeck("1000")
    g.MinusAssign(NewZeck("101"))
    fmt.Println(g)
    g = NewZeck("10101010")
    g.MinusAssign(NewZeck("1010101"))
    fmt.Println(g)

    fmt.Println("\nMultiplication:")
    g = NewZeck("1001")
    g.TimesAssign(NewZeck("101"))
    fmt.Println(g)
    g = NewZeck("101010")
    g.PlusAssign(NewZeck("101"))
    fmt.Println(g)
}


101 var l .

for l 0 endfor
arr

0 var i .
for l
    i 1 + var i var j .
    j l < var pass .
    while pass
        get j not insert j .
        j i + var j
        l < var pass .
    endwhile
endfor
print /# show all doors #/

/# show only open doors #/
|| print .
0 var i .
for l
    get i
    if : i out | | out . . endif .
    i 1 + var i .
endfor

input . /# pause until ENTER key pressed #/


{-# LANGUAGE LambdaCase #-}
import Data.List (find, mapAccumL)
import Control.Arrow (first, second)

-- Generalized Fibonacci series defined for any Num instance, and for Zeckendorf numbers as well.
-- Used to build Zeckendorf tables.
fibs :: Num a => a -> a -> [a]
fibs a b = res
  where
    res = a : b : zipWith (+) res (tail res)

data Fib = Fib { sign :: Int, digits :: [Int]}

-- smart constructor
mkFib s ds =
  case dropWhile (==0) ds of
    [] -> 0
    ds -> Fib s (reverse ds)

-- Textual representation
instance Show Fib where
  show (Fib s ds) = sig s ++ foldMap show (reverse ds)
    where sig = \case { -1 -> "-"; s -> "" }

-- Equivalence relation
instance Eq Fib where
  Fib sa a == Fib sb b = sa == sb && a == b

-- Order relation
instance Ord Fib where
  a `compare` b =
    sign a `compare` sign b <>
    case find (/= 0) $ alignWith (-) (digits a) (digits b) of
      Nothing -> EQ
      Just 1 -> if sign a > 0 then GT else LT
      Just (-1) -> if sign a > 0 then LT else GT

-- Arithmetic
instance Num Fib where
  negate (Fib s ds) = Fib (negate s) ds
  abs (Fib s ds) = Fib 1 ds
  signum (Fib s _) = fromIntegral s

  fromInteger n =
    case compare n 0 of
      LT -> negate $ fromInteger (- n)
      EQ -> Fib 0 [0]
      GT -> Fib 1 . reverse . fst $ divModFib n 1

  0 + a = a
  a + 0 = a
  a + b =
    case (sign a, sign b) of
      ( 1, 1) -> res
      (-1, 1) -> b - (-a)
      ( 1,-1) -> a - (-b)
      (-1,-1) -> - ((- a) + (- b))
    where
      res = mkFib 1 . process $ 0:0:c
      c = alignWith (+) (digits a) (digits b)
       -- use cellular automata
      process =
        runRight 3 r2 . runLeftR 3 r2 . runRightR 4 r1

  0 - a = -a
  a - 0 = a
  a - b =
    case (sign a, sign b) of
      ( 1, 1) -> res
      (-1, 1) -> - ((-a) + b)
      ( 1,-1) -> a + (-b)
      (-1,-1) -> - ((-a) - (-b))
    where
      res = case find (/= 0) c of
        Just 1  -> mkFib 1 . process $ c
        Just (-1) -> - (b - a)
        Nothing -> 0
      c = alignWith (-) (digits a) (digits b)
      -- use cellular automata
      process =
        runRight 3 r2 . runLeftR 3 r2 . runRightR 4 r1 . runRight 3 r3

  0 * a = 0
  a * 0 = 0
  1 * a = a
  a * 1 = a
  a * b =
    case (sign a, sign b) of
      (1, 1) -> res
      (-1, 1) -> - ((-a) * b)
      ( 1,-1) -> - (a * (-b))
      (-1,-1) -> ((-a) * (-b))
    where
      -- use Zeckendorf table
      table = fibs a (a + a)
      res = sum $ onlyOnes $ zip (digits b) table
      onlyOnes = map snd . filter ((==1) . fst)

-- Enumeration
instance Enum Fib where
  toEnum = fromInteger . fromIntegral
  fromEnum = fromIntegral . toInteger

instance Real Fib where
  toRational = fromInteger . toInteger

-- Integral division
instance Integral Fib where
  toInteger (Fib s ds) = signum (fromIntegral s) * res
    where
      res = sum (zipWith (*) (fibs 1 2) (fromIntegral <$> ds))

  quotRem 0 _ = (0, 0)
  quotRem a 0 = error "divide by zero"
  quotRem a b = case (sign a, sign b) of
      (1, 1) -> first (mkFib 1) $ divModFib a b
      (-1, 1) -> second negate . first negate $ quotRem (-a) b
      ( 1,-1) -> first negate $ quotRem a (-b)
      (-1,-1) -> second negate $ quotRem (-a) (-b)

------------------------------------------------------------
-- helper funtions

-- general division using Zeckendorf table
divModFib :: (Ord a, Num c, Num a) => a -> a -> ([c], a)
divModFib a b = (q, r)
  where
    (r, q) = mapAccumL f a $ reverse $ takeWhile (<= a) table
    table = fibs b (b+b)
    f n x = if  n < x then (n, 0) else (n - x, 1)

-- application of rewriting rules
-- runs window from left to right
runRight n f = go
  where
    go []  = []
    go lst = let (w, r) = splitAt n lst
                 (h: t) = f w
             in h : go (t ++ r)

-- runs window from left to right and reverses the result
runRightR n f = go []
  where
    go res []  = res
    go res lst = let (w, r) = splitAt n lst
                     (h: t) = f w
                 in go (h : res) (t ++ r)

-- runs reversed window and reverses the result
runLeftR n f = runRightR n (reverse . f . reverse)

-- rewriting rules from [C. Ahlbach et. all]
r1 = \case [0,3,0]   -> [1,1,1]
           [0,2,0]   -> [1,0,1]
           [0,1,2]   -> [1,0,1]
           [0,2,1]   -> [1,1,0]
           [x,0,2]   -> [x,1,0]
           [x,0,3]   -> [x,1,1]
           [0,1,2,0] -> [1,0,1,0]
           [0,2,0,x] -> [1,0,0,x+1]
           [0,3,0,x] -> [1,1,0,x+1]
           [0,2,1,x] -> [1,1,0,x  ]
           [0,1,2,x] -> [1,0,1,x  ]
           l -> l

r2 = \case [0,1,1] -> [1,0,0]
           l -> l

r3 = \case [1,-1]    -> [0,1]
           [2,-1]    -> [1,1]
           [1, 0, 0] -> [0,1,1]
           [1,-1, 0] -> [0,0,1]
           [1,-1, 1] -> [0,0,2]
           [1, 0,-1] -> [0,1,0]
           [2, 0, 0] -> [1,1,1]
           [2,-1, 0] -> [1,0,1]
           [2,-1, 1] -> [1,0,2]
           [2, 0,-1] -> [1,1,0]
           l -> l

alignWith :: (Int -> Int -> a) -> [Int] -> [Int] -> [a]
alignWith f a b = go [] a b
  where
    go res as [] = ((`f` 0) <$> reverse as) ++ res
    go res [] bs = ((0 `f`) <$> reverse bs) ++ res
    go res (a:as) (b:bs) = go (f a b : res) as bs


is_open = make(100);
for pass in [1..100]
  for door in [pass..100]
    if (door % pass)
      continue;
    endif
    is_open[door] = !is_open[door];
  endfor
endfor

"output the result";
for door in [1..100]
  player:tell("door #", door, " is ", (is_open[door] ? "open" : "closed"), ".");
endfor