begin % zig-zag matrix %
    % z is returned holding a zig-zag matrix of order n, z must be at least n x n %
    procedure makeZigZag ( integer value n
                         ; integer array z( *, * )
                         ) ;
    begin
        procedure move ;
        begin
            if   y = n then begin
                upRight := not upRight;
                x := x + 1
                end
            else if x = 1 then begin
                upRight := not upRight;
                y := y + 1
                end
            else begin
                x := x - 1;
                y := y + 1
            end
        end move ;
        procedure swapXY ;
        begin
            integer swap;
            swap := x;
            x    := y;
            y    := swap;
        end swapXY ;
        integer x, y;
        logical upRight;
        % initialise the n x n matrix in z %
        for i := 1 until n do for j := 1 until n do z( i, j ) := 0;
        % fill in the zig-zag matrix %
        x := y := 1;
        upRight := true;
        for i := 1 until n * n do begin
            z( x, y ) := i - 1;
            if upRight then move
            else begin
                swapXY;
                move;
                swapXY
            end;
        end;
    end makeZigZap ;

    begin
        integer array zigZag( 1 :: 10, 1 :: 10 );
        for n := 5 do begin
            makeZigZag( n, zigZag );
            for i := 1 until n do begin
                 write( i_w := 4, s_w := 1, zigZag( i, 1 ) );
                for j := 2 until n do writeon( i_w := 4, s_w := 1, zigZag( i, j ) );
            end
        end
    end

end.


      zz   ←  {⍵⍴⎕IO-⍨⍋⊃,/{(2|⍴⍵):⌽⍵⋄⍵}¨(⊂w)/¨⍨w{↓⍵∘.=⍨∪⍵}+/[1]⍵⊤w←⎕IO-⍨⍳×/⍵}   ⍝  General zigzag (any rectangle)
      zzSq ←  {zz,⍨⍵}                                                           ⍝  Square zigzag
      zzSq 5
 0  1  5  6 14
 2  4  7 13 15
 3  8 12 16 21
 9 11 17 20 22
10 18 19 23 24


$constant DOOR_OPEN = 1
$constant DOOR_CLOSED = 0
$constant MAX_DOORS = 100

var i, j = integer
dim integer doors(MAX_DOORS)

rem - all doors are initially closed
for i = 1 to MAX_DOORS
  doors(i) = DOOR_CLOSED
next i

rem - cycle through at increasing intervals and flip doors
for i = 1 to MAX_DOORS
  for j = i to MAX_DOORS step i
    doors(j) = 1 - doors(j)
  next j
next i

rem - report results
print "The open doors are:"
for i = 1 to MAX_DOORS
  if doors(i) = DOOR_OPEN then
     print i;
next i

end


variable door,
    isOpen = Char_Type [101],
    pass;

for (door = 1; door <= 100; door++) {
    isOpen[door] = 0;
}

for (pass = 1; pass <= 100; pass++) {
    for (door = pass; door <= 100; door += pass) {
        isOpen[door] = not isOpen[door];
    }
}

for (door = 1; door <= 100; door++) {
    if (isOpen[door]) {
        print("Door " + string(door) + ":open");
    } else {
        print("Door " + string(door) + ":close");
    }
}


set n to 5 -- Size of zig-zag matrix (n^2 cells).

-- Create an empty matrix.
set m to {}
repeat with i from 1 to n
	set R to {}
	repeat with j from 1 to n
		set end of R to 0
	end repeat
	set end of m to R
end repeat

-- Populate the matrix in a zig-zag manner.
set {x, y, v, d} to {1, 1, 0, 1}
repeat while v < (n ^ 2)
	if 1 ≤ x and x ≤ n and 1 ≤ y and y ≤ n then
		set {m's item y's item x, x, y, v} to {v, x + d, y - d, v + 1}
	else if x > n then
		set {x, y, d} to {n, y + 2, -d}
	else if y > n then
		set {x, y, d} to {x + 2, n, -d}
	else if x < 1 then
		set {x, y, d} to {1, y, -d}
	else if y < 1 then
		set {x, y, d} to {x, 1, -d}
	end if
end repeat
--> R = {{0, 1, 5, 6, 14}, {2, 4, 7, 13, 15}, {3, 8, 12, 16, 21}, {9, 11, 17, 20, 22}, {10, 18, 19, 23, 24}}

-- Reformat the matrix into a table for viewing.
repeat with i in m
	repeat with j in i
		set j's contents to  (characters -(length of (n ^ 2 as string)) thru -1 of ("          " & j)) as string
	end repeat
	set end of i to return
end repeat
return return & m as string


variable open := <<(* --> false)>>;
for (pass; 1; pass <= 100)
    for (door_num; pass; door_num <= 100; pass)
        open[door_num] := !(open[door_num]);;;
iterate (door_num; [1...100])
    print("Door ", door_num, " is ",
          (open[door_num] ? "open.\n" : "closed.\n"));;


data _null_;
   open=1;
   close=0;
   array Door{100};
   do Pass = 1 to 100;
      do Current = Pass to 100 by Pass;
         if Door{Current} ne open
            then Door{Current} = open;
            else Door{Current} = close;
      end;
   end;
   NumberOfOpenDoors = sum(of Door{*});
   put "Number of Open Doors:  " NumberOfOpenDoors;
run;


100 S = 5
110 S2 = S ^ 2 : REM SQUARED
120 H = S2 / 2 : REM HALFWAY
130 S2 = S2 - 1
140 DX = 1 : REM INITIAL
150 DY = 0 : REM DIRECTION
160 N = S - 1
170 DIM A%(N, N)

200 FOR I = 0 TO H
210     A%(X, Y) = I
220     A%(N - X, N - Y) = S2 - I
230     X = X + DX
240     Y = Y + DY
250     IF Y = 0 THEN DY = DY + 1 : IF DY THEN DX = -DX
260     IF X = 0 THEN DX = DX + 1 : IF DX THEN DY = -DY
270 NEXT I

300 FOR Y = 0 TO N
310     FOR X = 0 TO N
320         IF X THEN PRINT TAB(X * (LEN(STR$(S2)) + 1) + 1);
330         PRINT A%(X, Y);
340     NEXT X
350     PRINT
360 NEXT Y


zigzag: function [n][
    result: map 1..n 'x -> map 1..n => 0

    x: 1, y: 1, v: 0, d: 1

    while [v < n^2][
        if? all? @[1 =< x x =< n 1 =< y y =< n][
            set get result (y-1) (x-1) v
            x: x + d, y: y - d, v: v + 1
        ]
        else[if? x > n [x: n, y: y + 2, d: neg d]
            else[if? y > n [x: x + 2, y: n, d: neg d]
                else[if? x < 1 [x: 1, d: neg d]
                    else[if y < 1 [y: 1, d: neg d]
                    ]
                ]
            ]
        ]
    ]
    result
]

zz: zigzag 5
loop zz 'row -> print map row 'col [pad to :string col 3]


class MAIN is
  main is
    doors :ARRAY{BOOL} := #(100);
    loop
      pass::= doors.ind!;
      loop
        i::= pass.stepto!(doors.size - 1, pass + 1);
        doors[i] := ~doors[i];
      end;
    end;
    loop
      #OUT + (doors.ind! + 1) + " " + doors.elt! + "\n";
    end;
  end;
end;


for { i <- 1 to 100
      r = 1 to 100 map (i % _ == 0) reduceLeft (_^_)
    } println (i +" "+ (if (r) "open" else "closed"))


(* ****** ****** *)
//
#include
"share/atspre_define.hats" // defines some names
#include
"share/atspre_staload.hats" // for targeting C
#include
"share/HATS/atspre_staload_libats_ML.hats" // for ...
//
(* ****** ****** *)
//
extern
fun
Zig_zag_matrix(n: int): void
//
(* ****** ****** *)

fun max(a: int, b: int): int =
  if a > b then a else b

fun movex(n: int, x: int, y: int): int =
  if y < n-1 then max(0, x-1) else x+1

fun movey(n: int, x: int, y: int): int =
  if y < n-1 then y+1 else y

fun zigzag(n: int, i: int, row: int, x: int, y: int): void =
  if i = n*n then ()
  else
    let
      val () = (if x = row then begin print i; print ','; end else ())
      //val () = (begin print x; print ' '; print y; print ' '; print i; print ' '; end)
      val nextX: int = if ((x+y) % 2) = 0 then movex(n, x, y) else movey(n, y, x)
      val nextY: int = if ((x+y) % 2) = 0 then movey(n, x, y) else movex(n, y, x)
    in
      zigzag(n, i+1, row, nextX, nextY)
    end

implement
Zig_zag_matrix(n) =
  let
    fun loop(row: int): void =
      if row = n then () else
        let
          val () = zigzag(n, 0, row, 0, 0)
          val () = println!(" ")
        in
          loop(row + 1)
        end
  in
    loop(0)
  end

(* ****** ****** *)

implement
main0() = () where
{
  val () = Zig_zag_matrix(5)
} (* end of [main0] *)

(* ****** ****** *)


n = 5                           ; size
v := x := y := 1                ; initial values
Loop % n*n {                    ; for every array element
   a_%x%_%y% := v++             ; assign the next index
   If ((x+y)&1)                 ; odd diagonal
      If (x < n)                ; while inside the square
         y -= y<2 ? 0 : 1, x++  ; move right-up
      Else y++                  ; on the edge increment y, but not x: to even diagonal
   Else                         ; even diagonal
      If (y < n)                ; while inside the square
         x -= x<2 ? 0 : 1, y++  ; move left-down
      Else x++                  ; on the edge increment x, but not y: to odd diagonal
}

Loop %n% {                      ; generate printout
   x := A_Index                 ; for each row
   Loop %n%                     ; and for each column
      t .= a_%x%_%A_Index% "`t" ; attach stored index
   t .= "`n"                    ; row is complete
}
MsgBox %t%                      ; show output


(define *max-doors* 100)

(define (show-doors doors)
  (let door ((i 0)
             (l (vector-length doors)))
    (cond ((= i l)
           (newline))
          (else
           (printf "~nDoor ~a is ~a"
                   (+ i 1)
                   (if (vector-ref doors i) "open" "closed"))
           (door (+ i 1) l)))))

(define (flip-doors doors)
  (define (flip-all i)
    (cond ((> i *max-doors*) doors)
          (else
           (let flip ((idx (- i 1)))
             (cond ((>= idx *max-doors*)
                    (flip-all (+ i 1)))
                   (else
                    (vector-set! doors idx (not (vector-ref doors idx)))
                    (flip (+ idx i))))))))
  (flip-all 1))

(show-doors (flip-doors (make-vector *max-doors* #f)))


#include <Array.au3>
$Array = ZigZag(5)
_ArrayDisplay($Array)

Func ZigZag($int)
	Local $av_array[$int][$int]
	Local $x = 1, $y = 1
	For $I = 0 To $int ^ 2 -1
		$av_array[$x-1][$y-1] = $I
		If Mod(($x + $y), 2) = 0 Then ;Even
			if ($y < $int) Then
				$y += 1
			Else
				$x += 2
			EndIf
			if ($x > 1) Then $x -= 1
		Else ; ODD
			if ($x < $int) Then
				$x += 1
			Else
				$y += 2
			EndIf
			If $y > 1 Then $y -= 1
		EndIf
	Next
	Return $av_array
EndFunc   ;==>ZigZag


doors=zeros(1,100);
for i = 1:100
  for j = i:i:100
    doors(j) = ~doors(j);
  end
end
for i = 1:100
  if ( doors(i) )
    s = "open";
  else
    s = "closed";
  end
  printf("%d %s\n", i, s);
end


$ include "seed7_05.s7i";

const proc: main is func
  local
    var array boolean: doorOpen is 100 times FALSE;
    var integer: pass is 0;
    var integer: index is 0;
    var array[boolean] string: closedOrOpen is [boolean] ("closed", "open");
  begin
    for pass range 1 to 100 do
      for key index range doorOpen do
        if index rem pass = 0 then
          doorOpen[index] := not doorOpen[index];
        end if;
      end for;
    end for;
    for key index range doorOpen do
      write(index lpad 3 <& " is " <& closedOrOpen[doorOpen[index]] rpad 7);
      if index rem 5 = 0 then
        writeln;
      end if;
    end for;
  end func;


# syntax: GAWK -f ZIG-ZAG_MATRIX.AWK [-v offset={0|1}] [size]
BEGIN {
# offset: "0" prints 0 to size^2-1 while "1" prints 1 to size^2
    offset = (offset == "") ? 0 : offset
    size = (ARGV[1] == "") ? 5 : ARGV[1]
    if (offset !~ /^[01]$/) { exit(1) }
    if (size !~ /^[0-9]+$/) { exit(1) }
    width = length(size ^ 2 - 1 + offset) + 1
    i = j = 1
    for (n=0; n<=size^2-1; n++) { # build array
      arr[i-1,j-1] = n + offset
      if ((i+j) % 2 == 0) {
        if (j < size) { j++ } else { i+=2 }
        if (i > 1) { i-- }
      }
      else {
        if (i < size) { i++ } else { j+=2 }
        if (j > 1) { j-- }
      }
    }
    for (row=0; row<size; row++) { # show array
      for (col=0; col<size; col++) {
        printf("%*d",width,arr[row,col])
      }
      printf("\n")
    }
    exit(0)
}


put false repeated 100 times as a list into Doors100

repeat 1 to 100
	set step to it
	repeat step to 100 by step
		set newValue to not item it of Doors100
		set item it of Doors100 to newValue
	end repeat
end repeat

put the counter for each item of Doors100 which is true


      Size% = 5
      DIM array%(Size%-1,Size%-1)

      i% = 1
      j% = 1
      FOR e% = 0 TO Size%^2-1
        array%(i%-1,j%-1) = e%
        IF ((i% + j%) AND 1) = 0 THEN
          IF j% < Size% j% += 1 ELSE i% += 2
          IF i% > 1 i% -= 1
        ELSE
          IF i% < Size% i% += 1 ELSE j% += 2
          IF j% > 1 j% -= 1
        ENDIF
      NEXT

      @% = &904
      FOR row% = 0 TO Size%-1
        FOR col% = 0 TO Size%-1
          PRINT array%(row%,col%);
        NEXT
        PRINT
      NEXT row%


beads 1 program 'Zig-zag Matrix'

calc main_init
	var test : array^2 of num = create_array(5)
	printMatrix(test)

calc create_array(
	dimension:num
	):array^2 of num
	var
		result : array^2 of num
		lastValue = dimension^2 - 1
		loopFrom
		loopTo
		row
		col
		currDiag = 0
		currNum = 0
	loop
		if (currDiag < dimension)	// if doing the upper-left triangular half
			loopFrom = 1
			loopTo = currDiag + 1
		else	// doing the bottom-right triangular half
			loopFrom = currDiag - dimension + 2
			loopTo = dimension
		loop count:c from:loopFrom to:loopTo
			var i = loopFrom + c - 1
			if (rem(currDiag, 2) == 0)	// want to fill upwards
				row = loopTo - i + loopFrom
				col = i
			else	// want to fill downwards
				row = i
				col = loopTo - i + loopFrom
			result[row][col] = currNum
			inc currNum
		inc currDiag
		if (currNum > lastValue)
			exit
	return result

calc printMatrix(
	matrix:array^2 of num
	)
	var dimension = tree_count(matrix)
	var maxDigits = 1 + lg((dimension^2-1), base:10)
	loop across:matrix ptr:rowp index:row
		var tempstr : str
		loop across:rowp index:col
			tempstr = tempstr & " " & to_str(matrix[row][col], min:maxDigits)
		log(tempstr)


import <Utilities/Sequence.sl>;

main:=
	let
		doors := flipDoors(duplicate(false, 100), 1);
		open[i] := i when doors[i];
	in
		open;

flipDoors(doors(1), count) :=
	let
		newDoors[i] := not doors[i] when i mod count = 0 else doors[i];
	in
		doors when count >= 100 else flipDoors(newDoors, count + 1);


program hundred_doors;

const toggle := {['open', 'closed'], ['closed', 'open']};

doorStates := ['closed'] * 100;

(for interval in [1..100])
  doorStates := [if i mod interval = 0 then
                    toggle(prevState) else
                    prevState end:
                 prevState = doorStates(i)];
end;

(for finalState = doorStates(i))
  print('door', i, 'is', finalState);
end;

end program;


Flip ← {m←2|+⌜˜↕≠𝕩 ⋄ (⍉𝕩×¬m)+𝕩×m}
Zz   ← {Flip ⍋∘⍋⌾⥊+⌜˜↕𝕩}


var doors = []

{ |pass|
    { |i|
        if (pass `divides` i) {
            doors[i] := false -> not!
        }
    } << 1..100
} << 1..100

{ |i|
    say ("Door %3d is %s" % (i, doors[i] ? 'open' : 'closed'))
} << 1..100


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

int main(int c, char **v)
{
	int i, j, m, n, *s;

	/* default size: 5 */
	if (c < 2 || ((m = atoi(v[1]))) <= 0) m = 5;

	/* alloc array*/
	s = malloc(sizeof(int) * m * m);

	for (i = n = 0; i < m * 2; i++)
		for (j = (i < m) ? 0 : i-m+1; j <= i && j < m; j++)
			s[(i&1)? j*(m-1)+i : (i-j)*m+j ] = n++;

	for (i = 0; i < m * m; putchar((++i % m) ? ' ':'\n'))
		printf("%3d", s[i]);

	/* free(s) */
	return 0;
}


BEGIN
    INTEGER LIMIT = 100, door, stride;
    BOOLEAN ARRAY DOORS(1:LIMIT);
    TEXT intro;

    FOR stride := 1 STEP 1 UNTIL LIMIT DO
        FOR door := stride STEP stride UNTIL LIMIT DO
            DOORS(door) := NOT DOORS(door);

    intro :- "All doors closed but ";
    FOR door := 1 STEP 1 UNTIL LIMIT DO
        IF DOORS(door) THEN BEGIN
            OUTTEXT(intro); OUTINT(door, 0); intro :- ", "
        END;
    OUTIMAGE
END.


define: #a -> (Array newSize: 100).
a infect: [| :_ | False].

a keysDo: [| :pass |
  pass to: a indexLast by: pass do: [| :door |
    a at: door infect: #not `er]].

a keysAndValuesDo: [| :door :isOpen |
  inform: 'door #' ; door ; ' is ' ; (isOpen ifTrue: ['open'] ifFalse: ['closed'])].


public static int[,] ZigZag(int n)
{
    int[,] result = new int[n, n];
    int i = 0, j = 0;
    int d = -1; // -1 for top-right move, +1 for bottom-left move
    int start = 0, end = n * n - 1;
    do
    {
        result[i, j] = start++;
        result[n - i - 1, n - j - 1] = end--;

        i += d; j -= d;
        if (i < 0)
        {
            i++; d = -d; // top reached, reverse
        }
        else if (j < 0)
        {
            j++; d = -d; // left reached, reverse
        }
    } while (start < end);
    if (start == end)
        result[i, j] = start;
    return result;
}


|a|
a := Array new: 100 .
1 to: 100 do: [ :i | a at: i put: false ].

1 to: 100 do: [ :pass |
  pass to: 100 by: pass do: [ :door |
    a at: door put: (a at: door) not .
  ]
].

"output"
1 to: 100 do: [ :door |
   ( 'door #%1 is %2' %
     { door . (a at: door) ifTrue: [ 'open' ] ifFalse: [ 'closed' ] } ) displayNl
]


#include <vector>
#include <memory>	// for auto_ptr
#include <cmath>	// for the log10 and floor functions
#include <iostream>
#include <iomanip>	// for the setw function

using namespace std;

typedef vector< int > IntRow;
typedef vector< IntRow > IntTable;

auto_ptr< IntTable > getZigZagArray( int dimension )
{
	auto_ptr< IntTable > zigZagArrayPtr( new IntTable(
		dimension, IntRow( dimension ) ) );

	// fill along diagonal stripes (oriented as "/")
	int lastValue = dimension * dimension - 1;
	int currNum = 0;
	int currDiag = 0;
	int loopFrom;
	int loopTo;
	int i;
	int row;
	int col;
	do
	{
		if ( currDiag < dimension ) // if doing the upper-left triangular half
		{
			loopFrom = 0;
			loopTo = currDiag;
		}
		else // doing the bottom-right triangular half
		{
			loopFrom = currDiag - dimension + 1;
			loopTo = dimension - 1;
		}

		for ( i = loopFrom; i <= loopTo; i++ )
		{
			if ( currDiag % 2 == 0 ) // want to fill upwards
			{
				row = loopTo - i + loopFrom;
				col = i;
			}
			else // want to fill downwards
			{
				row = i;
				col = loopTo - i + loopFrom;
			}

			( *zigZagArrayPtr )[ row ][ col ] = currNum++;
		}

		currDiag++;
	}
	while ( currDiag <= lastValue );

	return zigZagArrayPtr;
}

void printZigZagArray( const auto_ptr< IntTable >& zigZagArrayPtr )
{
	size_t dimension = zigZagArrayPtr->size();

	int fieldWidth = static_cast< int >( floor( log10(
		static_cast< double >( dimension * dimension - 1 ) ) ) ) + 2;

	size_t col;
	for ( size_t row = 0; row < dimension; row++ )
	{
		for ( col = 0; col < dimension; col++ )
			cout << setw( fieldWidth ) << ( *zigZagArrayPtr )[ row ][ col ];
		cout << endl;
	}
}

int main()
{
	printZigZagArray( getZigZagArray( 5 ) );
}


x=1!y=3!z=0
PRINT "Open doors: ";x;" ";
DO
    z=x+y
    PRINT z;" ";
    x=z
    y=y+2
UNTIL z>=100
END


class ZigZag(Integer size) {

	value data = Array {
		for (i in 0:size)
		Array.ofSize(size, 0)
	};

	variable value i = 1;
	variable value j = 1;

	for (element in 0 : size^2) {
		data[j - 1]?.set(i - 1, element);
		if ((i + j).even) {
			if (j < size) {
				j++;
			}
			else {
				i += 2;
			}
			if (i > 1) {
				i--;
			}
		}
		else {
			if (i < size) {
				i++;
			}
			else {
				j += 2;
			}
			if (j > 1) {
				j--;
			}
		}
	}

	shared void display() {
		for (row in data) {
			for (element in row) {
				process.write(element.string.pad(3));
			}
			print(""); //newline
		}
	}
}

shared void run() {
	value zz = ZigZag(5);
	zz.display();
}


(defn partitions [sizes coll]
  (lazy-seq
   (when-let [n (first sizes)]
     (when-let [s (seq coll)]
       (cons (take n coll)
	     (partitions (next sizes) (drop n coll)))))))

(defn take-from [n colls]
  (lazy-seq
   (when-let [s (seq colls)]
     (let [[first-n rest-n] (split-at n s)]
       (cons (map first first-n)
	     (take-from n (concat (filter seq (map rest first-n)) rest-n)))))))

(defn zig-zag [n]
  (->> (partitions (concat (range 1 (inc n)) (range (dec n) 0 -1)) (range (* n n)))
       (map #(%1 %2) (cycle [reverse identity]) ,)
       (take-from n ,)))

user> (zig-zag 5)
(( 0  1  5  6 14)
 ( 2  4  7 13 15)
 ( 3  8 12 16 21)
 ( 9 11 17 20 22)
 (10 18 19 23 24))

user> (zig-zag 6)
(( 0  1  5  6 14 15)
 ( 2  4  7 13 16 25)
 ( 3  8 12 17 24 26)
 ( 9 11 18 23 27 32)
 (10 19 22 28 31 33)
 (20 21 29 30 34 35))


		DEFINE('PASS(A,I),O')		:(PASS.END)
PASS		O = 0
PASS.LOOP	O = O + I
		EQ(A<O>,1)			:S(PASS.1)F(PASS.0)
PASS.0		A<O> = 1			:S(PASS.LOOP)F(RETURN)
PASS.1		A<O> = 0			:S(PASS.LOOP)F(RETURN)
PASS.END

MAIN		D = ARRAY(100,0)
		I = 0

MAIN.LOOP	I = LE(I,100) I + 1		:F(OUTPUT)
		PASS(D,I)			:(MAIN.LOOP)

OUTPUT		I = 1 ; OPEN = 'Opened doors are: '
OUTPUT.LOOP	OPEN = OPEN EQ(D<I>,1) " " I
		I = LE(I,100) I + 1		:S(OUTPUT.LOOP)F(OUTPUT.WRITE)
OUTPUT.WRITE	OUTPUT = OPEN

END


# Calculate a zig-zag pattern of numbers like so:
#   0 1 5
#   2 4 6
#   3 7 8
#
# There are many interesting ways to solve this; we
# try for an algebraic approach, calculating triangle
# areas, so that me minimize space requirements.

zig_zag_value = (x, y, n) ->

  upper_triangle_zig_zag = (x, y) ->
    # calculate the area of the triangle from the prior
    # diagonals
    diag = x + y
    triangle_area = diag * (diag+1) / 2
    # then add the offset along the diagonal
    if diag % 2 == 0
      triangle_area + y
    else
      triangle_area + x

  if x + y < n
    upper_triangle_zig_zag x, y
  else
    # For the bottom right part of the matrix, we essentially
    # use reflection to count backward.
    bottom_right_cell = n * n - 1
    n -= 1
    v = upper_triangle_zig_zag(n-x, n-y)
    bottom_right_cell - v

zig_zag_matrix = (n) ->
  row = (i) -> (zig_zag_value i, j, n for j in [0...n])
  (row i for i in [0...n])

do ->
  for n in [4..6]
    console.log "---- n=#{n}"
    console.log zig_zag_matrix(n)
    console.log "\n"


/* declare the variables */
var isOpen = {};
var pass, door;

/* initialize the doors */
for door = 0; door < 100; door++ {
	isOpen[door] = true;
}

/* do the 99 remaining passes */
for pass = 1; pass < 100; ++pass {
	for door = pass; door < 100; door += pass+1 {
  		isOpen[door] = !isOpen[door];
	}
}

/* print the results */
var states = { true: "open", false: "closed" };
for door = 0; door < 100; door++ {
	printf("Door #%d is %s.\n", door+1, states[isOpen[door]]);
}


con
  _clkmode = xtal1+pll16x
  _clkfreq = 80_000_000

obj
  ser : "FullDuplexSerial.spin"

pub init
  ser.start(31, 30, 0, 115200)

  doors

  waitcnt(_clkfreq + cnt)
  ser.stop
  cogstop(0)

var

  byte door[101] ' waste one byte by using only door[1..100]

pri doors | i,j

  repeat i from 1 to 100
    repeat j from i to 100 step i
      not door[j]

  ser.str(string("Open doors: "))

  repeat i from 1 to 100
    if door[i]
      ser.dec(i)
      ser.tx(32)

  ser.str(string(13,10))


(defun zigzag (n)
  (flet ((move (i j)
           (if (< j (1- n))
               (values (max 0 (1- i)) (1+ j))
               (values (1+ i) j))))
    (loop with a = (make-array (list n n) :element-type 'integer)
          with x = 0
          with y = 0
          for v from 0 below (* n n)
          do (setf (aref a x y) v)
             (if (evenp (+ x y))
                 (setf (values x y) (move x y))
                 (setf (values y x) (move y x)))
          finally (return a))))


DECLARE	@sqr INT,
		@i INT,
		@door INT;

SELECT @sqr =1,
	@i = 3,
	@door = 1;

WHILE(@door <=100)
BEGIN
	IF(@door = @sqr)
	BEGIN
		PRINT 'Door ' + RTRIM(CAST(@door AS CHAR)) + ' is open.';
		SET @sqr= @sqr+@i;
		SET @i=@i+2;
	END
	ELSE
	BEGIN
		PRINT 'Door ' + RTRIM(CONVERT(CHAR,@door)) + ' is closed.';
	END
SET @door = @door + 1
END


def zigzag(n)
  (seq=(0...n).to_a).product(seq)
    .sort_by {|x,y| [x+y, (x+y).even? ? y : -y]}
    .map_with_index{|v, i| {v, i}}.sort.map(&.last).each_slice(n).to_a
end

def print_matrix(m)
  format = "%#{m.flatten.max.to_s.size}d " * m[0].size
  m.each {|row| puts format % row}
end

print_matrix zigzag(5)


--#SET TERMINATOR @

SET SERVEROUTPUT ON @

BEGIN
 DECLARE TYPE DOORS_ARRAY AS BOOLEAN ARRAY [100];
 DECLARE DOORS DOORS_ARRAY;
 DECLARE I SMALLINT;
 DECLARE J SMALLINT;
 DECLARE STATUS CHAR(10);
 DECLARE SIZE SMALLINT DEFAULT 100;

 -- Initializes the array, with all spaces (doors) as false (closed).
 SET I = 1;
 WHILE (I <= SIZE) DO
  SET DOORS[I] = FALSE;
  SET I = I + 1;
 END WHILE;

 -- Processes the doors.
 SET I = 1;
 WHILE (I <= SIZE) DO
  SET J = 1;
  WHILE (J <= SIZE) DO
   IF (MOD(J, I) = 0) THEN
    IF (DOORS[J] = TRUE) THEN
     SET DOORS[J] = FALSE;
    ELSE
     SET DOORS[J] = TRUE;
    END IF;
   END IF;
   SET J = J + 1;
  END WHILE;
  SET I = I + 1;
 END WHILE;

 -- Prints the final status o the doors.
 SET I = 1;
 WHILE (I <= SIZE) DO
  SET STATUS = (CASE WHEN (DOORS[I] = TRUE) THEN 'OPEN' ELSE 'CLOSED' END);
  CALL DBMS_OUTPUT.PUT_LINE('Door ' || I || ' is '|| STATUS);
  SET I = I + 1;
 END WHILE;
END @


int[][] zigZag(in int n) pure nothrow @safe {
    static void move(in int n, ref int i, ref int j)
    pure nothrow @safe @nogc {
        if (j < n - 1) {
            if (i > 0) i--;
            j++;
        } else
            i++;
    }

    auto a = new int[][](n, n);
    int x, y;
    foreach (v; 0 .. n ^^ 2) {
        a[y][x] = v;
        (x + y) % 2 ? move(n, x, y) : move(n, y, x);
    }
    return a;
}

void main() {
    import std.stdio;

    writefln("%(%(%2d %)\n%)", 5.zigZag);
}


datatype Door = Closed | Opened

fun toggle Closed = Opened
  | toggle Opened = Closed

fun pass (step, doors) = List.map (fn (index, door) => if (index mod step) = 0
						       then (index, toggle door)
						       else (index, door))
				  doors

(* [1..n] *)
fun runs n = List.tabulate (n, fn k => k+1)

fun run n =
    let
	val initialdoors = List.tabulate (n, fn i => (i+1, Closed))
	val counter = runs n
    in
	foldl pass initialdoors counter
    end

fun opened_doors n = List.mapPartial (fn (index, Closed) => NONE
				       | (index, Opened) => SOME (index))
				     (run n)


clear
set obs 100
gen doors=0
gen index=_n
forvalues i=1/100 {
	quietly replace doors=!doors if mod(_n,`i')==0
}
list index if doors, noobs noheader

  +-------+
  |     1 |
  |     4 |
  |     9 |
  |    16 |
  |    25 |
  |-------|
  |    36 |
  |    49 |
  |    64 |
  |    81 |
  |   100 |
  +-------+


/** Missing scalar multiplication, but we don't need it. */
def makeVector2(x, y) {
  return def vector {
    to x() { return x }
    to y() { return y }
    to add(other) { return makeVector2(x + other.x(), y + other.y()) }
    to clockwise() { return makeVector2(-y, x) }
  }
}

/** Bugs: (1) The printing is specialized. (2) No bounds check on the column. */
def makeFlex2DArray(rows, cols) {
  def storage := ([null] * (rows * cols)).diverge()
  return def flex2DArray {
    to __printOn(out) {
      for y in 0..!rows {
        for x in 0..!cols {
          out.print(<import:java.lang.makeString>.format("%3d", [flex2DArray[y, x]]))
        }
        out.println()
      }
    }
    to get(r, c) { return storage[r * cols + c] }
    to put(r, c, v) { storage[r * cols + c] := v }
  }
}


(
var n = 100, doors = false ! n;
var pass = { |j| (0, j .. n-1).do { |i| doors[i] = doors[i].not } };
(1..n-1).do(pass);
doors.selectIndices { |open| open }; // all are closed except [ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81 ]
)


/* declare enum to identify the state of a door */
enum DoorState : String {
    case Opened = "Opened"
    case Closed = "Closed"
}

/* declare list of doors state and initialize them */
var doorsStateList = [DoorState](count: 100, repeatedValue: DoorState.Closed)

/* do the 100 passes */
for i in 1...100 {
    /* map on a strideTo instance to only visit the needed doors on each iteration */
    map(stride(from: i - 1, to: 100, by: i)) {
        doorsStateList[$0] = doorsStateList[$0] == .Opened ? .Closed : .Opened
    }
}

/* print the results */
for (index, item) in enumerate(doorsStateList) {
    println("Door \(index+1) is \(item.rawValue)")
}


import extensions;

extension op : IntNumber
{
    zigzagMatrix()
    {
        auto result := IntMatrix.allocate(self, self);

        int i := 0;
        int j := 0;
        int d := -1;
        int start := 0;
        int end := self*self - 1;

        while (start < end)
        {
            result.setAt(i, j, start); start += 1;
            result.setAt(self - i - 1, self - j - 1, end); end -= 1;

            i := i + d;
            j := j - d;
            if (i < 0)
            {
                i:=i+1; d := d.Negative
            }
            else if (j < 0)
            {
                j := j + 1; d := d.Negative
            }
        };

        if (start == end)
        {
            result.setAt(i, j, start)
        };

        ^ result
    }
}

public program()
{
    console.printLine(5.zigzagMatrix()).readChar()
}


defmodule RC do
  require Integer
  def zigzag(n) do
    fmt = "~#{to_char_list(n*n-1) |> length}w "
    (for x <- 1..n, y <- 1..n, do: {x,y})
      |> Enum.sort_by(fn{x,y}->{x+y, if(Integer.is_even(x+y), do: y, else: x)} end)
      |> Enum.with_index |> Enum.sort
      |> Enum.each(fn {{_x,y},i} ->
           :io.format fmt, [i]
           if y==n, do: IO.puts ""
         end)
  end
end

RC.zigzag(5)


source hundredDoors
  @: [ 1..100 -> 0 ];
  templates toggle
    def jump: $;
    $jump..100:$jump -> \(when <?([email protected]($) <=0>)> do @hundredDoors($): 1;  otherwise @hundredDoors($): 0;\) -> !VOID
  end toggle
  1..100 -> toggle -> !VOID
  [email protected] -> \[i](<=1> ' $i;' !\) !
end hundredDoors

$hundredDoors -> 'Open doors:$...;' -> !OUT::write


package require Tcl 8.5
set n 100
set doors [concat - [lrepeat $n 0]]
for {set step 1} {$step <= $n} {incr step} {
    for {set i $step} {$i <= $n} {incr i $step} {
        lset doors $i [expr { ! [lindex $doors $i]}]
    }
}
for {set i 1} {$i <= $n} {incr i} {
    puts [format "door %d is %s" $i [expr {[lindex $doors $i] ? "open" : "closed"}]]
}


-module( zigzag ).

-export( [matrix/1, task/0] ).

matrix( N ) ->
	{{_X_Y, N}, Proplist} = lists:foldl( fun matrix_as_proplist/2, {{{0, 0}, N}, []}, lists:seq(0, (N * N) - 1) ),
	[columns( X, Proplist ) || X <- lists:seq(0, N - 1)].

task() -> matrix( 5 ).

columns( Column, Proplist ) -> lists:sort( [Value || {{_X, Y}, Value} <- Proplist, Y =:= Column] ).

matrix_as_proplist( N, {{X_Y, Max}, Acc} ) ->
	Next = next_indexes( X_Y, Max ),
	{{Next, Max}, [{X_Y, N} | Acc]}.

next_indexes( {X, Y}, Max ) when Y + 1 =:= Max, (X + Y) rem 2 =:= 0  -> {X + 1, Y - 1};
next_indexes( {X, Y}, Max ) when Y + 1 =:= Max, (X + Y) rem 2 =:= 1  -> {X + 1, Y};
next_indexes( {X, Y}, Max ) when X + 1 =:= Max, (X + Y) rem 2 =:= 0  -> {X, Y + 1};
next_indexes( {X, Y}, Max ) when X + 1 =:= Max, (X + Y) rem 2 =:= 1  -> {X - 1, Y + 1};
next_indexes( {X, 0}, _Max ) when X rem 2 =:= 0 -> {X + 1, 0};
next_indexes( {X, 0}, _Max ) when X rem 2 =:= 1 -> {X - 1, 1};
next_indexes( {0, Y}, _Max ) when Y rem 2 =:= 0 -> {1, Y - 1};
next_indexes( {0, Y}, _Max ) when Y rem 2 =:= 1 -> {0, Y + 1};
next_indexes( {X, Y}, _Max ) when (X + Y) rem 2 =:= 0 -> {X + 1, Y - 1};
next_indexes( {X, Y}, _Max ) when (X + Y) rem 2 =:= 1 -> {X - 1, Y + 1}.


seq(0,X,1,100
For(X,1,100
0 or Ans-not(fPart(cumSum(1 or Ans)/A
End
Pause Ans


Define doors(fast) = Func
  Local doors,i,j
  seq(false,x,1,100) ? doors
  If fast Then
    For i,1,10,1
      true ? doors[i^2]
    EndFor
  Else
    For i,1,100,1
      For j,i,100,i
        not doors[j] ? doors[j]
      EndFor
    EndFor
  EndIf
  Return doors
EndFunc


PROGRAM ZIG_ZAG

!$DYNAMIC
     DIM ARRAY%[0,0]

BEGIN
     SIZE%=5
     !$DIM ARRAY%[SIZE%-1,SIZE%-1]

     I%=1
     J%=1
     FOR E%=0 TO SIZE%^2-1 DO
          ARRAY%[I%-1,J%-1]=E%
          IF ((I%+J%) AND 1)=0 THEN
              IF J%<SIZE% THEN J%+=1 ELSE I%+=2 END IF
              IF I%>1 THEN I%-=1 END IF
           ELSE
              IF I%<SIZE% THEN I%+=1 ELSE J%+=2 END IF
              IF J%>1 THEN J%-=1 END IF
          END IF
     END FOR

     FOR ROW%=0 TO SIZE%-1 DO
         FOR COL%=0 TO SIZE%-1 DO
            WRITE("###";ARRAY%[ROW%,COL%];)
         END FOR
         PRINT
     END FOR
END PROGRAM


function zigzag(integer size)
    sequence s
    integer i, j, d, max
    s = repeat(repeat(0,size),size)
    i = 1  j = 1  d = -1
    max = size*size
    for n = 1 to floor(max/2)+1 do
        s[i][j] = n
        s[size-i+1][size-j+1] = max-n+1
        i += d  j-= d
        if i < 1 then
            i += 1  d = -d
        elsif j < 1 then
            j += 1  d = -d
        end if
    end for
    return s
end function

? zigzag(5)


for(%steps = 1; %a <= 100; %a++)
	for(%current = %steps; %current <= 100; %current += %steps)
		%door[%current] = !%door[%current];
for(%a = 1; %a <= 100; %a++)
	echo("Door #" @ %a @ " is" SPC %door[%current] ? "Open" : "Closed" @ ".");


WITH    OneToTen (N)
AS  (   SELECT  N
        FROM (  VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9)
                ) V(N)
        )
    ,   InitDoors (Num, IsOpen)
AS  (   SELECT  1
            +   1 * Units.N
            +   10 * Tens.N AS Num
            ,   CONVERT(Bit, 0) AS IsOpen
        FROM    OneToTen AS Units
        CROSS JOIN  OneToTen AS Tens
        ) -- This part could be easier with a tally table or equivalent table-valued function
    ,   States (NbStep, Num, IsOpen)
AS  (   SELECT  0 AS NbStep
            ,   Num
            ,   IsOpen
        FROM    InitDoors AS InitState
        UNION ALL
        SELECT  1 + NbStep
            ,   Num
            ,   CASE Num % (1 + NbStep)
                    WHEN 0 THEN ~IsOpen
                    ELSE IsOpen
                END
        FROM    States
        WHERE   NbStep < 100
        )
SELECT  Num AS DoorNumber
    ,   Concat( 'Door number ', Num, ' is '
            ,   CASE IsOpen
                    WHEN 1 THEN ' open'
                    ELSE ' closed'
                END ) AS RESULT -- Concat needs SQL Server 2012
FROM    States
WHERE   NbStep = 100
ORDER BY Num
; -- Fortunately, maximum recursion is 100 in SQL Server.
-- For more doors, the MAXRECURSION hint should be used.
-- More doors would also need an InitDoors with more rows.


//Produce a zig zag matrix - Nigel Galloway: April 7th., 2015
let zz l a =
  let N = Array2D.create l a 0
  let rec gng (n, i, g, e) =
    N.[n,i] <- g
    match e with
    | _ when i=a-1 && n=l-1 -> N
    | 1 when n = l-1        -> gng (n, i+1, g+1, 2)
    | 2 when i = a-1        -> gng (n+1, i, g+1, 1)
    | 1 when i = 0          -> gng (n+1, 0, g+1, 2)
    | 2 when n = 0          -> gng (0, i+1, g+1, 1)
    | 1                     -> gng (n+1, i-1, g+1, 1)
    | _                     -> gng (n-1, i+1, g+1, 2)
  gng (0, 0, 0, 2)


#lang transd

MainModule: {
    doors: Vector<Bool>(100),
    _start: (λ
        (for i in Seq(100) do
            (for k in Seq(i 100 (+ i 1)) do
                (set-el doors k (not (get doors k)))
        ))

        (for i in Seq(100) do
            (if (get doors i) (textout (+ i 1) " "))
    ))
}


! Optimized solution with True BASIC

OPTION NOLET
x = 1
y = 3
z = 0
PRINT STR$(x) & " Open"
DO UNTIL z >= 100
z = x + y
PRINT STR$(z) & " Open"
x = z
y = y + 2
LOOP

END


USING: columns fry kernel make math math.ranges prettyprint
sequences sequences.cords sequences.extras ;
IN: rosetta-code.zig-zag-matrix

: [1,b,1] ( n -- seq )
    [1,b] dup but-last-slice <reversed> cord-append ;

: <reversed-evens> ( seq -- seq' )
    [ even? [ <reversed> ] when ] map-index ;

: diagonals ( n -- seq )
    [ sq <iota> ] [ [1,b,1] ] bi
    [ [ cut [ , ] dip ] each ] { } make nip <reversed-evens> ;

: zig-zag-matrix ( n -- seq )
    [ diagonals ] [ dup ] bi '[
        [
            dup 0 <column> _ head ,
            [ _ < [ rest-slice ] when ] map-index harvest
        ] until-empty
    ] { } make ;

: zig-zag-demo ( -- ) 5 zig-zag-matrix simple-table. ;

MAIN: zig-zag-demo


using gfx  // for Point; convenient x/y wrapper

**
** A couple methods for generating a 'zigzag' array like
**
**   0  1  5  6
**   2  4  7 12
**   3  8 11 13
**   9 10 14 15
**
class ZigZag
{
  ** return an n x n array of uninitialized Int
  static Int[][] makeSquareArray(Int n)
  {
    Int[][] grid := Int[][,] {it.size=n}
    n.times |i| { grid[i] = Int[,] {it.size=n} }
    return grid
  }

  Int[][] zig(Int n)
  {
    grid := makeSquareArray(n)

    move := |Int i, Int j->Point|
    { return j < n - 1 ? Point(i <= 0 ? 0 : i-1, j+1) : Point(i+1, j) }
    pt := Point(0,0)
    (n*n).times |i| {
      grid[pt.y][pt.x] = i
      if ((pt.x+pt.y)%2 != 0) pt = move(pt.x,pt.y)
      else {tmp:= move(pt.y,pt.x); pt = Point(tmp.y, tmp.x) }
    }
    return grid
  }

  public static Int[][] zag(Int size)
  {
    data := makeSquareArray(size)

    Int i := 1
    Int j := 1
    for (element:=0; element < size * size; element++)
    {
      data[i - 1][j - 1] = element
      if((i + j) % 2 == 0) {
        // Even stripes
        if (j < size) {
          j++
        } else {
          i += 2
        }
        if (i > 1) {
          i--
        }
      } else {
        // Odd stripes
        if (i < size) {
          i++;
        } else {
          j += 2
        }
        if (j > 1) {
          j--
        }
      }
    }
    return data;
  }

  Void print(Int[][] data)
  {
    data.each |row|
    {
      buf := StrBuf()
      row.each |num|
      {
        buf.add(num.toStr.justr(3))
      }
      echo(buf)
    }
  }

  Void main()
  {
    echo("zig method:")
    print(zig(8))
    echo("\nzag method:")
    print(zag(8))
  }
}


// library: math: get: task: door: open: close100 <description></description> <version control></version control> <version>1.0.0.0.11</version> <version control></version control> (filenamemacro=getmaocl.s) [<Program>] [<Research>] [kn, ri, mo, 31-12-2012 22:03:16]
PROC PROCMathGetTaskDoorOpenClose( INTEGER doorMaxI, INTEGER passMaxI )
 // e.g. PROC Main()
 // e.g.  PROCMathGetTaskDoorOpenClose( 100, 100 )
 // e.g. END
 // e.g.
 // e.g. <F12> Main()
 //
 // ===
 //
 // The output will be:
 //
 // door 1 is open
 // door 4 is open
 // door 9 is open
 // door 16 is open
 // door 25 is open
 // door 36 is open
 // door 49 is open
 // door 64 is open
 // door 81 is open
 // door 100 is open
 // all other doors are closed
 //
 // ===
 //
 INTEGER passMinI = 1
 INTEGER passI = 0
 //
 INTEGER doorminI = 1
 INTEGER doorI = 0
 //
 STRING s[255] = ""
 //
 INTEGER bufferI = 0
 //
 PushPosition()
 bufferI = CreateTempBuffer()
 PopPosition()
 //
 FOR doorI = doorMinI TO doorMaxI
  //
  SetGlobalInt( Format( "doorsI", doorI ), 0 )
  //
 ENDFOR
 //
 FOR passI = passMinI TO passMaxI
  //
  doorI = passI - passI
  //
  REPEAT
   //
   doorI = doorI + passI
   //
   SetGlobalInt( Format( "doorsI", doorI ), NOT( GetGlobalInt( Format( "doorsI", doorI ) ) ) )
   //
  UNTIL ( doorI >= doorMaxI )
  //
 ENDFOR
 //
 FOR doorI = doorMinI TO doorMaxI
  //
  IF ( GetGlobalInt( Format( "doorsI", doorI ) ) > 0 )
   //
   s = "open"
   //
   AddLine( Format( "door", " ", doorI, " ", "is", " ", s ), bufferI )
   //
  ELSE
   //
   s = "closed"
   //
  ENDIF
  //
 ENDFOR
 //
 AddLine( "all other doors are closed", bufferI )
 //
 GotoBufferId( bufferI )
 //
END

PROC Main()
 PROCMathGetTaskDoorOpenClose( 100, 100 )
END


$$ MODE TUSCRIPT
DICT doors create
COMPILE
LOOP door=1,100
 LOOP pass=1,100
 SET go=MOD (door,pass)
 DICT doors lookup door,num,cnt,status
   IF (num==0) THEN
     SET status="open"
     DICT doors add  door,num,cnt,status
   ELSE
    IF (go==0) THEN
       IF (status=="closed") THEN
         SET status="open"
       ELSE
         SET status="closed"
       ENDIF
     DICT doors update door,num,cnt,status
     ENDIF
   ENDIF
 ENDLOOP
ENDLOOP
ENDCOMPILE
DICT doors unload door,num,cnt,status


0 value diag

: south  diag abs + cell+ ;

' cell+ value zig
' south value zag

: init ( n -- )
  1- cells negate to diag
  ['] cell+ to zig
  ['] south to zag ;

: swap-diag   zig zag to zig to zag ;

: put ( n addr -- n+1 addr )
  2dup !  swap 1+ swap ;

: turn ( addr -- addr+E/S )
  zig execute  swap-diag
  diag negate to diag ;

: zigzag ( matrix n -- )
  { n } n init
  0 swap
  n 1 ?do
    put turn
    i 0 do put diag + loop
  loop
  swap-diag
  n 1 ?do
    put turn
    n i 1+ ?do put diag + loop
  loop
  ! ;

: .matrix ( n matrix -- )
  over 0 do
    cr
    over 0 do
      dup @ 3 .r cell+
    loop
  loop 2drop ;

: test ( n -- )  here over zigzag here .matrix ;
5 test
  0  1  5  6 14
  2  4  7 13 15
  3  8 12 16 21
  9 11 17 20 22
 10 18 19 23 24 ok


PROGRAM ZIGZAG

  IMPLICIT NONE
    INTEGER, PARAMETER :: size = 5
    INTEGER :: zzarray(size,size), x(size*size), y(size*size), i, j

    ! index arrays
    x = (/ ((j, i = 1, size), j = 1, size) /)
    y = (/ ((i, i = 1, size), j = 1, size) /)

    ! Sort indices
    DO i = 2, size*size
       j = i - 1
       DO WHILE (j>=1 .AND. (x(j)+y(j)) > (x(i)+y(i)))
          j = j - 1
       END DO
       x(j+1:i) = cshift(x(j+1:i),-1)
       y(j+1:i) = cshift(y(j+1:i),-1)
    END DO

    ! Create zig zag array
    DO i = 1, size*size
       IF (MOD(x(i)+y(i), 2) == 0) THEN
          zzarray(x(i),y(i)) = i - 1
       ELSE
          zzarray(y(i),x(i)) = i - 1
       END IF
    END DO

    ! Print zig zag array
    DO j = 1, size
       DO i = 1, size
          WRITE(*, "(I5)", ADVANCE="NO") zzarray(i,j)
       END DO
       WRITE(*,*)
    END DO

 END PROGRAM ZIGZAG


    PRINT "Open doors are:"

    LET I = 1
10  IF I = 100 THEN END
    rem funcion SQR
    LET B = I*I
    rem funcion MODULO
    LET A = I - (I / B) * B
    IF A < 11 THEN PRINT B
    LET I = I + 1
    GOTO 10


interface Door {
  id: number;
  open: boolean;
}

function doors(): Door[] {
  var Doors: Door[] = [];

  for (let i = 1; i <= 100; i++) {
    Doors.push({id: i, open: false});
  }

  for (let secuence of Doors) {
    for (let door of Doors) {
      if (door.id % secuence.id == 0) {
        door.open = !door.open;
      }
    }
  }

  return Doors.filter(a => a.open);
}


' FB 1.05.0 Win64

Dim As Integer n

Do
  Input "Enter size of matrix "; n
Loop Until n > 0

Dim zigzag(1 To n, 1 To n) As Integer '' all zero by default

' enter the numbers 0 to (n^2 - 1) in the matrix's anti-diagonals
zigzag(1, 1) = 0
If n > 1 Then
  Dim As Integer row = 0, col = 3
  Dim As Boolean down = true, increment = true
  Dim As Integer i = 0, j = 2, k
  Do
    If down Then
      For k = 1 To j
        i += 1
        row += 1
        col -= 1
        zigzag(row, col) = i
      Next
      down = false
    Else
      For k = 1 To j
        i += 1
        row -= 1
        col += 1
        zigzag(row, col) = i
      Next
      down = true
    End If
    If increment Then
      j += 1
      If j > n Then
        j = n - 1
        increment = false
      End If
    Else
      j -= 1
      If j = 0 Then Exit Do
    End If
    If down AndAlso increment Then
      col += 2
      row -= 1
    ElseIf Not Down AndAlso increment Then
      row += 2
      col -= 1
    ElseIf down AndAlso Not increment Then
      col += 1
    Else '' Not down AndAlso NotIncrement
      row += 1
    End If
  Loop
End If

' print zigzag matrix if n < 20
Print
If n < 20 Then
  For i As Integer = 1 To n
    For j As Integer = 1 To n
      Print Using "####"; zigzag(i, j);
    Next j
    Print
  Next i
Else
  Print "Matrix is too big to display on 80 column console"
End If

Print
Print "Press any key to quit"
Sleep


(defun hyaku-mai-tobira ()
  (let ((doors (vector 100)))
    (each ((i (range 0 99)))
      (each ((j (range i 99 (+ i 1))))
        (flip [doors j])))
    doors))

(each ((counter (range 1))
       (door (hyaku-mai-tobira)))
  (put-line `door @counter is @(if door "open" "closed")`))


FOR p = 1 TO 100
  FOR d = p TO 100 STEP p
    @(d) = @(d) = 0
  NEXT d
NEXT p

FOR d= 1 TO 100
  IF @(d) PRINT "Door ";d;" is open"
NEXT d


package main

import (
    "fmt"
    "strconv"
)

func zz(n int) []int {
    r := make([]int, n*n)
    i := 0
    n2 := n * 2
    for d := 1; d <= n2; d++ {
        x := d - n
        if x < 0 {
            x = 0
        }
        y := d - 1
        if y > n-1 {
            y = n - 1
        }
        j := n2 - d
        if j > d {
            j = d
        }
        for k := 0; k < j; k++ {
            if d&1 == 0 {
                r[(x+k)*n+y-k] = i
            } else {
                r[(y-k)*n+x+k] = i
            }
            i++
        }
    }

    return r
}

func main() {
    const n = 5
    w := len(strconv.Itoa(n*n - 1))
    for i, e := range zz(n) {
        fmt.Printf("%*d ", w, e)
        if i%n == n-1 {
            fmt.Println("")
        }
    }
}


entry LP_DO_IT

    variables
        string  V_DOORS
        boolean V_DOOR_STATE
        string  V_DOOR_STATE_S
        numeric V_IDX
        numeric V_TOTAL_DOORS
        string  V_DOOR_STATE_LIST
        numeric V_LOOP_COUNT
    endvariables

    V_TOTAL_DOORS = 100
    putitem V_DOORS, V_TOTAL_DOORS, 0

    V_DOORS = $replace (V_DOORS, 1, "·;", "·;0", -1)

    putitem/id V_DOOR_STATE_LIST, "1", "Open"
    putitem/id V_DOOR_STATE_LIST, "0", "Close"

    V_LOOP_COUNT = 1
    while (V_LOOP_COUNT <= V_TOTAL_DOORS)
        V_IDX = 0
        V_IDX = V_IDX + V_LOOP_COUNT

        getitem V_DOOR_STATE, V_DOORS, V_IDX
        while (V_IDX <= V_TOTAL_DOORS)

            V_DOOR_STATE = !V_DOOR_STATE
            getitem/id V_DOOR_STATE_S, V_DOOR_STATE_LIST, $number(V_DOOR_STATE)
            putitem V_DOORS, V_IDX, V_DOOR_STATE

            V_IDX = V_IDX + V_LOOP_COUNT
            getitem V_DOOR_STATE, V_DOORS, V_IDX
        endwhile

        V_LOOP_COUNT = V_LOOP_COUNT + 1

    endwhile

    V_IDX = 1
    getitem V_DOOR_STATE, V_DOORS, V_IDX
    while (V_IDX <= V_TOTAL_DOORS)
        getitem/id V_DOOR_STATE_S, V_DOOR_STATE_LIST, $number(V_DOOR_STATE)
        if (V_DOOR_STATE)
            putmess "Door %%V_IDX%%% is finally %%V_DOOR_STATE_S%%%"
        endif

        V_IDX = V_IDX + 1
        getitem V_DOOR_STATE, V_DOORS, V_IDX
    endwhile

end ; LP_DO_IT


hundredDoors : [Boolean]
hundredDoors =
  toggleEachNth : Nat -> [Boolean] -> [Boolean]
  toggleEachNth n doors =
    go counter = cases
      [] -> []
      (d +: ds) -> if counter == n
        then (not d) +: go 1 ds
        else d +: go (counter+1) ds

    go 1 doors

  foldr toggleEachNth (replicate 100 'false) (range 1 101)

results = filterMap (cases (open, ix) -> if open then Some (ix+1) else None)
                    (indexed hundredDoors)


def zz = { n ->
  grid = new int[n][n]
  i = 0
  for (d in 1..n*2) {
    (x, y) = [Math.max(0, d - n), Math.min(n - 1, d - 1)]
     Math.min(d, n*2 - d).times {
       grid[d%2?y-it:x+it][d%2?x+it:y-it] = i++;
      }
  }
  grid
}


#! /bin/bash

declare -a doors
for((i=1; i <= 100; i++)); do
    doors[$i]=0
done

for((i=1; i <= 100; i++)); do
    for((j=i; j <= 100; j += i)); do
	echo $i $j
	doors[$j]=$(( doors[j] ^ 1 ))
    done
done

for((i=1; i <= 100; i++)); do
    if [[ ${doors[$i]} -eq 0 ]]; then
	op="closed"
    else
	op="open"
    fi
    echo $i $op
done


import Data.Array (Array, array, bounds, range, (!))
import Text.Printf (printf)
import Data.List (sortBy)

compZig :: (Int, Int) -> (Int, Int) -> Ordering
compZig (x, y) (x_, y_) = compare (x + y) (x_ + y_) <> go x y
  where
    go x y
      | even (x + y) = compare x x_
      | otherwise = compare y y_

zigZag :: (Int, Int) -> Array (Int, Int) Int
zigZag upper = array b $ zip (sortBy compZig (range b)) [0 ..]
  where
    b = ((0, 0), upper)


#
# 100 doors
#

decl int i j
decl boolean<> doors

# append 101 boolean values to doors stream
for (set i 0) (or (< i 100) (= i 100)) (inc i)
        append false doors
end for

# loop through, opening and closing doors
for (set i 1) (or (< i 100) (= i 100)) (inc i)
        for (set j i) (or (< j 100) (= j 100)) (inc j)
                if (= (mod j i) 0)
                        set doors<j> (not doors<j>)
                end if
        end for
end for

# loop through and output which doors are open
for (set i 1) (or (< i 100) (= i 100)) (inc i)
        out "Door " i ": " console
        if doors<i>
                out "open" endl console
        else
                out "closed" endl console
        end if
end if


#import std
#import nat

doors = 0!* iota 100

pass("n","d") = remainder\"n"?l(~&r,not ~&r)* num "d"

#cast %nL

main = ~&rFlS num pass=>doors nrange(100,1)


procedure main(args)
   n := integer(!args) | 5
   every !(A := list(n)) := list(n)
   A := zigzag(A)
   show(A)
end

procedure show(A)
    every writes(right(!A,5) | "\n")
end

procedure zigzag(A)
    x := [0,0]
    every i := 0 to (*A^2 -1) do {
        x := nextIndices(*A, x)
        A[x[1]][x[2]] := i
        }
    return A
end

procedure nextIndices(n, x)
    return if (x[1]+x[2])%2 = 0
           then if x[2] = n then [x[1]+1, x[2]] else [max(1, x[1]-1), x[2]+1]
           else if x[1] = n then [x[1], x[2]+1] else [x[1]+1, max(1, x[2]-1)]
end


···
http://rosettacode.org/wiki/100_doors
···
■ HundredDoors
  § static
    ▶ main
    • args⦂ String[]
      open⦂   boolean: true
      closed⦂ boolean: false
      doors⦂  boolean[1+100] · all initially closed
      🔁 pass from 1 to 100
         ∀ visited ∈ pass‥100 by pass
         · toggle the visited doors
           if the doors[visited] are closed
              let the doors[visited] be open
           else
              let the doors[visited] be closed
      for each door #n in doors⦂ boolean
        if the door is open
           System.out.println "Door #⸨n⸩ is open."


int main() {
	bool doors_open[101];
	for(int i = 1; i < doors_open.length; i++) {
		for(int j = 1; i*j < doors_open.length; j++) {
			doors_open[i*j] = !doors_open[i*j];
		}
		stdout.printf("%d: %s\n", i, (doors_open[i] ? "open" : "closed"));
	}
	return 0;
}


100 PROGRAM "ZigZag.bas"
110 LET SIZE=5
120 NUMERIC A(1 TO SIZE,1 TO SIZE)
130 LET I,J=1
140 FOR E=0 TO SIZE^2-1
150   LET A(I,J)=E
160   IF ((I+J) BAND 1)=0 THEN
170     IF J<SIZE THEN
180       LET J=J+1
190     ELSE
200       LET I=I+2
210     END IF
220     IF I>1 THEN LET I=I-1
230   ELSE
240     IF I<SIZE THEN
250       LET I=I+1
260     ELSE
270       LET J=J+2
280     END IF
290     IF J>1 THEN LET J=J-1
300   END IF
310 NEXT
320 FOR ROW=1 TO SIZE
330   FOR COL=1 TO SIZE
340     PRINT USING " ##":A(ROW,COL);
350   NEXT
360   PRINT
370 NEXT


Sub Rosetta_100Doors()
Dim Door(100) As Boolean, i As Integer, j As Integer
For i = 1 To 100 Step 1
    For j = i To 100 Step i
        Door(j) = Not Door(j)
    Next j
    If Door(i) = True Then
        Debug.Print "Door " & i & " is Open"
    Else
        Debug.Print "Door " & i & " is Closed"
    End If
Next i
End Sub
<!-- /lang -->

*** USE THIS ONE, SEE COMMENTED LINES, DONT KNOW WHY EVERYBODY FOLLOWED OTHERS ANSWERS AND CODED THE PROBLEM DIFFERENTLY ***
*** ALWAYS USE AND TEST A READABLE, EASY TO COMPREHEND CODING BEFORE 'OPTIMIZING' YOUR CODE AND TEST THE 'OPTIMIZED' CODE AGAINST THE 'READABLE' ONE.
Panikkos Savvides.

Sub Rosetta_100Doors2()
Dim Door(100) As Boolean, i As Integer, j As Integer
Dim strAns As String
' There are 100 doors in a row that are all initially closed.
' You make 100 passes by the doors.
For j = 1 To 100
    ' The first time through, visit every door and toggle the door
    ' (if the door is closed, open it; if it is open, close it).
    For i = 1 To 100 Step 1
      Door(i) = Not Door(i)
    Next i
    ' The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
    For i = 2 To 100 Step 2
      Door(i) = Not Door(i)
    Next i
    ' The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
    For i = 3 To 100 Step 3
      Door(i) = Not Door(i)
    Next i
Next j

For j = 1 To 100
    If Door(j) = True Then
        strAns = j & strAns & ", "
    End If
Next j

If Right(strAns, 2) = ", " Then strAns = Left(strAns, Len(strAns) - 2)
If Len(strAns) = 0 Then strAns = "0"
Debug.Print "Doors [" & strAns & "] are open, the rest are closed."
' Doors [0] are open, the rest are closed., AKA ZERO DOORS OPEN
End Sub


public static int[][] Zig_Zag(final int size)
{
 int[][] data = new int[size][size];
 int i = 1;
 int j = 1;
 for (int element = 0; element < size * size; element++)
 {
  data[i - 1][j - 1] = element;
  if ((i + j) % 2 == 0)
  {
   // Even stripes
   if (j < size)
    j++;
   else
    i+= 2;
   if (i > 1)
    i--;
  }
  else
  {
   // Odd stripes
   if (i < size)
    i++;
   else
    j+= 2;
   if (j > 1)
    j--;
  }
 }
 return data;
}


Dim doorIsOpen(100), pass, currentDoor, text

For currentDoor = 0 To 99
	doorIsOpen(currentDoor) = False
Next

For pass = 0 To 99
	For currentDoor = pass To 99 Step pass + 1
		doorIsOpen(currentDoor) = Not doorIsOpen(currentDoor)
	Next
Next

For currentDoor = 0 To 99
	text = "Door #" & currentDoor + 1 & " is "
	If doorIsOpen(currentDoor) Then
		text = text & "open."
	Else
		text = text & "closed."
	End If
	WScript.Echo(text)
Next


Buf_Switch(Buf_Free)
Ins_Char('-', COUNT, 100)                      // All doors closed
for (#1 = 1; #1 <= 100; #1++) {
    for (#2 = #1; #2 <= 100; #2 += #1) {
        Goto_Col(#2)
        Ins_Char((Cur_Char^0x62), OVERWRITE)   // Toggle between '-' and 'O'
    }
}


function ZigZagMatrix(n) {
    this.height = n;
    this.width = n;

    this.mtx = [];
    for (var i = 0; i < n; i++)
        this.mtx[i] = [];

    var i=1, j=1;
    for (var e = 0; e < n*n; e++) {
        this.mtx[i-1][j-1] = e;
        if ((i + j) % 2 == 0) {
            // Even stripes
            if (j < n) j ++;
            else       i += 2;
            if (i > 1) i --;
        } else {
            // Odd stripes
            if (i < n) i ++;
            else       j += 2;
            if (j > 1) j --;
        }
    }
}
ZigZagMatrix.prototype = Matrix.prototype;

var z = new ZigZagMatrix(5);
print(z);
print();

z = new ZigZagMatrix(4);
print(z);


module main;
  integer i;

  initial begin
    $display("Las siguientes puertas están abiertas:");
    for (i=1; i<=10; i=i+1) if (i%i*i<11) $display(i*i);
    $finish ;
  end
endmodule


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program yahoosearch64.s   */

/* access RosettaCode.org and data extract       */
/* use openssl  for access to port 443 */
/* test openssl : package libssl-dev  */
/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

.equ TAILLEBUFFER,  500

.equ SSL_OP_NO_SSLv3,        0x02000000
.equ SSL_OP_NO_COMPRESSION,  0x00020000
.equ SSL_MODE_AUTO_RETRY,    0x00000004
.equ SSL_CTRL_MODE,          33

.equ BIO_C_SET_CONNECT,      100
.equ BIO_C_DO_STATE_MACHINE, 101
.equ BIO_C_SET_SSL,          109
.equ BIO_C_GET_SSL,          110

.equ LGBUFFERREQ,       512001

/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessDebutPgm:       .asciz "Début du programme. \n"
szRetourLigne:        .asciz "\n"
szMessFinOK:          .asciz "Fin normale du programme. \n"
szMessErreur:         .asciz "Erreur  !!!"
szMessExtractArea:    .asciz "Extraction = "
szNomSite1:           .asciz "search.yahoo.com:443"   // host name and port
szLibStart:           .asciz ">Rosetta Code"          // search string
szNomrepCertif:       .asciz "/pi/certificats"
szRequete1:           .asciz "GET /search?p=\"Rosettacode.org\"&b=1 HTTP/1.1 \r\nHost: search.yahoo.com\r\nConnection: keep-alive\r\nContent-Type: text/plain\r\n\r\n"
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
.align 4
sBufferreq:           .skip LGBUFFERREQ
szExtractArea:        .skip TAILLEBUFFER
stNewSSL:             .skip 200
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:
    ldr x0,qAdrszMessDebutPgm
    bl affichageMess                             // start message

    /* connexion host port 443 and send query */
    bl envoiRequete
    cmp x0,#-1
    beq 99f                                       // error ?

    bl analyseReponse

    ldr x0,qAdrszMessFinOK                        // end message
    bl affichageMess
    mov x0, #0                                    // return code ok
    b 100f
99:
    ldr x0,qAdrszMessErreur                       // error
    bl affichageMess
    mov x0, #1                                    // return code error
    b 100f
100:
    mov x8,EXIT                                   // program end
    svc 0                                         // system call
qAdrszMessDebutPgm:          .quad szMessDebutPgm
qAdrszMessFinOK:             .quad szMessFinOK
qAdrszMessErreur:            .quad szMessErreur

/*********************************************************/
/*   connexion host port 443 and send query            */
/*********************************************************/
envoiRequete:
    stp x1,lr,[sp,-16]!            // save  registers
    stp x2,x3,[sp,-16]!            // save  registers
    stp x4,x5,[sp,-16]!            // save  registers
    //*************************************
    // openSsl functions use              *
    //*************************************
                                    //init ssl
    bl OPENSSL_init_crypto
    bl ERR_load_BIO_strings
    mov x2, #0
    mov x1, #0
    mov x0, #2
    bl OPENSSL_init_crypto
    mov x2, #0
    mov x1, #0
    mov x0, #0
    bl OPENSSL_init_ssl
    cmp x0,#0
    blt erreur
    bl TLS_client_method
    bl SSL_CTX_new
    cmp x0,#0
    ble erreur
    mov x20,x0                       // save contex
    ldr x1,iFlag
    bl SSL_CTX_set_options
    mov x0,x20                      // contex
    mov x1,#0
    ldr x2,qAdrszNomrepCertif
    bl SSL_CTX_load_verify_locations
    cmp x0,#0
    ble erreur
    mov x0,x20                       // contex
    bl BIO_new_ssl_connect
    cmp x0,#0
    ble erreur
    mov x21,x0                       // save bio
    mov x1,#BIO_C_GET_SSL
    mov x2,#0
    ldr x3,qAdrstNewSSL
    bl BIO_ctrl
    ldr x0,qAdrstNewSSL
    ldr x0,[x0]
    mov x1,#SSL_CTRL_MODE
    mov x2,#SSL_MODE_AUTO_RETRY
    mov x3,#0
    bl SSL_ctrl
    mov x0,x21                       // bio
    mov x1,#BIO_C_SET_CONNECT
    mov x2,#0
    ldr x3,qAdrszNomSite1
    bl BIO_ctrl
    mov x0,x21                       // bio
    mov x1,#BIO_C_DO_STATE_MACHINE
    mov x2,#0
    mov x3,#0
    bl  BIO_ctrl
                                    // compute query length
    mov x2,#0
    ldr x1,qAdrszRequete1           // query
1:
    ldrb w0,[x1,x2]
    cmp x0,#0
    add x8,x2,1
    csel x2,x8,x2,ne
    bne 1b
                                    // send query
    mov x0,x21                       // bio
                                    // x1 = address query
                                    // x2 = length query
    mov x3,#0
    bl BIO_write                    // send query
    cmp x0,#0
    blt erreur
    ldr x22,qAdrsBufferreq           // buffer address
2:                                  // begin loop to read datas
    mov x0,x21                       // bio
    mov x1,x22                       // buffer address
    ldr x2,qLgBuffer
    mov x3,#0
    bl BIO_read
    cmp x0,#0
    ble 4f                          // error ou pb server
    add x22,x22,x0
    sub x2,x22,#8
    ldr x2,[x2]
    ldr x3,qCharEnd
    cmp x2,x3                       // text end ?
    beq 4f
    mov x1,#0xFFFFFF                // delay loop
3:
    subs x1,x1,1
    bgt 3b
    b 2b                            // loop read other chunk
4:                                  // read end
    //ldr x0,qAdrsBufferreq           // to display buffer response of the query
    //bl affichageMess
    mov x0, x21                      // close bio
    bl BIO_free_all
    mov x0,#0
    b 100f
erreur:                             // error display
    ldr x1,qAdrszMessErreur
    bl   afficheErreur
    mov x0,#-1                      // error code
    b 100f
100:
    ldp x4,x5,[sp],16              // restaur  2 registers
    ldp x2,x3,[sp],16              // restaur  2 registers
    ldp x1,lr,[sp],16              // restaur  2 registers
    ret                            // return to address lr x30
qAdrszRequete1:             .quad szRequete1
qAdrsBufferreq:             .quad sBufferreq
iFlag:                      .quad SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION
qAdrstNewSSL:               .quad stNewSSL
qAdrszNomSite1:             .quad szNomSite1
qAdrszNomrepCertif:         .quad szNomrepCertif
qCharEnd:                   .quad 0x0A0D0A0D300A0D0A
qLgBuffer:                  .quad LGBUFFERREQ - 1
/*********************************************************/
/*   response analyze                                    */
/*********************************************************/
analyseReponse:
    stp x1,lr,[sp,-16]!                       // save  registers
    stp x2,x3,[sp,-16]!                       // save  registers
    ldr x0,qAdrsBufferreq                     // buffer address
    ldr x1,qAdrszLibStart                     // key text address
    mov x2,#2                                 // occurence key text
    mov x3,#-11                               // offset
    ldr x4,qAdrszExtractArea                  // address result area
    bl extChaine
    cmp x0,#-1
    beq 99f
    ldr x0,qAdrszMessExtractArea
    bl affichageMess
    ldr x0,qAdrszExtractArea                  // résult display
    bl affichageMess
    ldr x0,qAdrszRetourLigne
    bl affichageMess
    b 100f
99:
    ldr x0,qAdrszMessErreur                   // error
    bl affichageMess
    mov x0, #-1                               // error return code
    b 100f
100:
    ldp x2,x3,[sp],16              // restaur  2 registers
    ldp x1,lr,[sp],16              // restaur  2 registers
    ret                            // return to address lr x30
qAdrszLibStart:                 .quad szLibStart
qAdrszExtractArea:              .quad szExtractArea
qAdrszMessExtractArea:          .quad szMessExtractArea
qAdrszRetourLigne:              .quad szRetourLigne
/*********************************************************/
/*   Text Extraction behind text key                     */
/*********************************************************/
/* x0  buffer address   */
/* x1  key text to search */
/* x2  number occurences to key text */
/* x3  offset */
/* x4  result address */
extChaine:
    stp x1,lr,[sp,-16]!  // save  registers
    stp x2,x3,[sp,-16]!  // save  registers
    stp x4,x5,[sp,-16]!  // save  registers
    stp x6,x7,[sp,-16]!  // save  registers
    mov x5,x0            // save buffer address
    mov x6,x1            // save key text
                         // compute text length
    mov x8,#0
1:                       // loop
    ldrb w0,[x5,x8]      // load a byte
    cmp x0,#0            // end ?
    add x9,x8,1
    csel x8,x9,x8,ne
    bne 1b               // no -> loop
    add x8,x8,x5            // compute text end

    mov x7,#0
2:                       // compute length text key
    ldrb w0,[x6,x7]
    cmp x0,#0
    add x9,x7,1
    csel x7,x9,x7,ne
    bne 2b

3:                       // loop to search niéme(x2)  key text
    mov x0,x5
    mov x1,x6
    bl rechercheSousChaine
    cmp x0,#0
    blt 100f
    subs x2,x2,1
    ble 31f
    add x5,x5,x0
    add x5,x5,x7
    b 3b
31:
    add x0,x0,x5           // add address text to index
    add x3,x3,x0           // add offset
    sub x3,x3,1
                        // and add length key text
    add x3,x3,x7
    cmp x3,x8           // > at text end
    bge 98f
    mov x0,0
4:                      // character loop copy
    ldrb w2,[x3,x0]
    strb w2,[x4,x0]
    cbz x2,99f           // text end ?  return zero
    cmp x0,48           // extraction length
    beq 5f
    add x0,x0,1
    b 4b                // and loop
5:
    mov x2,0            // store final zéro
    strb w2,[x4,x0]
    add x0,x0,1
    add x0,x0,x3        // x0 return the last position of extraction
                        // it is possible o search another text
    b 100f
98:
    mov x0,-1           // error
    b 100f
99:
    mov x0,0
100:
    ldp x6,x7,[sp],16   // restaur  2 registers
    ldp x4,x5,[sp],16   // restaur  2 registers
    ldp x2,x3,[sp],16   // restaur  2 registers
    ldp x1,lr,[sp],16   // restaur  2 registers
    ret                 // return to address lr x30
/******************************************************************/
/*   search substring in string                                   */
/******************************************************************/
/* x0 contains address string */
/* x1 contains address substring */
/* x0 return start index substring or -1 if not find */
rechercheSousChaine:
    stp x1,lr,[sp,-16]!                   // save  registers
    stp x2,x3,[sp,-16]!                   // save  registers
    stp x4,x5,[sp,-16]!                   // save  registers
    stp x6,x7,[sp,-16]!                   // save  registers
    mov x2,#0                             // index position string
    mov x3,#0                             // index position substring
    mov x6,#-1                            // search index
    ldrb w4,[x1,x3]                       // load first byte substring
    cbz x4,99f                             // zero final ?  error
1:
    ldrb w5,[x0,x2]                       // load string byte
    cbz x5,99f                            // zero final ?  yes -> not found
    cmp x5,x4                             // compare character two strings
    beq 2f
    mov x6,-1                             // not equal - > raz index
    mov x3,0                              // and raz byte counter
    ldrb w4,[x1,x3]                       // and load byte
    add x2,x2,1                           // and increment byte counter
    b 1b                                  // and loop
2:                                        // characters equal
    cmp x6,-1                            // first character equal ?
    csel x6,x2,x6,eq                      // yes -> start index in x6
    add x3,x3,1                           // increment substring counter
    ldrb w4,[x1,x3]                       // and load next byte
    cbz x4,3f                             // zero final ?  yes -> search end
    add x2,x2,1                           // else increment string index
    b 1b                                  // and loop
3:
    mov x0,x6                             // return start index substring in the string
    b 100f
99:
    mov x0,-1                             // not found
100:
    ldp x6,x7,[sp],16                     // restaur  2 registers
    ldp x4,x5,[sp],16                     // restaur  2 registers
    ldp x2,x3,[sp],16                     // restaur  2 registers
    ldp x1,lr,[sp],16                     // restaur  2 registers
    ret                                   // return to address lr x30
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


(*
    From the library.
*)
DEFINE reverse == [] swap shunt;
       shunt   == [swons] step.

(*
    Split according to the parameter given.
*)
DEFINE take-drop  == [dup] swap dup [[] cons [take swap] concat concat] dip []
                     cons concat [drop] concat.

(*
    Take the first of a list of lists.
*)
DEFINE take-first == [] cons 3 [dup] times [dup] swap concat [take [first] map
                     swap dup] concat swap concat [drop swap] concat swap
                     concat [take [rest] step []] concat swap concat [[cons]
                     times swap concat 1 drop] concat.

DEFINE zigzag ==

(*
    Use take-drop to generate a list of lists.
*)
4 [dup] times 1 swap from-to-list swap pred 1 swap from-to-list reverse concat
swap dup * pred 0 swap from-to-list swap [take-drop i] step [pop list] [cons]
while

(*
    The odd numbers must be modified with reverse.
*)
[dup size 2 div popd [1 =] [pop reverse] [pop] ifte] map

(*
    Take the first of the first of n lists.
*)
swap dup take-first [i] cons times pop

(*
    Merge the n separate lists.
*)
[] [pop list] [cons] while

(*
    And print them.
*)
swap dup * pred 'd 1 1 format size succ [] cons 'd swons [1 format putchars]
concat [step '\n putch] cons step.

11 zigzag.


# Create an m x n matrix
 def matrix(m; n; init):
   if m == 0 then []
   elif m == 1 then [range(0;n)] | map(init)
   elif m > 0 then
     matrix(1;n;init) as $row
     | [range(0;m)] | map( $row )
   else error("matrix\(m);_;_) invalid")
   end ;

# Print a matrix neatly, each cell occupying n spaces
def neatly(n):
  def right: tostring | ( " " * (n-length) + .);
  . as $in
  | length as $length
  | reduce range (0;$length) as $i
      (""; . + reduce range(0;$length) as $j
      (""; "\(.) \($in[$i][$j] | right )" ) + "\n" ) ;


library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

entity DOORS is
	port (CLK: in std_logic; OUTPUT: out std_logic_vector(1 to 100));
end DOORS;

architecture Behavioral of DOORS is
begin
	process (CLK)
	variable TEMP: std_logic_vector(1 to 100);
	begin
		--setup closed doors
		TEMP := (others => '0');

		--looping through
		for i in 1 to TEMP'length loop
			for j in i to TEMP'length loop
				if (j mod i) = 0 then
					TEMP(j) := not TEMP(j);
				end if;
			end loop;
		end loop;

		--assign output
		OUTPUT <= TEMP;
	end process;
end Behavioral;


/* ARM assembly Raspberry PI  */
/*  program yahoosearch.s   */
/* access RosettaCode.org and data extract       */
/* use openssl  for access to port 443 */
/* test openssl : package libssl-dev  */

/* REMARK 1 : this program use routines in a include file
   see task Include a file language arm assembly
   for the routine affichageMess conversion10
   see at end of this program the instruction include */

/*******************************************/
/* Constantes                              */
/*******************************************/
.equ STDOUT, 1           @ Linux output console
.equ EXIT,   1           @ Linux syscall
.equ WRITE,  4           @ Linux syscall
.equ BRK,    0x2d        @ Linux syscall
.equ CHARPOS,     '@'

.equ EXIT,          1
.equ TAILLEBUFFER,  500

.equ SSL_OP_NO_SSLv3,        0x02000000
.equ SSL_OP_NO_COMPRESSION,  0x00020000
.equ SSL_MODE_AUTO_RETRY,    0x00000004
.equ SSL_CTRL_MODE,          33

.equ BIO_C_SET_CONNECT,      100
.equ BIO_C_DO_STATE_MACHINE, 101
.equ BIO_C_SET_SSL,          109
.equ BIO_C_GET_SSL,          110

.equ LGBUFFERREQ,       512001
.equ LGBUFFER2,         128001

/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessDebutPgm:       .asciz "Début du programme. \n"
szRetourLigne:        .asciz "\n"
szMessFinOK:          .asciz "Fin normale du programme. \n"
szMessErreur:         .asciz "Erreur  !!!"
szMessExtractArea:    .asciz "Extraction = "
szNomSite1:           .asciz "search.yahoo.com:443"   @ host name and port
szLibStart:           .asciz ">Rosetta Code"          @ search string
szNomrepCertif:       .asciz "/pi/certificats"
szRequete1:           .asciz "GET /search?p=\"Rosettacode.org\"&b=1 HTTP/1.1 \r\nHost: search.yahoo.com\r\nConnection: keep-alive\r\nContent-Type: text/plain\r\n\r\n"
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
.align 4
sBufferreq:           .skip LGBUFFERREQ
szExtractArea:        .skip TAILLEBUFFER
stNewSSL:             .skip 200
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:
    ldr r0,iAdrszMessDebutPgm
    bl affichageMess                             @ start message

    /* connexion host port 443 and send query */
    bl envoiRequete
    cmp r0,#-1
    beq 99f                                       @ error ?

    bl analyseReponse

    ldr r0,iAdrszMessFinOK                        @ end message
    bl affichageMess
    mov r0, #0                                    @ return code ok
    b 100f
99:
    ldr r0,iAdrszMessErreur                       @ error
    bl affichageMess
    mov r0, #1                                    @ return code error
    b 100f
100:
    mov r7,#EXIT                                  @ program end
    svc #0                                        @ system call
iAdrszMessDebutPgm:          .int szMessDebutPgm
iAdrszMessFinOK:             .int szMessFinOK
iAdrszMessErreur:            .int szMessErreur

/*********************************************************/
/*   connexion host port 443 and send query            */
/*********************************************************/
envoiRequete:
    push {r2-r8,lr}                 @ save registers
    @*************************************
    @ openSsl functions use              *
    @*************************************
                                    @init ssl
    bl OPENSSL_init_crypto
    bl ERR_load_BIO_strings
    mov r2, #0
    mov r1, #0
    mov r0, #2
    bl OPENSSL_init_crypto
    mov r2, #0
    mov r1, #0
    mov r0, #0
    bl OPENSSL_init_ssl
    cmp r0,#0
    blt erreur
    bl TLS_client_method
    bl SSL_CTX_new
    cmp r0,#0
    ble erreur
    mov r6,r0                       @ save ctx
    ldr r1,iFlag
    bl SSL_CTX_set_options
    mov r0,r6
    mov r1,#0
    ldr r2,iAdrszNomrepCertif
    bl SSL_CTX_load_verify_locations
    cmp r0,#0
    ble erreur
    mov r0,r6
    bl BIO_new_ssl_connect
    cmp r0,#0
    ble erreur
    mov r5,r0                       @ save bio
    mov r1,#BIO_C_GET_SSL
    mov r2,#0
    ldr r3,iAdrstNewSSL
    bl BIO_ctrl
    ldr r0,iAdrstNewSSL
    ldr r0,[r0]
    mov r1,#SSL_CTRL_MODE
    mov r2,#SSL_MODE_AUTO_RETRY
    mov r3,#0
    bl SSL_ctrl
    mov r0,r5                       @ bio
    mov r1,#BIO_C_SET_CONNECT
    mov r2,#0
    ldr r3,iAdrszNomSite1
    bl BIO_ctrl
    mov r0,r5                       @ bio
    mov r1,#BIO_C_DO_STATE_MACHINE
    mov r2,#0
    mov r3,#0
    bl  BIO_ctrl
                                    @ compute query length
    mov r2,#0
    ldr r1,iAdrszRequete1           @ query
1:
    ldrb r0,[r1,r2]
    cmp r0,#0
    addne r2,#1
    bne 1b
                                    @ send query
    mov r0,r5                       @ bio
                                    @ r1 = address query
                                    @ r2 = length query
    mov r3,#0
    bl BIO_write                    @ send query
    cmp r0,#0
    blt erreur
    ldr r7,iAdrsBufferreq           @ buffer address
2:                                  @ begin loop to read datas
    mov r0,r5                       @ bio
    mov r1,r7                       @ buffer address
    mov r2,#LGBUFFERREQ - 1
    mov r3,#0
    bl BIO_read
    cmp r0,#0
    ble 4f                          @ error ou pb server
    add r7,r0
    sub r2,r7,#6
    ldr r2,[r2]
    ldr r3,iCharEnd
    cmp r2,r3                       @ text end ?
    beq 4f
    mov r1,#0xFFFFFF                @ delay loop
3:
    subs r1,#1
    bgt 3b
    b 2b                            @ loop read other chunk
4:                                  @ read end
    //ldr r0,iAdrsBufferreq           @ to display buffer response of the query
    //bl affichageMess
    mov r0, r5                      @ close bio
    bl BIO_free_all
    mov r0,#0
    b 100f
erreur:                             @ error display
    ldr r1,iAdrszMessErreur
    bl   afficheerreur
    mov r0,#-1                      @ error code
    b 100f
100:
    pop {r2-r8,lr}                  @ restaur registers
    bx lr
iAdrszRequete1:             .int szRequete1
iAdrsBufferreq:             .int sBufferreq
iFlag:                      .int SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION
iAdrstNewSSL:               .int stNewSSL
iAdrszNomSite1:             .int szNomSite1
iAdrszNomrepCertif:         .int szNomrepCertif
iCharEnd:                   .int 0x0A0D300A
/*********************************************************/
/*   response analyze                                    */
/*********************************************************/
analyseReponse:
    push {r1-r4,lr}                           @ save registers
    ldr r0,iAdrsBufferreq                     @ buffer address
    ldr r1,iAdrszLibStart                     @ key text address
    mov r2,#2                                 @ occurence key text
    mov r3,#-11                               @ offset
    ldr r4,iAdrszExtractArea                  @ address result area
    bl extChaine
    cmp r0,#-1
    beq 99f
    ldr r0,iAdrszMessExtractArea
    bl affichageMess
    ldr r0,iAdrszExtractArea                  @ résult display
    bl affichageMess
    ldr r0,iAdrszRetourLigne
    bl affichageMess
    b 100f
99:
    ldr r0,iAdrszMessErreur                   @ error
    bl affichageMess
    mov r0, #-1                               @ error return code
    b 100f
100:
    pop {r1-r4,lr}                            @ restaur registers
    bx lr
iAdrszLibStart:                 .int szLibStart
iAdrszExtractArea:              .int szExtractArea
iAdrszMessExtractArea:          .int szMessExtractArea
iAdrszRetourLigne:              .int szRetourLigne
/*********************************************************/
/*   Text Extraction behind text key                     */
/*********************************************************/
/* r0  buffer address   */
/* r1  key text to search */
/* r2  number occurences to key text */
/* r3  offset */
/* r4  result address */
extChaine:
    push {r2-r8,lr}      @ save registers
    mov r5,r0            @ save buffer address
    mov r6,r1            @ save key text
                         @ compute text length
    mov r7,#0
1:                       @ loop
    ldrb r0,[r5,r7]      @ load a byte
    cmp r0,#0            @ end ?
    addne r7,#1          @ no -> loop
    bne 1b
    add r7,r5            @ compute text end

    mov r8,#0
2:                       @ compute length text key
    ldrb r0,[r6,r8]
    cmp r0,#0
    addne r8,#1
    bne 2b

3:                       @ loop to search nième(r2)  key text
    mov r0,r5
    mov r1,r6
    bl rechercheSousChaine
    cmp r0,#0
    blt 100f
    subs r2,#1
    addgt r5,r0
    addgt r5,r8
    bgt 3b
    add r0,r5           @ add address text to index
    add r3,r0           @ add offset
    sub r3,#1
                        @ and add length key text
    add r3,r8
    cmp r3,r7           @ > at text end
    movge r0,#-1        @ yes -> error
    bge 100f
    mov r0,#0
4:                      @ character loop copy
    ldrb r2,[r3,r0]
    strb r2,[r4,r0]
    cmp r2,#0           @ text end ?
    moveq r0,#0         @ return zero
    beq 100f
    cmp r0,#48          @ extraction length
    beq 5f
    add r0,#1
    b 4b                @ and loop
5:
    mov r2,#0           @ store final zéro
    strb r2,[r4,r0]
    add r0,#1
    add r0,r3           @ r0 return the last position of extraction
                        @ it is possible o search another text
100:
   	pop {r2-r8,lr}      @ restaur registers
    bx lr

/******************************************************************/
/*   search substring in string                                   */
/******************************************************************/
/* r0 contains address string */
/* r1 contains address substring */
/* r0 return start index substring or -1 if not find */
rechercheSousChaine:
    push {r1-r6,lr}                       @ save registers
    mov r2,#0                             @ index position string
    mov r3,#0                             @ index position substring
    mov r6,#-1                            @ search index
    ldrb r4,[r1,r3]                       @ load first byte substring
    cmp r4,#0                             @ zero final ?
    moveq r0,#-1                          @ error
    beq 100f
1:
    ldrb r5,[r0,r2]                       @ load string byte
    cmp r5,#0                             @ zero final ?
    moveq r0,#-1                          @ yes -> not find
    beq 100f
    cmp r5,r4                             @ compare character two strings
    beq 2f
    mov r6,#-1                            @ not equal - > raz index
    mov r3,#0                             @ and raz byte counter
    ldrb r4,[r1,r3]                       @ and load byte
    add r2,#1                             @ and increment byte counter
    b 1b                                  @ and loop
2:                                        @ characters equal
    cmp r6,#-1                            @ first character equal ?
    moveq r6,r2                           @ yes -> start index in r6
    add r3,#1                             @ increment substring counter
    ldrb r4,[r1,r3]                       @ and load next byte
    cmp r4,#0                             @ zero final ?
    beq 3f                                @ yes -> search end
    add r2,#1                             @ else increment string index
    b 1b                                  @ and loop
3:
    mov r0,r6                             @ return start index substring in the string
100:
    pop {r1-r6,lr}                        @ restaur registres
    bx lr

/***************************************************/
/*      ROUTINES INCLUDE                 */
/***************************************************/
.include "../affichage.inc"


function zigzag_matrix(n::Int)
    matrix = zeros(Int, n, n)
    x, y = 1, 1
    for i = 0:(n*n-1)
        matrix[y,x] = i
        if (x + y) % 2 == 0
            # Even stripes
            if x < n
                x += 1
                y -= (y > 1)
            else
                y += 1
            end
        else
            # Odd stripes
            if y < n
                x -= (x > 1)
                y += 1
            else
                x += 1
            end
        end
    end
    return matrix
end


include ..\Utilitys.tlhy

%Size 5 !Size
0 ( $Size dup ) dim

%i 1 !i %j 1 !j

$Size 2 power [
    1 -
    ( $i $j ) set
    $i $j + 1 band 0 == (
        [$j $Size < ( [$j 1 + !j] [$i 2 + !i] ) if
        $i 1 > [ $i 1 - !i] if ]
        [$i $Size < ( [$i 1 + !i] [$j 2 + !j] ) if
        $j 1 > [ $j 1 - !j] if ]
    ) if
] for

$Size [
    %row !row
    $Size [
        %col !col
        ( $row $col ) get tostr 32 32 chain chain 1 3 slice print drop
    ] for
    nl
] for

nl "End " input


Public Sub Doors100()
  ' the state of a door is represented by the data type boolean (false = door closed, true = door opened)
  Dim doorstate(1 To 100) As Boolean ' the doorstate()-array is initialized by VB with value 'false'
  Dim i As Long, j As Long

  For i = 1 To 100
      For j = i To 100 Step i
          doorstate(j) = Not doorstate(j)
      Next j
  Next i

  Debug.Print "The following doors are open:"
  For i = 1 To 100
      ' print number if door is openend
      If doorstate(i) Then Debug.Print CStr(i)
  Next i
End Sub


test:
yahooSearch("test", 1)
yahooSearch("test", 2)
return

yahooSearch(query, page)
{
  global
  start := ((page - 1) * 10) + 1
  filedelete, search.txt
  urldownloadtofile, % "http://search.yahoo.com/search?p=" . query
  . "&b=" . start, search.txt
  fileread, content, search.txt
  reg = (.+?)

(.+?)
(.+?)

  index := found := 1
  while (found := regexmatch(content, reg, self, found + 1))
  {
    msgbox % title%A_Index% := fix(self1)
    content%A_Index% := fix(self2)
    url%A_Index% := fix(self3)
  }
}

fix(url)
{
if pos := instr(url, "

")
StringLeft, url, url, pos - 1
url := regexreplace(url, "<.*?>")
return url
}


using System;
using System.Net;
using System.Text.RegularExpressions;
using System.Collections.Generic;

class YahooSearch {
    private string query;
    private string content;
    private int page;

    const string yahoo = "http://search.yahoo.com/search?";

    public YahooSearch(string query) : this(query, 0) { }

    public YahooSearch(string query, int page) {
        this.query = query;
        this.page = page;
        this.content = new WebClient()
            .DownloadString(
                string.Format(yahoo + "p={0}&b={1}", query, this.page * 10 + 1)
            );
    }

    public YahooResult[] Results {
        get {
            List<YahooResult> results = new List<YahooResult>();

            Func<string, string, string> substringBefore = (str, before) =>
            {
                int iHref = str.IndexOf(before);
                return iHref < 0 ? "" : str.Substring(0, iHref);
            };
            Func<string, string, string> substringAfter = (str, after) =>
            {
                int iHref = str.IndexOf(after);
                return iHref < 0 ? "" : str.Substring(iHref + after.Length);
            };
            Converter<string, string> getText = p =>
                Regex.Replace(p, "<[^>]*>", x => "");

            Regex rx = new Regex(@"

                                ]+)>
                                    (?'LinkText' .*?)
                                (?>)

                            (?'Abstract' .*?)
                        (?>
)
                        .*?
                    (?>
)

",
                RegexOptions.IgnorePatternWhitespace
                | RegexOptions.ExplicitCapture
            );
            foreach (Match e in rx.Matches(this.content)) {
                string rurl = getText(substringBefore(substringAfter(
                    e.Groups["LinkAttributes"].Value, @"href="""), @""""));
                string rtitle = getText(e.Groups["LinkText"].Value);
                string rcontent = getText(e.Groups["Abstract"].Value);

                results.Add(new YahooResult(rurl, rtitle, rcontent));
            }
            return results.ToArray();
        }
    }

    public YahooSearch NextPage() {
        return new YahooSearch(this.query, this.page + 1);
    }

    public YahooSearch GetPage(int page) {
        return new YahooSearch(this.query, page);
    }
}

class YahooResult {
    public string URL { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public YahooResult(string url, string title, string content) {
        this.URL = url;
        this.Title = title;
        this.Content = content;
    }

    public override string ToString()
    {
        return string.Format("\nTitle: {0}\nLink:  {1}\nText:  {2}",
            Title, URL, Content);
    }
}

// Usage:

class Prog {
    static void Main() {
        foreach (int page in new[] { 0, 1 })
        {
            YahooSearch x = new YahooSearch("test", page);

            foreach (YahooResult result in x.Results)
            {
                Console.WriteLine(result);
            }
        }
    }
}


// version 1.1.3

typealias Vector = IntArray
typealias Matrix = Array<Vector>

fun zigzagMatrix(n: Int): Matrix {
    val result = Matrix(n) { Vector(n) }
    var down = false
    var count = 0
    for (col in 0 until n) {
        if (down)
            for (row in 0..col) result[row][col - row] = count++
        else
            for (row in col downTo 0) result[row][col - row] = count++
        down = !down
    }
    for (row in 1 until n) {
        if (down)
           for (col in n - 1 downTo row) result[row + n - 1 - col][col] = count++
        else
           for (col in row until n) result[row + n - 1 - col][col] = count++
        down = !down
    }
    return result
}
fun printMatrix(m: Matrix) {
    for (i in 0 until m.size) {
        for (j in 0 until m.size) print("%2d ".format(m[i][j]))
        println()
    }
    println()
}

fun main(args: Array<String>) {
    printMatrix(zigzagMatrix(5))
    printMatrix(zigzagMatrix(10))
}


Module Module1

   Sub Main()
       Dim doors(100) As Boolean 'Door 1 is at index 0

       For pass = 1 To 100
           For door = pass - 1 To 99 Step pass
               doors(door) = Not doors(door)
           Next
       Next

       For door = 0 To 99
           Console.WriteLine("Door # " & (door + 1) & " is " & If(doors(door), "Open", "Closed"))
       Next

       Console.ReadLine()
   End Sub

End Module


T YellowstoneGenerator
   min_ = 1
   n_ = 0
   n1_ = 0
   n2_ = 0
   Set[Int] sequence_

   F next()
      .n2_ = .n1_
      .n1_ = .n_
      I .n_ < 3
         .n_++
      E
         .n_ = .min_
         L !(.n_ !C .sequence_ & gcd(.n1_, .n_) == 1 & gcd(.n2_, .n_) > 1)
            .n_++
      .sequence_.add(.n_)
      L
         I .min_ !C .sequence_
            L.break
         .sequence_.remove(.min_)
         .min_++
      R .n_

print(‘First 30 Yellowstone numbers:’)
V ygen = YellowstoneGenerator()
print(ygen.next(), end' ‘’)
L(i) 1 .< 30
   print(‘ ’ygen.next(), end' ‘’)
print()


import std.stdio, std.exception, std.regex, std.algorithm, std.string,
       std.net.curl;

struct YahooResult {
    string url, title, content;

    string toString() const {
        return "\nTitle: %s\nLink:  %s\nText:  %s"
               .format(title, url, content);
    }
}

struct YahooSearch {
    private string query, content;
    private uint page;

    this(in string query_, in uint page_ = 0) {
        this.query = query_;
        this.page = page_;
        this.content = "http://search.yahoo.com/search?p=%s&b=%d"
                       .format(query, page * 10 + 1).get.assumeUnique;
    }

    @property results() const {
        immutable re = `

                                <a \s (?P<linkAttributes> [^>]+)>
                                  (?P<linkText> .*?)

                              (?P<abstract> .*?)

                            .*?

`;

        const clean = (string s) => s.replace("<[^>]*>".regex("g"),"");

        return content.match(re.regex("gx")).map!(m => YahooResult(
            clean(m.captures["linkAttributes"]
                  .findSplitAfter(`href="`)[1]
                  .findSplitBefore(`"`)[0]),
            clean(m.captures["linkText"]),
            clean(m.captures["abstract"])
        ));
    }

    YahooSearch nextPage() const {
        return YahooSearch(query, page + 1);
    }
}

void main() {
    writefln("%(%s\n%)", "test".YahooSearch.results);
}


Public Sub Form_Open()
Dim hWebView As WebView

Me.Arrangement = Arrange.Fill
Me.Maximized = True
Me.Title = "Yahoo! search interface"

hWebView = New WebView(Me)
hWebView.Expand = True
hWebView.URL = "https://www.yahoo.com"

End


#!/bin/ksh

# Produce a zig-zag array.

#	# Variables:
#
integer DEF_SIZE=5			# Default size = 5
arr_size=${1:-$DEF_SIZE}	# $1 = size, or default

    #	# Externals:
    #

#	# Functions:
#

 ######
# main #
 ######
integer i j n
typeset -a zzarr

for (( i=n=0; i<arr_size*2; i++ )); do
	for (( j= (i<arr_size) ? 0 : i-arr_size+1; j<=i && j<arr_size; j++ )); do
		(( zzarr[(i&1) ? j*(arr_size-1)+i : (i-j)*arr_size+j] = n++ ))
	done
done

for ((i=0; i<arr_size*arr_size; i++)); do
	printf "%3d " ${zzarr[i]}
	(( (i+1)%arr_size == 0 )) && printf "\n"
done


var(
     'square'  = array
    ,'size'    = integer( 5 )// for a 5 X 5 square
    ,'row'     = array
    ,'x'       = integer( 1 )
    ,'y'       = integer( 1 )
    ,'counter' = integer( 1 )
);

// create place-holder matrix
loop( $size );
   $row = array;

   loop( $size );
      $row->insert( 0 );

    /loop;

   $square->insert( $row );

/loop;

while( $counter < $size * $size );
   // check downward diagonal
   if(
         $x > 1
         &&
         $y < $square->size
         &&
         $square->get( $y + 1 )->get( $x - 1 ) == 0
      );

         $x -= 1;
         $y += 1;

   // check upward diagonal
   else(
         $x < $square->size
         &&
         $y > 1
         &&
         $square->get( $y - 1 )->get( $x + 1 ) == 0
      );

         $x += 1;
         $y -= 1;

   // check right
   else(
         (
            $y == 1
            ||
            $y == $square->size
         )
         &&
         $x < $square->size
         &&
         $square->get( $y )->get( $x + 1 ) == 0
      );

      $x += 1;

   // down
   else;
      $y += 1;

   /if;

   $square->get( $y )->get( $x ) = loop_count;

   $counter += 1;

/while;

$square;


const number_doors = 101

fn main() {
    mut closed_doors := []bool{len: number_doors, init: true}
    for pass in 0..number_doors {
        for door := 0; door < number_doors; door += pass + 1 {
            closed_doors[door] = !closed_doors[door]
        }
    }
    for pass in 1..number_doors {
        if !closed_doors[pass] {
            println('Door #$pass Open')
        }
    }
}


BYTE FUNC Gcd(BYTE a,b)
  BYTE tmp

  IF a<b THEN
    tmp=a a=b b=tmp
  FI

  WHILE b#0
  DO
    tmp=a MOD b
    a=b b=tmp
  OD
RETURN (a)

BYTE FUNC Contains(BYTE ARRAY a BYTE len,value)
  BYTE i

  FOR i=0 TO len-1
  DO
    IF a(i)=value THEN
      RETURN (1)
    FI
  OD
RETURN (0)

PROC Generate(BYTE ARRAY seq BYTE count)
  BYTE i,x

  seq(0)=1 seq(1)=2 seq(2)=3
  FOR i=3 TO COUNT-1
  DO
    x=1
    DO
      IF Contains(seq,i,x)=0 AND
        Gcd(x,seq(i-1))=1 AND Gcd(x,seq(i-2))>1 THEN
        EXIT
      FI
      x==+1
    OD
    seq(i)=x
  OD
RETURN

PROC Main()
  DEFINE COUNT="30"
  BYTE ARRAY seq(COUNT)
  BYTE i

  Generate(seq,COUNT)
  PrintF("First %B Yellowstone numbers:%E",COUNT)
  FOR i=0 TO COUNT-1
  DO
    PrintB(seq(i)) Put(32)
  OD
RETURN


with Ada.Text_IO;
with Ada.Containers.Ordered_Sets;

procedure Yellowstone_Sequence is

   generic  --  Allow more than one generator, but must be instantiated
   package Yellowstones is
      function Next return Integer;
      function GCD (Left, Right : Integer) return Integer;
   end Yellowstones;

   package body Yellowstones
   is
      package Sequences is
        new Ada.Containers.Ordered_Sets (Integer);

      --  Internal package state
      N_0 : Integer := 0;
      N_1 : Integer := 0;
      N_2 : Integer := 0;
      Seq : Sequences.Set;
      Min : Integer := 1;

      function GCD (Left, Right : Integer) return Integer
      is (if Right = 0
          then Left
          else GCD (Right, Left mod Right));

      function Next return Integer is
      begin
         N_2 := N_1;
         N_1 := N_0;
         if N_0 < 3 then
            N_0 := N_0 + 1;
         else
            N_0 := Min;
            while
              not (not Seq.Contains (N_0)
                     and then GCD (N_1, N_0) = 1
                     and then GCD (N_2, N_0) > 1)
            loop
               N_0 := N_0 + 1;
            end loop;
         end if;
         Seq.Insert (N_0);
         while Seq.Contains (Min) loop
            Seq.Delete (Min);
            Min := Min + 1;
         end loop;
         return N_0;
      end Next;

   end Yellowstones;

   procedure First_30 is
      package Yellowstone is new Yellowstones;  --  New generator instance
      use Ada.Text_IO;
   begin
      Put_Line ("First 30 Yellowstone numbers:");
      for A in 1 .. 30 loop
         Put (Yellowstone.Next'Image); Put (" ");
      end loop;
      New_Line;
   end First_30;

begin
   First_30;
end Yellowstone_Sequence;


package main

import (
    "fmt"
    "golang.org/x/net/html"
    "io/ioutil"
    "net/http"
    "regexp"
    "strings"
)

var (
    expr = `<h3 class="title"><a class=.*?href="(.*?)".*?>(.*?)</a></h3>` +
        `.*?<div class="compText aAbs" ><p class=.*?>(.*?)</p></div>`
    rx = regexp.MustCompile(expr)
)

type YahooResult struct {
    title, url, content string
}

func (yr YahooResult) String() string {
    return fmt.Sprintf("Title  : %s\nUrl    : %s\nContent: %s\n", yr.title, yr.url, yr.content)
}

type YahooSearch struct {
    query string
    page  int
}

func (ys YahooSearch) results() []YahooResult {
    search := fmt.Sprintf("http://search.yahoo.com/search?p=%s&b=%d", ys.query, ys.page*10+1)
    resp, _ := http.Get(search)
    body, _ := ioutil.ReadAll(resp.Body)
    s := string(body)
    defer resp.Body.Close()
    var results []YahooResult
    for _, f := range rx.FindAllStringSubmatch(s, -1) {
        yr := YahooResult{}
        yr.title = html.UnescapeString(strings.ReplaceAll(strings.ReplaceAll(f[2], "", ""), "", ""))
        yr.url = f[1]
        yr.content = html.UnescapeString(strings.ReplaceAll(strings.ReplaceAll(f[3], "", ""), "", ""))
        results = append(results, yr)
    }
    return results
}

func (ys YahooSearch) nextPage() YahooSearch {
    return YahooSearch{ys.query, ys.page + 1}
}

func main() {
    ys := YahooSearch{"rosettacode", 0}
    // Limit output to first 5 entries, say, from pages 1 and 2.
    fmt.Println("PAGE 1 =>\n")
    for _, res := range ys.results()[0:5] {
        fmt.Println(res)
    }
    fmt.Println("PAGE 2 =>\n")
    for _, res := range ys.nextPage().results()[0:5] {
        fmt.Println(res)
    }
}


local zigzag = {}

function zigzag.new(n)
    local a = {}
    local i -- cols
    local j -- rows

    a.n = n
    a.val = {}

    for j = 1, n do
        a.val[j] = {}
        for i = 1, n do
            a.val[j][i] = 0
        end
    end

    i = 1
    j = 1

    local di
    local dj
    local k = 0

    while k < n * n do
        a.val[j][i] = k
        k = k + 1
        if i == n then
            j = j + 1
            a.val[j][i] = k
            k = k + 1
            di = -1
            dj = 1
        end
        if j == 1 then
            i = i + 1
            a.val[j][i] = k
            k = k + 1
            di = -1
            dj = 1
        end
        if j == n then
            i = i + 1
            a.val[j][i] = k
            k = k + 1
            di = 1
            dj = -1
        end
        if i == 1 then
            j = j + 1
            a.val[j][i] = k
            k = k + 1
            di = 1
            dj = -1
        end
        i = i + di
        j = j + dj
    end

    setmetatable(a, {__index = zigzag, __tostring = zigzag.__tostring})
    return a
end

function zigzag:__tostring()
    local s = {}
    for j = 1, self.n do
        local row = {}
        for i = 1, self.n do
            row[i] = string.format('%d', self.val[j][i])
        end
        s[j] = table.concat(row, ' ')
    end
    return table.concat(s, '\n')
end

print(zigzag.new(5))