task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#PARI.2FGP
PARI/GP
zz(n)={ my(M=matrix(n,n),i,j,d=-1,start,end=n^2-1); while(ct--, M[i+1,j+1]=start; M[n-i,n-j]=end; start++; end--; i+=d; j-=d; if(i<0, i++; d=-d , if(j<0, j++; d=-d ) ); if(start>end,return(M)) ) };
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#Fortran
Fortran
program doors implicit none integer, allocatable :: door(:) character(6), parameter :: s(0:1) = [character(6) :: "closed", "open"] integer :: i, n   print "(A)", "Number of doors?" read *, n allocate (door(n)) door = 1 do i = 1, n door(i:n:i) = 1 - door(i:n:i) print "(A,G0,2A)", "door ", i, " is ", s(door(i)) end do end program
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#MIPS_Assembly
MIPS Assembly
  .data array: .word 1, 2, 3, 4, 5, 6, 7, 8, 9 # creates an array of 9 32 Bit words.   .text main: la $s0, array li $s1, 25 sw $s1, 4($s0) # writes $s1 (25) in the second array element # the four counts thi bytes after the beginning of the address. 1 word = 4 bytes, so 4 acesses the second element   lw $s2, 20($s0) # $s2 now contains 6   li $v0, 10 # end program syscall  
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#Phix
Phix
with javascript_semantics function call_fn(integer f, n) return call_func(f,{f,n}) end function function Y(integer f) return f end function function fac(integer self, integer n) return iff(n>1?n*call_fn(self,n-1):1) end function function fib(integer self, integer n) return iff(n>1?call_fn(self,n-1)+call_fn(self,n-2):n) end function procedure test(string name, integer rid=routine_id(name)) integer f = Y(rid) printf(1,"%s: ",{name}) for i=1 to 10 do printf(1," %d",call_fn(f,i)) end for printf(1,"\n"); end procedure test("fac") test("fib")
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Pascal
Pascal
Program zigzag( input, output );   const size = 5; var zzarray: array [1..size, 1..size] of integer; element, i, j: integer; direction: integer; width, n: integer;   begin i := 1; j := 1; direction := 1; for element := 0 to (size*size) - 1 do begin zzarray[i,j] := element; i := i + direction; j := j - direction; if (i = 0) then begin direction := -direction; i := 1; if (j > size) then begin j := size; i := 2; end; end else if (i > size) then begin direction := -direction; i := size; j := j + 2; end else if (j = 0) then begin direction := -direction; j := 1; if (i > size) then begin j := 2; i := size; end; end else if (j > size) then begin direction := -direction; j := size; i := i + 2; end; end;   width := 2; n := size; while (n > 0) do begin width := width + 1; n := n div 10; end; for j := 1 to size do begin for i := 1 to size do write(zzarray[i,j]:width); writeln; end; end.
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#Free_Pascal
Free Pascal
  program OneHundredIsOpen;   const DoorCount = 100;   var IsOpen: array[1..DoorCount] of boolean; Door, Jump: integer;   begin // Close all doors for Door := 1 to DoorCount do IsOpen[Door] := False; // Iterations for Jump := 1 to DoorCount do begin Door := Jump; repeat IsOpen[Door] := not IsOpen[Door]; Door := Door + Jump; until Door > DoorCount; end; // Show final status for Door := 1 to DoorCount do begin Write(Door, ' '); if IsOpen[Door] then WriteLn('open') else WriteLn('closed'); end; // Wait for <enter> Readln; end.  
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Modula-2
Modula-2
VAR staticArray: ARRAY [1..10] OF INTEGER;
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#Phixmonti
Phixmonti
0 var subr   def fac dup 1 > if dup 1 - subr exec * endif enddef   def fib dup 1 > if dup 1 - subr exec swap 2 - subr exec + endif enddef   def test print ": " print var subr 10 for subr exec print " " print endfor nl enddef   getid fac "fac" test getid fib "fib" test
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#PHP
PHP
<?php function Y($f) { $g = function($w) use($f) { return $f(function() use($w) { return call_user_func_array($w($w), func_get_args()); }); }; return $g($g); }   $fibonacci = Y(function($f) { return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); }; });   echo $fibonacci(10), "\n";   $factorial = Y(function($f) { return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); }; });   echo $factorial(10), "\n"; ?>
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Perl
Perl
use 5.010;   sub zig_zag { my $n = shift; my $max_number = $n**2; my @matrix; my $number = 0; for my $j ( 0 .. --$n ) { for my $i ( $j % 2 ? 0 .. $j : reverse 0 .. $j ) { $matrix[$i][ $j - $i ] = $number++; #next if $j == $n; $matrix[ $n - $i ][ $n - ( $j - $i ) ] = $max_number - $number; } } return @matrix; }   my @zig_zag_matrix = zig_zag(5); say join "\t", @{$_} foreach @zig_zag_matrix;  
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#FreeBASIC
FreeBASIC
' version 27-10-2016 ' compile with: fbc -s console   #Define max_doors 100   Dim As ULong c, n, n1, door(1 To max_doors)   ' toggle, at start all doors are closed (0) ' 0 = door closed, 1 = door open For n = 1 To max_doors For n1 = n To max_doors Step n door(n1) = 1 - door(n1) Next Next   ' count the doors that are open (1) Print "doors that are open nr: "; For n = 1 To max_doors If door(n) = 1 Then Print n; " "; c = c + 1 End If Next   Print : Print Print "There are " + Str(c) + " doors open"   ' empty keyboard buffer While InKey <> "" : Wend Print : Print "hit any key to end program" Sleep End
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Modula-3
Modula-3
VAR staticArray: ARRAY [1..10] OF INTEGER;
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#PicoLisp
PicoLisp
(de Y (F) (let X (curry (F) (Y) (F (curry (Y) @ (pass (Y Y))))) (X X) ) )
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#Pop11
Pop11
define Y(f); procedure (x); x(x) endprocedure( procedure (y); f(procedure(z); (y(y))(z) endprocedure) endprocedure ) enddefine;   define fac(h); procedure (n); if n = 0 then 1 else n * h(n - 1) endif endprocedure enddefine;   define fib(h); procedure (n); if n < 2 then 1 else h(n - 1) + h(n - 2) endif endprocedure enddefine;   Y(fac)(5) => Y(fib)(5) =>
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Phix
Phix
with javascript_semantics integer n = 9 integer zstart = 0, zend = n*n-1 --integer zstart = 1, zend = n*n string fmt = sprintf("%%%dd",length(sprintf("%d",zend))) sequence m = repeat(repeat("??",n),n) integer x = 1, y = 1, d = -1 while 1 do m[x][y] = sprintf(fmt,zstart) if zstart=zend then exit end if zstart += 1 m[n-x+1][n-y+1] = sprintf(fmt,zend) zend -= 1 x += d y -= d if x<1 then x += 1 d = -d elsif y<1 then y += 1 d = -d end if end while for i=1 to n do m[i] = join(m[i]) end for puts(1,join(m,"\n"))
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#friendly_interactive_shell
friendly interactive shell
# Set doors to empty list set doors   # Initialize doors arrays for i in (seq 100) set doors[$i] 0 end   for i in (seq 100) set j $i while test $j -le 100 # Logical not on doors set doors[$j] (math !$doors[$j]) set j (math $j + $i) end end   # Print every door for i in (seq (count $doors)) echo -n "$i " if test $doors[$i] -eq 0 echo closed else echo open end end  
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Monte
Monte
var myArray := ['a', 'b', 'c','d']
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#PostScript
PostScript
y { {dup cons} exch concat dup cons i }.   /fac { { {pop zero?} {pop succ} {{dup pred} dip i *} ifte } y }.
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#PowerShell
PowerShell
$fac = { param([ScriptBlock] $f) invoke-expression @" { param([int] `$n) if (`$n -le 0) {1} else {`$n * {$f}.InvokeReturnAsIs(`$n - 1)} } "@ }   $fib = { param([ScriptBlock] $f) invoke-expression @" { param([int] `$n) switch (`$n) { 0 {1} 1 {1} default {{$f}.InvokeReturnAsIs(`$n-1)+{$f}.InvokeReturnAsIs(`$n-2)} } } "@ }   $Z = { param([ScriptBlock] $f) invoke-expression @" { param([ScriptBlock] `$x) {$f}.InvokeReturnAsIs(`$(invoke-expression @`" { param(```$y) {`$x}.InvokeReturnAsIs({`$x}).InvokeReturnAsIs(```$y) } `"@)) }.InvokeReturnAsIs({ param([ScriptBlock] `$x) {$f}.InvokeReturnAsIs(`$(invoke-expression @`" { param(```$y) {`$x}.InvokeReturnAsIs({`$x}).InvokeReturnAsIs(```$y) } `"@)) }) "@ }   $Z.InvokeReturnAsIs($fac).InvokeReturnAsIs(5) $Z.InvokeReturnAsIs($fib).InvokeReturnAsIs(5)
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Phixmonti
Phixmonti
5 var Size 0 Size repeat Size repeat   1 var i 1 var j   Size 2 power for swap i get rot j set i set i j + 1 bitand 0 == IF j Size < IF j 1 + var j ELSE i 2 + var i ENDIF i 1 > IF i 1 - var i ENDIF ELSE i Size < IF i 1 + var i ELSE j 2 + var j ENDIF j 1 > IF j 1 - var j ENDIF ENDIF endfor   Size FOR var row Size FOR var col row get col get tostr 32 32 chain chain 1 3 slice print drop drop ENDFOR nl ENDFOR
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#Frink
Frink
  doors = new array[[101], false] for pass=1 to 100 for door=pass to 100 step pass doors@door = ! doors@door   print["Open doors: "] for door=1 to 100 if doors@door print["$door "]  
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Nanoquery
Nanoquery
// create a fixed-length array (length 10) arr = array(10)   // assign a value to the first position in the array and then display it arr[0] = "hello, world!" println arr[0]     // create a variable-length list l = list()   // place the numbers 1-10 in the list for i in range(1,10) append l i end   // display the list println l
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#Prolog
Prolog
:- use_module(lambda).   % The Y combinator y(P, Arg, R) :- Pred = P +\Nb2^F2^call(P,Nb2,F2,P), call(Pred, Arg, R).     test_y_combinator :- % code for Fibonacci function Fib = \NFib^RFib^RFibr1^(NFib < 2 -> RFib = NFib ; NFib1 is NFib - 1, NFib2 is NFib - 2, call(RFibr1,NFib1,RFib1,RFibr1), call(RFibr1,NFib2,RFib2,RFibr1), RFib is RFib1 + RFib2 ),   y(Fib, 10, FR), format('Fib(~w) = ~w~n', [10, FR]),   % code for Factorial function Fact = \NFact^RFact^RFactr1^(NFact = 1 -> RFact = NFact ; NFact1 is NFact - 1, call(RFactr1,NFact1,RFact1,RFactr1), RFact is NFact * RFact1 ),   y(Fact, 10, FF), format('Fact(~w) = ~w~n', [10, FF]).
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#PHP
PHP
function ZigZagMatrix($num) { $matrix = array(); for ($i = 0; $i < $num; $i++){ $matrix[$i] = array(); }   $i=1; $j=1; for ($e = 0; $e < $num*$num; $e++) { $matrix[$i-1][$j-1] = $e; if (($i + $j) % 2 == 0) { if ($j < $num){ $j++; }else{ $i += 2; } if ($i > 1){ $i --; } } else { if ($i < $num){ $i++; }else{ $j += 2; } if ($j > 1){ $j --; } } } return $matrix; }
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#FunL
FunL
for i <- 1..100 r = foldl1( \a, b -> a xor b, [(a|i) | a <- 1..100] ) println( i + ' ' + (if r then 'open' else 'closed') )
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Neko
Neko
var myArray = $array(1);   $print(myArray[0]);
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#Python
Python
>>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args))) >>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1)) >>> [ Y(fac)(i) for i in range(10) ] [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] >>> fib = lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)) >>> [ Y(fib)(i) for i in range(10) ] [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#PicoLisp
PicoLisp
(load "@lib/simul.l")   (de zigzag (N) (prog1 (grid N N) (let (D '(north west south east .) E '(north east .) This 'a1) (for Val (* N N) (=: val Val) (setq This (or ((cadr D) ((car D) This)) (prog (setq D (cddr D)) ((pop 'E) This) ) ((pop 'E) This) ) ) ) ) ) )   (mapc '((L) (for This L (prin (align 3 (: val)))) (prinl) ) (zigzag 5) )
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#PL.2FI
PL/I
/* Fill a square matrix with the values 0 to N**2-1, */ /* in a zig-zag fashion. */ /* N is the length of one side of the square. */ /* Written 22 February 2010. */   declare n fixed binary;   put skip list ('Please type the size of the matrix:'); get list (n);   begin; declare A(n,n) fixed binary; declare (i, j, inc, q) fixed binary;   on subrg snap begin; declare i fixed binary; do i = 1 to n; put skip edit (a(i,*)) (f(4)); end; stop; end;   A = -1; inc = -1; i, j = 1;   loop: do q = 0 to n**2-1; a(i,j) = q; if q = n**2-1 then leave; if i = 1 & j = n then if iand(j,1) = 1 then /* odd-sided matrix */ do; i = i + 1; inc = -inc; iterate loop; end; else /* an even-sided matrix */ do; i = i + inc; j = j - inc; iterate loop; end; if inc = -1 then if i+inc < 1 then do; inc = -inc; j = j + 1; a(i,j) = q; iterate loop; end; if inc = 1 then if i+inc > n then do; inc = -inc; j = j + 1; a(i,j) = q; iterate loop; end; if inc = 1 then if j-inc < 1 then do; inc = -inc; i = i + 1; a(i,j) = q; iterate loop; end; if inc = -1 then if j - inc > n then do; inc = -inc; i = i + 1; a(i,j) = q; iterate loop; end; i = i + inc; j = j - inc; end;   /* Display the square. */ do i = 1 to n; put skip edit (a(i,*)) (f(4)); end; end;
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#Futhark
Futhark
  let main(n: i32): [n]bool = loop is_open = replicate n false for i < n do let js = map (*i+1) (iota n) let flips = map (\j -> if j < n then unsafe !is_open[j] else true -- Doesn't matter. ) js in scatter is_open js flips  
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Nemerle
Nemerle
using System; using System.Console; using System.Collections;   module ArrayOps { Main() : void { def fives = array(10); foreach (i in [1 .. 10]) fives[i - 1] = i * 5; def ten = fives[1]; WriteLine($"Ten: $ten");   def dynamic = ArrayList(); dynamic.Add(1); dynamic.Add(3); dynamic[1] = 2; foreach (i in dynamic) Write($"$i\t"); // Nemerle isn't great about displaying arrays, it's better with lists though } }
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#Q
Q
> Y: {{x x} {({y {(x x) y} x} y) x} x} > fac: {{$[y<2; 1; y*x y-1]} x} > (Y fac) 6 720j > fib: {{$[y<2; 1; (x y-1) + (x y-2)]} x} > (Y fib) each til 20 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765  
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Plain_TeX
Plain TeX
\long\def\antefi#1#2\fi{#2\fi#1} \def\fornum#1=#2to#3(#4){% \edef#1{\number\numexpr#2}\edef\fornumtemp{\noexpand\fornumi\expandafter\noexpand\csname fornum\string#1\endcsname {\number\numexpr#3}{\ifnum\numexpr#4<0 <\else>\fi}{\number\numexpr#4}\noexpand#1}\fornumtemp } \long\def\fornumi#1#2#3#4#5#6{\def#1{\unless\ifnum#5#3#2\relax\antefi{#6\edef#5{\number\numexpr#5+(#4)\relax}#1}\fi}#1} \def\elem(#1,#2){\numexpr(#1+#2)*(#1+#2-1)/2-(\ifodd\numexpr#1+#2\relax#1\else#2\fi)\relax} \def\zzmat#1{% \noindent% quit vertical mode \fornum\yy=1to#1(+1){% \fornum\xx=1to#1(+1){% \ifnum\numexpr\xx+\yy\relax<\numexpr#1+2\relax \hbox to 2em{\hfil\number\elem(\xx,\yy)}% \else \hbox to 2em{\hfil\number\numexpr#1*#1-1-\elem(#1+1-\xx,#1+1-\yy)\relax}% \fi }% \par\noindent% next line + quit vertical mode }\par } \zzmat{5} \bye
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#PostScript
PostScript
%!PS %%BoundingBox: 0 0 300 200 /size 9 def % defines row * column (9*9 -> 81 numbers,  % from 0 to 80) /itoa { 2 string cvs } bind def % visual bounding box... % 0 0 moveto 300 0 lineto 300 200 lineto 0 200 lineto % closepath stroke 20 150 translate % it can be easily enhanced to support more columns and % rows. This limit is put here just to avoid more than 2 % digits, mainly because of formatting size size mul 99 le { /Helvetica findfont 14 scalefont setfont /ulimit size size mul def /sizem1 size 1 sub def  % prepare the number list 0 ulimit 1 sub { dup 1 add } repeat ulimit array astore /di -1 def /dj 1 def /ri 1 def /rj 0 def /pus true def 0 0 moveto /i 0 def /j 0 def {  % can be rewritten a lot better :) 0.8 setgray i 30 mul j 15 mul neg lineto stroke 0 setgray i 30 mul j 15 mul neg moveto itoa show i 30 mul j 15 mul neg moveto pus { i ri add size ge { /ri 0 def /rj 1 def } if j rj add size ge { /ri 1 def /rj 0 def } if /pus false def /i i ri add def /j j rj add def /ri rj /rj ri def def } { i di add dup 0 le exch sizem1 ge or j dj add dup 0 le exch sizem1 ge or or { /pus true def /i i di add def /j j dj add def /di di neg def /dj dj neg def } { /i i di add def /j j dj add def } ifelse } ifelse } forall stroke showpage } if %%EOF
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#FutureBasic
FutureBasic
  include "NSLog.incl"   NSInteger door, square = 1, increment = 3   for door = 1 to 100 if ( door == square ) NSLog( @"Door %ld is open.", door ) square += increment : increment += 2 else NSLog( @"Door %ld is closed.", door ) end if next   HandleEvents  
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   array = int[10] array[0] = 42   say array[0] array[3] say   words = ['Ogof', 'Ffynnon', 'Ddu']   say words[0] words[1] words[2] say   -- Dynamic arrays can be simulated via the Java Collections package splk = ArrayList() splk.add(words[0]) splk.add(words[1]) splk.add(words[2]) splk.add('Draenen')   say splk.get(0) splk.get(3) say splk.get(0) splk.get(1) splk.get(2) say   -- or by using NetRexx "indexed strings" (associative arrays) cymru = '' cymru[0] = 0 cymru[0] = cymru[0] + 1; cymru[cymru[0]] = splk.get(0) splk.get(1) splk.get(2) cymru[0] = cymru[0] + 1; cymru[cymru[0]] = splk.get(0) splk.get(3)   loop x_ = 1 to cymru[0] by 1 say x_':' cymru[x_] end x_
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#Quackery
Quackery
[ ' stack nested nested ' share nested join swap nested join dup dup 0 peek put ] is recursive ( x --> x )   [ over 2 < iff [ 2drop 1 ] done dip [ dup 1 - ] do * ] is factorial ( n x --> n )   [ over 2 < iff drop done swap 1 - tuck 1 - over do dip do + ] is fibonacci ( n x --> n )   say "8 factorial = " 8 ' factorial recursive do echo cr say "8 fibonacci = " 8 ' fibonacci recursive do echo cr
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#PowerShell
PowerShell
function zigzag( [int] $n ) { $zigzag=New-Object 'Object[,]' $n,$n $nodd = $n -band 1 $nm1 = $n - 1 $i=0; $j=0; foreach( $k in 0..( $n * $n - 1 ) ) { $zigzag[$i,$j] = $k $iodd = $i -band 1 $jodd = $j -band 1 if( ( $j -eq $nm1 ) -and ( $iodd -ne $nodd ) ) { $i++ } elseif( ( $i -eq $nm1 ) -and ( $jodd -eq $nodd ) ) { $j++ } elseif( ( $i -eq 0 ) -and ( -not $jodd ) ) { $j++ } elseif( ( $j -eq 0 ) -and $iodd ) { $i++ } elseif( $iodd -eq $jodd ) { $i-- $j++ } else { $i++ $j-- } } ,$zigzag }   function displayZigZag( [int] $n ) { $a = zigzag $n 0..$n | ForEach-Object { $b=$_ $pad=($n*$n-1).ToString().Length "$(0..$n | ForEach-Object { "{0,$pad}" -f $a[$b,$_] } )" } }
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#FUZE_BASIC
FUZE BASIC
READ x,y,z PRINT "Open doors: ";x;" "; CYCLE z=x+y PRINT z;" "; x=z y=y+2 REPEAT UNTIL z>=100 DATA 1,3,0 END
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#NewLISP
NewLISP
(array 5) → (nil nil nil nil nil)
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#R
R
Y <- function(f) { (function(x) { (x)(x) })( function(y) { f( (function(a) {y(y)})(a) ) } ) }
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#Racket
Racket
#lang lazy   (define Y (λ (f) ((λ (x) (f (x x))) (λ (x) (f (x x))))))   (define Fact (Y (λ (fact) (λ (n) (if (zero? n) 1 (* n (fact (- n 1)))))))) (define Fib (Y (λ (fib) (λ (n) (if (<= n 1) n (+ (fib (- n 1)) (fib (- n 2))))))))
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Prolog
Prolog
zig_zag(N) :- zig_zag(N, N).   % compute zig_zag for a matrix of Lig lines of Col columns zig_zag(Lig, Col) :- length(M, Lig), maplist(init(Col), M), fill(M, 0, 0, 0, Lig, Col, up), % display the matrix maplist(print_line, M).     fill(M, Cur, L, C, NL, NC, _) :- L is NL - 1, C is NC - 1, nth0(L, M, Line), nth0(C, Line, Cur).   fill(M, Cur, L, C, NL, NC, Sens) :- nth0(L, M, Line), nth0(C, Line, Cur), Cur1 is Cur + 1, compute_next(NL, NC, L, C, Sens, L1, C1, Sens1), fill(M, Cur1, L1, C1, NL, NC, Sens1).     init(N, L) :- length(L, N).   % compute_next % arg1 : Number of lnes of the matrix % arg2 : number of columns of the matrix % arg3 : current line % arg4 : current column % arg5 : current direction of movement % arg6 : nect line % arg7 : next column % arg8 : next direction of movement compute_next(_NL, NC, 0, Col, up, 0, Col1, down) :- Col < NC - 1, Col1 is Col+1.   compute_next(_NL, NC, 0, Col, up, 1, Col, down) :- Col is NC - 1.   compute_next(NL, _NC, Lig, 0, down, Lig1, 0, up) :- Lig < NL - 1, Lig1 is Lig+1.   compute_next(NL, _NC, Lig, 0, down, Lig, 1, up) :- Lig is NL - 1.   compute_next(NL, _NC, Lig, Col, down, Lig1, Col1, down) :- Lig < NL - 1, Lig1 is Lig + 1, Col1 is Col-1.   compute_next(NL, _NC, Lig, Col, down, Lig, Col1, up) :- Lig is NL - 1, Col1 is Col+1.   compute_next(_NL, NC, Lig, Col, up, Lig1, Col1, up) :- Col < NC - 1, Lig1 is Lig - 1, Col1 is Col+1.   compute_next(_NL, NC, Lig, Col, up, Lig1, Col, down) :- Col is NC - 1, Lig1 is Lig + 1.     print_line(L) :- maplist(print_val, L), nl.   print_val(V) :- writef('%3r ', [V]).  
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#F.C5.8Drmul.C3.A6
Fōrmulæ
Public Sub Main() Dim bDoor As New Boolean[101] Dim siCount1, siCount2, siStart As Short   For siCount1 = 1 To 100 Inc siStart For siCount2 = siStart To 100 Step siCount1 bDoor[siCount2] = Not bDoor[siCount2] Next Next   For siCount1 = 1 To 100 If bDoor[siCount1] Then Print siCount1;; Next   End
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Nim
Nim
var # fixed size arrays x = [1,2,3,4,5,6,7,8,9,10] # type and size automatically inferred y: array[1..5, int] = [1,2,3,4,5] # starts at 1 instead of 0 z: array['a'..'z', int] # indexed using characters   x[0] = x[1] + 1 echo x[0] echo z['d']   x[7..9] = y[3..5] # copy part of array   var # variable size sequences a = @[1,2,3,4,5,6,7,8,9,10] b: seq[int] = @[1,2,3,4,5]   a[0] = a[1] + 1 echo a[0]   a.add(b) # append another sequence a.add(200) # append another element echo a.pop() # pop last item, removing and returning it echo a
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#Raku
Raku
sub Y (&f) { sub (&x) { x(&x) }( sub (&y) { f(sub ($x) { y(&y)($x) }) } ) } sub fac (&f) { sub ($n) { $n < 2 ?? 1 !! $n * f($n - 1) } } sub fib (&f) { sub ($n) { $n < 2 ?? $n !! f($n - 1) + f($n - 2) } } say map Y($_), ^10 for &fac, &fib;
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#PureBasic
PureBasic
Procedure zigZag(size) Protected i, v, x, y   Dim a(size - 1, size - 1)   x = 1 y = 1 For i = 1 To size * size ;loop once for each element a(x - 1, y - 1) = v ;assign the next index   If (x + y) & 1 = 0 ;even diagonal (zero based count) If x < size ;while inside the square If y > 1 ;move right-up y - 1 EndIf x + 1 Else y + 1 ;on the edge increment y, but not x until diagonal is odd EndIf Else ;odd diagonal (zero based count) If y < size ;while inside the square If x > 1 ;move left-down x - 1 EndIf y + 1 Else x + 1 ;on the edge increment x, but not y until diagonal is even EndIf EndIf v + 1 Next     ;generate and show printout PrintN("Zig-zag matrix of size " + Str(size) + #CRLF$) maxDigitCount = Len(Str(size * size)) + 1 For y = 0 To size - 1 For x = 0 To size - 1 Print(RSet(Str(a(x, y)), maxDigitCount, " ")) Next PrintN("") Next PrintN("") EndProcedure   If OpenConsole() zigZag(5) zigZag(6)   Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") Input() CloseConsole() EndIf
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#Gambas
Gambas
Public Sub Main() Dim bDoor As New Boolean[101] Dim siCount1, siCount2, siStart As Short   For siCount1 = 1 To 100 Inc siStart For siCount2 = siStart To 100 Step siCount1 bDoor[siCount2] = Not bDoor[siCount2] Next Next   For siCount1 = 1 To 100 If bDoor[siCount1] Then Print siCount1;; Next   End
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#NS-HUBASIC
NS-HUBASIC
10 DIM A(1) 20 A(1)=10 30 PRINT A(1)
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#REBOL
REBOL
Y: closure [g] [do func [f] [f :f] closure [f] [g func [x] [do f :f :x]]]
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Python
Python
def zigzag(n): '''zigzag rows''' def compare(xy): x, y = xy return (x + y, -y if (x + y) % 2 else y) xs = range(n) return {index: n for n, index in enumerate(sorted( ((x, y) for x in xs for y in xs), key=compare ))}     def printzz(myarray): '''show zigzag rows as lines''' n = int(len(myarray) ** 0.5 + 0.5) xs = range(n) print('\n'.join( [''.join("%3i" % myarray[(x, y)] for x in xs) for y in xs] ))     printzz(zigzag(6))
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#GAP
GAP
doors := function(n) local a,j,s; a := [ ]; for j in [1 .. n] do a[j] := 0; od; for s in [1 .. n] do j := s; while j <= n do a[j] := 1 - a[j]; j := j + s; od; od; return Filtered([1 .. n], j -> a[j] = 1); end;   doors(100); # [ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 ]
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#NSIS
NSIS
  !include NSISArray.nsh Function ArrayTest Push $0 ; Declaring an array NSISArray::New TestArray 1 2 NSISArray::Push TestArray "Hello" ; NSISArray arrays are dynamic by default. NSISArray::Push TestArray "World" NSISArray::Read TestArray 1 Pop $0 DetailPrint $0 Pop $0 FunctionEnd  
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#REXX
REXX
/*REXX program implements and displays a stateless Y combinator. */ numeric digits 1000 /*allow big numbers. */ say ' fib' Y(fib (50) ) /*Fibonacci series. */ say ' fib' Y(fib (12 11 10 9 8 7 6 5 4 3 2 1 0) ) /*Fibonacci series. */ say ' fact' Y(fact (60) ) /*single factorial.*/ say ' fact' Y(fact (0 1 2 3 4 5 6 7 8 9 10 11) ) /*single factorial.*/ say ' Dfact' Y(dfact (4 5 6 7 8 9 10 11 12 13) ) /*double factorial.*/ say ' Tfact' Y(tfact (4 5 6 7 8 9 10 11 12 13) ) /*triple factorial.*/ say ' Qfact' Y(qfact (4 5 6 7 8 40) ) /*quadruple factorial.*/ say ' length' Y(length (when for to where whenceforth) ) /*lengths of words. */ say 'reverse' Y(reverse (123 66188 3007 45.54 MAS I MA) ) /*reverses strings. */ say ' sign' Y(sign (-8 0 8) ) /*sign of the numbers.*/ say ' trunc' Y(trunc (-7.0005 12 3.14159 6.4 78.999) ) /*truncates numbers. */ say ' b2x' Y(b2x (1 10 11 100 1000 10000 11111 ) ) /*converts BIN──►HEX. */ say ' d2x' Y(d2x (8 9 10 11 12 88 89 90 91 6789) ) /*converts DEC──►HEX. */ say ' x2d' Y(x2d (8 9 10 11 12 88 89 90 91 6789) ) /*converts HEX──►DEC. */ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ Y: parse arg Y _; $=; do j=1 for words(_); interpret '$=$' Y"("word(_,j)')'; end; return $ /*──────────────────────────────────────────────────────────────────────────────────────*/ fib: procedure; parse arg x; if x<2 then return x; s= 0; a= 0; b= 1 do j=2 to x; s= a+b; a= b; b= s; end; return s /*──────────────────────────────────────────────────────────────────────────────────────*/ dfact: procedure; parse arg x;  != 1; do j=x to 2 by -2;  != !*j; end; return ! tfact: procedure; parse arg x;  != 1; do j=x to 2 by -3;  != !*j; end; return ! qfact: procedure; parse arg x;  != 1; do j=x to 2 by -4;  != !*j; end; return ! fact: procedure; parse arg x;  != 1; do j=2 to x  ;  != !*j; end; return !
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Quackery
Quackery
[ ]'[ tuck do dip do ] is with2 ( x x --> x x )   [ dup temp put [] swap dup * times [ i^ join ] sortwith [ with2 [ temp share /mod tuck + 1 & if negate ] > ] sortwith [ with2 [ temp share /mod + ] > ] dup witheach [ i^ unrot poke ] [] swap temp share times [ temp share split dip [ nested join ] ] drop temp release ] is zigzag ( n --> [ )   10 zigzag witheach [ witheach [ dup 10 < if sp echo sp ] cr ]
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Qi
Qi
  (define odd? A -> (= 1 (MOD A 2))) (define even? A -> (= 0 (MOD A 2)))   (define zigzag-val 0 0 N -> 0   X 0 N -> (1+ (zigzag-val (1- X) 0 N)) where (odd? X) X 0 N -> (1+ (zigzag-val (1- X) 1 N))   0 Y N -> (1+ (zigzag-val 1 (1- Y) N)) where (odd? Y) 0 Y N -> (1+ (zigzag-val 0 (1- Y) N))   X Y N -> (1+ (zigzag-val (MAX 0 (1- X)) (MIN (1- N) (1+ Y)) N)) where (even? (+ X Y)) X Y N -> (1+ (zigzag-val (MIN (1- N) (1+ X)) (MAX 0 (1- Y)) N)))   (define range E E -> [] S E -> [S|(range (1+ S) E)])   (define zigzag N -> (map (/. Y (map (/. X (zigzag-val X Y N)) (range 0 N))) (range 0 N)))  
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#GDScript
GDScript
func Doors(door_count:int) -> void : var doors : Array doors.resize(door_count)   # Note : Initialization is not necessarily mandatory (by default values are false) # Intentionally left here for i in door_count : doors[i] = false   # do visits for i in door_count : for j in range(i,door_count,i+1) : doors[j] = not doors[j]   # print results var results : String = "" for i in door_count : results += str(i+1) + " " if doors[i] else "" print("Doors open : %s" % [results] )   # calling the function from the _ready function func _ready() -> void : Doors(100)  
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Oberon-2
Oberon-2
  MODULE Arrays; IMPORT Out;   PROCEDURE Static; VAR x: ARRAY 5 OF LONGINT; BEGIN x[0] := 10; x[1] := 11; x[2] := 12; x[3] := 13; x[4] := x[0];   Out.String("Static at 4: ");Out.LongInt(x[4],0);Out.Ln; END Static;   PROCEDURE Dynamic; VAR x: POINTER TO ARRAY OF LONGINT; BEGIN NEW(x,5);   x[0] := 10; x[1] := 11; x[2] := 12; x[3] := 13; x[4] := x[0];   Out.String("Dynamic at 4: ");Out.LongInt(x[4],0);Out.Ln; END Dynamic;   BEGIN Static; Dynamic END Arrays.  
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#Ruby
Ruby
y = lambda do |f| lambda {|g| g[g]}[lambda do |g| f[lambda {|*args| g[g][*args]}] end] end   fac = lambda{|f| lambda{|n| n < 2 ? 1 : n * f[n-1]}} p Array.new(10) {|i| y[fac][i]} #=> [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]   fib = lambda{|f| lambda{|n| n < 2 ? n : f[n-1] + f[n-2]}} p Array.new(10) {|i| y[fib][i]} #=> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#R
R
zigzag1 <- function(n) { j <- seq(n) u <- rep(c(-1, 1), n) v <- j * (2 * j - 1) - 1 v <- as.vector(rbind(v, v + 1)) a <- matrix(0, n, n) for (i in seq(n)) { a[i, ] <- v[j + i - 1] v <- v + u } a }   zigzag1(5)
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#Genie
Genie
  // 100 doors problem // Author: Sinuhe masan (2019) init   // 100 elements array of boolean type doors:bool[100]   for var i = 1 to 100 doors[i] = false // set all doors closed     for var i = 1 to 100 j:int = i while j <= 100 do doors[j] = not doors[j] j = j + i   print("Doors open: ") for var i = 1 to 100 if doors[i] stdout.printf ("%d ", i)    
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Objeck
Objeck
  bundle Default { class Arithmetic { function : Main(args : System.String[]), Nil { array := Int->New[2]; array[0] := 13; array[1] := 7; (array[0] + array[1])->PrintLine(); } } }  
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#Rust
Rust
  //! A simple implementation of the Y Combinator: //! λf.(λx.xx)(λx.f(xx)) //! <=> λf.(λx.f(xx))(λx.f(xx))   /// A function type that takes its own type as an input is an infinite recursive type. /// We introduce the "Apply" trait, which will allow us to have an input with the same type as self, and break the recursion. /// The input is going to be a trait object that implements the desired function in the interface. trait Apply<T, R> { fn apply(&self, f: &dyn Apply<T, R>, t: T) -> R; }   /// If we were to pass in self as f, we get: /// λf.λt.sft /// => λs.λt.sst [s/f] /// => λs.ss impl<T, R, F> Apply<T, R> for F where F: Fn(&dyn Apply<T, R>, T) -> R { fn apply(&self, f: &dyn Apply<T, R>, t: T) -> R { self(f, t) } }   /// (λt(λx.(λy.xxy))(λx.(λy.f(λz.xxz)y)))t /// => (λx.xx)(λx.f(xx)) /// => Yf fn y<T, R>(f: impl Fn(&dyn Fn(T) -> R, T) -> R) -> impl Fn(T) -> R { move |t| (&|x: &dyn Apply<T, R>, y| x.apply(x, y)) (&|x: &dyn Apply<T, R>, y| f(&|z| x.apply(x, z), y), t) }   /// Factorial of n. fn fac(n: usize) -> usize { let almost_fac = |f: &dyn Fn(usize) -> usize, x| if x == 0 { 1 } else { x * f(x - 1) }; y(almost_fac)(n) }   /// nth Fibonacci number. fn fib(n: usize) -> usize { let almost_fib = |f: &dyn Fn((usize, usize, usize)) -> usize, (a0, a1, x)| match x { 0 => a0, 1 => a1, _ => f((a1, a0 + a1, x - 1)), };   y(almost_fib)((1, 1, n)) }   /// Driver function. fn main() { let n = 10; println!("fac({}) = {}", n, fac(n)); println!("fib({}) = {}", n, fib(n)); }    
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Racket
Racket
  #lang racket   (define/match (compare i j) [((list x y) (list a b)) (or (< x a) (and (= x a) (< y b)))])   (define/match (key i) [((list x y)) (list (+ x y) (if (even? (+ x y)) (- y) y))])   (define (zigzag-ht n) (define indexorder (sort (for*/list ([x n] [y n]) (list x y)) compare #:key key)) (for/hash ([(n i) (in-indexed indexorder)]) (values n i)))   (define (zigzag n) (define ht (zigzag-ht n)) (for/list ([x n]) (for/list ([y n]) (hash-ref ht (list x y)))))   (zigzag 4)  
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Raku
Raku
class Turtle { my @dv = [0,-1], [1,-1], [1,0], [1,1], [0,1], [-1,1], [-1,0], [-1,-1]; my $points = 8; # 'compass' points of neighbors on grid: north=0, northeast=1, east=2, etc.   has @.loc = 0,0; has $.dir = 0; has %.world; has $.maxegg; has $.range-x; has $.range-y;   method turn-left ($angle = 90) { $!dir -= $angle / 45; $!dir %= $points; } method turn-right($angle = 90) { $!dir += $angle / 45; $!dir %= $points; }   method lay-egg($egg) { %!world{~@!loc} = $egg; $!maxegg max= $egg; $!range-x minmax= @!loc[0]; $!range-y minmax= @!loc[1]; }   method look($ahead = 1) { my $there = @!loc »+« @dv[$!dir] »*» $ahead; %!world{~$there}; }   method forward($ahead = 1) { my $there = @!loc »+« @dv[$!dir] »*» $ahead; @!loc = @($there); }   method showmap() { my $form = "%{$!maxegg.chars}s"; my $endx = $!range-x.max; for $!range-y.list X $!range-x.list -> ($y, $x) { print (%!world{"$x $y"} // '').fmt($form); print $x == $endx ?? "\n" !! ' '; } } }   sub MAIN(Int $size = 5) { my $t = Turtle.new(dir => 1); my $counter = 0; for 1 ..^ $size -> $run { for ^$run { $t.lay-egg($counter++); $t.forward; } my $yaw = $run %% 2 ?? -1 !! 1; $t.turn-right($yaw * 135); $t.forward; $t.turn-right($yaw * 45); } for $size ... 1 -> $run { for ^$run -> $ { $t.lay-egg($counter++); $t.forward; } $t.turn-left(180); $t.forward; my $yaw = $run %% 2 ?? 1 !! -1; $t.turn-right($yaw * 45); $t.forward; $t.turn-left($yaw * 45); } $t.showmap; }
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#Glee
Glee
100` *=0=>d $$ create vector 1..100, create bit pattern d, marking all equal to 0 :for (1..100[.s]){ $$ loop s from 1 to 100 d^(100` %s *=0 )=>d;} $$ d = d xor (bit pattern of vector 1..100 % s) d $$ output d  
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Objective-C
Objective-C
// NSArrays are ordered collections of NSObject subclasses only.   // Create an array of NSString objects. NSArray *firstArray = [[NSArray alloc] initWithObjects:@"Hewey", @"Louie", @"Dewey", nil];   // NSArrays are immutable; it does have a mutable subclass, however - NSMutableArray. // Let's instantiate one with a mutable copy of our array. // We can do this by sending our first array a -mutableCopy message. NSMutableArray *secondArray = [firstArray mutableCopy];   // Replace Louie with Launchpad McQuack. [secondArray replaceObjectAtIndex:1 withObject:@"Launchpad"];   // Display the first object in the array. NSLog(@"%@", [secondArray objectAtIndex:0]);   // In non-ARC or non-GC environments, retained objects must be released later. [firstArray release]; [secondArray release];   // There is also a modern syntax which allows convenient creation of autoreleased immutable arrays. // No nil termination is then needed. NSArray *thirdArray = @[ @"Hewey", @"Louie", @"Dewey", @1, @2, @3 ];  
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#Scala
Scala
  def Y[A, B](f: (A => B) => (A => B)): A => B = { case class W(wf: W => (A => B)) { def apply(w: W): A => B = wf(w) } val g: W => (A => B) = w => f(w(w))(_) g(W(g)) }  
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Rascal
Rascal
0 (0,0), 1 (0,1), 3 (0,2) 2 (1,0), 4 (1,1), 6 (1,2) 5 (2,0), 7 (2,1), 8 (2,2)
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#REXX
REXX
/*REXX program produces and displays a zig─zag matrix (a square array). */ parse arg n start inc . /*obtain optional arguments from the CL*/ if n=='' | n=="," then n= 5 /*Not specified? Then use the default.*/ if start=='' | start=="," then start= 0 /* " " " " " " */ if inc=='' | inc=="," then inc= 1 /* " " " " " " */ row= 1; col= 1; size= n**2 /*start: 1st row & column; array size.*/ do j=start by inc for size; @.row.col= j if (row+col)//2==0 then do; if col<n then col= col+1; else row= row+2 if row\==1 then row= row-1 end else do; if row<n then row= row+1; else col= col+2 if col\==1 then col= col-1 end end /*j*/ /* [↑] // is REXX ÷ remainder.*/ call show /*display a (square) matrix──►terminal.*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ show: w= max(length(start), length(start+size*inc)) /*max width of any matrix elements,*/ do r=1 for n  ; _= right(@.r.1, w) /*show the rows of the matrix. */ do c=2 for n-1; _= _ right(@.r.c, w) /*build a line for output of a row.*/ end /*c*/; say _ /* [↑] align the matrix elements. */ end /*r*/; return
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#GML
GML
var doors,a,i; //Sets up the array for all of the doors. for (i = 1; i<=100; i += 1) { doors[i]=0; }   //This first for loop goes through and passes the interval down to the next for loop. for (i = 1; i <= 100; i += 1;) { //This for loop opens or closes the doors and uses the interval(if interval is 2 it only uses every other etc..) for (a = 0; a <= 100; a += i;) { //Opens or closes a door. doors[a] = !doors[a]; } } open_doors = '';   //This for loop goes through the array and checks for open doors. //If the door is open it adds it to the string then displays the string. for (i = 1; i <= 100; i += 1;) { if (doors[i] == 1) { open_doors += "Door Number "+string(i)+" is open#"; } } show_message(open_doors); game_end();
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#OCaml
OCaml
# Array.make 6 'A' ;; - : char array = [|'A'; 'A'; 'A'; 'A'; 'A'; 'A'|]   # Array.init 8 (fun i -> i * 10) ;; - : int array = [|0; 10; 20; 30; 40; 50; 60; 70|]   # let arr = [|0; 1; 2; 3; 4; 5; 6 |] ;; val arr : int array = [|0; 1; 2; 3; 4; 5; 6|]   # arr.(4) ;; - : int = 4   # arr.(4) <- 65 ;; - : unit = ()   # arr ;; - : int array = [|0; 1; 2; 3; 65; 5; 6|]
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#Scheme
Scheme
(define Y ; (Y f) = (g g) where (lambda (f) ; (g g) = (f (lambda a (apply (g g) a))) ((lambda (g) (g g)) ; (Y f) == (f (lambda a (apply (Y f) a))) (lambda (g) (f (lambda a (apply (g g) a)))))))   ;; head-recursive factorial (define fac ; fac = (Y f) = (f (lambda a (apply (Y f) a))) (Y (lambda (r) ; = (lambda (x) ... (r (- x 1)) ... ) (lambda (x) ; where r = (lambda a (apply (Y f) a)) (if (< x 2) ; (r ... ) == ((Y f) ... ) 1 ; == (lambda (x) ... (fac (- x 1)) ... ) (* x (r (- x 1))))))))   ;; tail-recursive factorial (define fac2 (lambda (x) ((Y (lambda (r) ; (Y f) == (f (lambda a (apply (Y f) a))) (lambda (x acc) ; r == (lambda a (apply (Y f) a)) (if (< x 2) ; (r ... ) == ((Y f) ... ) acc (r (- x 1) (* x acc)))))) x 1)))   ; double-recursive Fibonacci (define fib (Y (lambda (f) (lambda (x) (if (< x 2) x (+ (f (- x 1)) (f (- x 2))))))))   ; tail-recursive Fibonacci (define fib2 (lambda (x) ((Y (lambda (f) (lambda (x a b) (if (< x 1) a (f (- x 1) b (+ a b)))))) x 0 1)))   (display (fac 6)) (newline)   (display (fib2 134)) (newline)
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Ring
Ring
  # Project Zig-zag matrix   load "guilib.ring" load "stdlib.ring" new qapp { win1 = new qwidget() { setwindowtitle("Zig-zag matrix") setgeometry(100,100,600,400) n = 5 a = newlist(n,n) zigzag = newlist(n,n) for j = 1 to n for i = 1 to n a[j][i] = 0 next next i = 1 j = 1 k = 1 while k < n * n a[j][i] = k k = k + 1 if i = n j = j + 1 a[j][i] = k k = k + 1 di = -1 dj = 1 ok if j = 1 i = i + 1 a[j][i] = k k = k + 1 di = -1 dj = 1 ok if j = n i = i + 1 a[j][i] = k k = k + 1 di = 1 dj = -1 ok if i = 1 j = j + 1 a[j][i] = k k = k + 1 di = 1 dj = -1 ok i = i + di j = j + dj end for p = 1 to n for m = 1 to n zigzag[p][m] = new qpushbutton(win1) { x = 150+m*40 y = 30 + p*40 setgeometry(x,y,40,40) settext(string(a[p][m])) } next next show() } exec() }  
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Ruby
Ruby
def zigzag(n) (seq=*0...n).product(seq) .sort_by {|x,y| [x+y, (x+y).even? ? y : -y]} .each_with_index.sort.map(&:last).each_slice(n).to_a end   def print_matrix(m) format = "%#{m.flatten.max.to_s.size}d " * m[0].size puts m.map {|row| format % row} end   print_matrix zigzag(5)
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#Go
Go
package main   import "fmt"   func main() { doors := [100]bool{}   // the 100 passes called for in the task description for pass := 1; pass <= 100; pass++ { for door := pass-1; door < 100; door += pass { doors[door] = !doors[door] } }   // one more pass to answer the question for i, v := range doors { if v { fmt.Print("1") } else { fmt.Print("0") }   if i%10 == 9 { fmt.Print("\n") } else { fmt.Print(" ") }   } }
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Oforth
Oforth
[ "abd", "def", "ghi" ] at( 3 ) .   Array new dup addAll( [1, 2, 3] ) dup put( 2, 8.1 ) .  
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#Shen
Shen
(define y F -> ((/. X (X X)) (/. X (F (/. Z ((X X) Z))))))   (let Fac (y (/. F N (if (= 0 N) 1 (* N (F (- N 1)))))) (output "~A~%~A~%~A~%" (Fac 0) (Fac 5) (Fac 10)))
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#Sidef
Sidef
var y = ->(f) {->(g) {g(g)}(->(g) { f(->(*args) {g(g)(args...)})})}   var fac = ->(f) { ->(n) { n < 2 ? 1 : (n * f(n-1)) } } say 10.of { |i| y(fac)(i) }   var fib = ->(f) { ->(n) { n < 2 ? n : (f(n-2) + f(n-1)) } } say 10.of { |i| y(fib)(i) }
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Rust
Rust
  use std::cmp::Ordering; use std::cmp::Ordering::{Equal, Greater, Less}; use std::iter::repeat;   #[derive(Debug, PartialEq, Eq)] struct SortIndex { x: usize, y: usize, }   impl SortIndex { fn new(x: usize, y: usize) -> SortIndex { SortIndex { x, y } } }   impl PartialOrd for SortIndex { fn partial_cmp(&self, other: &SortIndex) -> Option<Ordering> { Some(self.cmp(other)) } }   impl Ord for SortIndex { fn cmp(&self, other: &SortIndex) -> Ordering { let lower = if self.x + self.y == other.x + other.y { if (self.x + self.y) % 2 == 0 { self.x < other.x } else { self.y < other.y } } else { (self.x + self.y) < (other.x + other.y) };   if lower { Less } else if self == other { Equal } else { Greater } } }   fn zigzag(n: usize) -> Vec<Vec<usize>> { let mut l: Vec<SortIndex> = (0..n * n).map(|i| SortIndex::new(i % n, i / n)).collect(); l.sort();   let init_vec = vec![0; n]; let mut result: Vec<Vec<usize>> = repeat(init_vec).take(n).collect(); for (i, &SortIndex { x, y }) in l.iter().enumerate() { result[y][x] = i } result }   fn main() { println!("{:?}", zigzag(5)); }    
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Scala
Scala
def zigzag(n: Int): Array[Array[Int]] = { val l = for (i <- 0 until n*n) yield (i%n, i/n) val lSorted = l.sortWith { case ((x,y), (u,v)) => if (x+y == u+v) if ((x+y) % 2 == 0) x<u else y<v else x+y < u+v } val res = Array.ofDim[Int](n, n) lSorted.zipWithIndex foreach { case ((x,y), i) => res(y)(x) = i } res }   zigzag(5).foreach{ ar => ar.foreach(x => print("%3d".format(x))) println }
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#Golfscript
Golfscript
100:c;[{0}c*]:d; c,{.c,>\)%{.d<\.d=1^\)d>++:d;}/}/ [c,{)"door "\+" is"+}%d{{"open"}{"closed"}if}%]zip {" "*puts}/
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Ol
Ol
  ; making a vector > #(1 2 3 4 5) #(1 2 3 4 5)   ; making a vector in a functional way > (vector 1 2 3 4 5) #(1 2 3 4 5)   ; another functional vector making way > (make-vector '(1 2 3 4 5)) #(1 2 3 4 5)   ; the same as above functional vector making way > (list->vector '(1 2 3 4 5)) #(1 2 3 4 5)   ; modern syntax of making a vector > [1 2 3 4 5] #(1 2 3 4 5)   ; making a vector of symbols > '[a b c d e] #(a b c d e)   ; making a vector of symbols but evaluate a third element > `[a b ,(* 7 13) d e] #(a b 91 d e)   ; making an empty vectors > #() #()   > [] #()   > '[] #()   > `[] #()   > (make-vector '()) #()   > (list->vector '()) #()   ; making a vector of a vectors (a matrix, for example) > [[1 2 3] [4 5 6] [7 8 9]] #(#(1 2 3) #(4 5 6) #(7 8 9))   ; getting length of a vector > (size [1 2 3 4 5]) 5   ; making n-length vector with undefined values (actually, #false) > (make-vector 5) #(#false #false #false #false #false)   ; making n-length vector with default values > (make-vector 5 0) #(0 0 0 0 0)   ; define a test vector for use in below > (define array [3 5 7 9 11]) ;; Defined array   ; getting first element of a vector > (ref array 1) 3   > (ref array (- (size array))) 3   ; getting last element of a vector > (ref array (size array)) 11   > (ref array -1) 11   ; vectors comparison > (equal? [1 2 3 4 5] [1 2 3 4 5]) #true   > (equal? [1 2 3 4 5] [7 2 3 4 5]) #false   ; vectors of vectors comparison > (equal? [[1 2 3] [4 5 6] [7 8 9]] [[1 2 3] [4 5 6] [7 8 9]]) #true   > (equal? [[1 2 3] [4 5 6] [7 8 9]] [[1 2 3] [4 5 6] [7 8 3]]) #false  
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#Slate
Slate
Method traits define: #Y &builder: [[| :f | [| :x | f applyWith: (x applyWith: x)] applyWith: [| :x | f applyWith: (x applyWith: x)]]].
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Scilab
Scilab
function a = zigzag3(n) a = zeros(n, n) for k=1:n j = modulo(k, 2) d = (2*j-1)*(n-1) m = (n-1)*(k-1) a(k+(1-j)*m:d:k+j*m) = k*(k-1)/2:k*(k+1)/2-1 a(n*(n+1-k)+(1-j)*m:d:n*(n+1-k)+j*m) = n*n-k*(k+1)/2:n*n-k*(k-1)/2-1 end endfunction   -->zigzag3(5) ans =   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.
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#Gosu
Gosu
  uses java.util.Arrays   var doors = new boolean[100] Arrays.fill( doors, false )   for( pass in 1..100 ) { var counter = pass-1 while( counter < 100 ) { doors[counter] = !doors[counter] counter += pass } }   for( door in doors index i ) { print( "door ${i+1} is ${door ? 'open' : 'closed'}" ) }    
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#ooRexx
ooRexx
a = .array~new -- create a zero element array b = .array~new(10) -- create an array with initial size of 10 c = .array~of(1, 2, 3) -- create a 3 element array holding objects 1, 2, and 3 a[3] = "Fred" -- assign an item b[2] = a[3] -- retrieve an item from the array c~append(4) -- adds to end. c[4] == 4 now
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#Smalltalk
Smalltalk
Y := [:f| [:x| x value: x] value: [:g| f value: [:x| (g value: g) value: x] ] ].   fib := Y value: [:f| [:i| i <= 1 ifTrue: [i] ifFalse: [(f value: i-1) + (f value: i-2)] ] ].   (fib value: 10) displayNl.   fact := Y value: [:f| [:i| i = 0 ifTrue: [1] ifFalse: [(f value: i-1) * i] ] ].   (fact value: 10) displayNl.
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Seed7
Seed7
$ include "seed7_05.s7i";   const type: matrix is array array integer;   const func matrix: zigzag (in integer: size) is func result var matrix: s is matrix.value; local var integer: i is 1; var integer: j is 1; var integer: d is -1; var integer: max is 0; var integer: n is 0; begin s := size times size times 0; max := size ** 2; for n range 1 to max div 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 incr(i); d := -d; elsif j < 1 then incr(j); d := -d; end if; end for; end func;   const proc: main is func local var matrix: s is matrix.value; var integer: i is 0; var integer: num is 0; begin s := zigzag(7); for i range 1 to length(s) do for num range s[i] do write(num lpad 4); end for; writeln; end for; end func;
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Sidef
Sidef
func zig_zag(w, h) {   var r = [] var n = 0   h.of { |e| w.of { |f| [e, f] } }.reduce('+').sort { |a, b| (a[0]+a[1] <=> b[0]+b[1]) || (a[0]+a[1] -> is_even ? a[0]<=>b[0]  : a[1]<=>b[1]) }.each { |a| r[a[1]][a[0]] = n++ }   return r }   zig_zag(5, 5).each { say .join('', {|i| "%4i" % i}) }
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#Groovy
Groovy
doors = [false] * 100 (0..99).each { it.step(100, it + 1) { doors[it] ^= true } } (0..99).each { println("Door #${it + 1} is ${doors[it] ? 'open' : 'closed'}.") }
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#OxygenBasic
OxygenBasic
    'CREATING A STATIC ARRAY float f[100]   'SETTING INDEX BASE indexbase 1 'default   'FILLING PART OF AN ARRAY f[20]={2,4,6,8,10,12}   'MAPPING AN ARRAY TO ANOTHER float *g @g=@f[20] print g[6] 'result 12   'DYNAMIC (RESIZEABLE) ARRAYS redim float f(100) f={2,4,6,8} 'assign some values redim float f(200) 'expand array print f(2) 'original values are preserved by default redim float f(200) clear 'array elements are cleared print f(2) 'value set to 0.0 redim float f(0) 'release allocated memory '  
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#Standard_ML
Standard ML
- datatype 'a mu = Roll of ('a mu -> 'a) fun unroll (Roll x) = x   fun fix f = (fn x => fn a => f (unroll x x) a) (Roll (fn x => fn a => f (unroll x x) a))   fun fac f 0 = 1 | fac f n = n * f (n-1)   fun fib f 0 = 0 | fib f 1 = 1 | fib f n = f (n-1) + f (n-2) ; datatype 'a mu = Roll of 'a mu -> 'a val unroll = fn : 'a mu -> 'a mu -> 'a val fix = fn : (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b val fac = fn : (int -> int) -> int -> int val fib = fn : (int -> int) -> int -> int - List.tabulate (10, fix fac); val it = [1,1,2,6,24,120,720,5040,40320,362880] : int list - List.tabulate (10, fix fib); val it = [0,1,1,2,3,5,8,13,21,34] : int list
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Standard_ML
Standard ML
fun rowprint r = (List.app (fn i => print (StringCvt.padLeft #" " 3 (Int.toString i))) r; print "\n"); fun zig lst M = List.app rowprint (lst M);   fun sign t = if t mod 2 = 0 then ~1 else 1;   fun zag n = List.tabulate (n, fn i=> rev ( List.tabulate (n, fn j => let val t = n-j+i and u = n+j-i in if i <= j then t*t div 2 + sign t * ( t div 2 - i ) else n*n - 1 - ( u*u div 2 + sign u * ( u div 2 - n + 1 + i) ) end )));   zig zag 5 ;
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Stata
Stata
function zigzag1(n) { j = 0::n-1 u = J(1, n, (-1, 1)) v = (j:*(2:*j:+3)) v = rowshape((v,v:+1), 1) a = J(n, n, .) for (i=1; i<=n; i++) { a[i, .] = v[j:+i] v = v+u } return(a) }   zigzag1(5) 1 2 3 4 5 +--------------------------+ 1 | 0 1 5 6 14 | 2 | 2 4 7 13 16 | 3 | 3 8 12 17 25 | 4 | 9 11 18 24 31 | 5 | 10 19 23 32 40 | +--------------------------+
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#GW-BASIC
GW-BASIC
10 DIM A(100) 20 FOR OFFSET = 1 TO 100 30 FOR I = 0 TO 100 STEP OFFSET 40 A(I) = A(I) + 1 50 NEXT I 60 NEXT OFFSET 70 ' Print "opened" doors 80 FOR I = 1 TO 100 90 IF A(I) MOD 2 = 1 THEN PRINT I 100 NEXT I
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Oz
Oz
declare Arr = {Array.new 1 %% lowest index 10 %% highest index 37} %% all 10 fields initialized to 37 in {Show Arr.1} Arr.1 := 64 {Show Arr.1}
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#SuperCollider
SuperCollider
// z-combinator ( z = { |f| { |x| x.(x) }.( { |y| f.({ |args| y.(y).(args) }) } ) }; )   // the same in a shorter form   ( r = { |x| x.(x) }; z = { |f| r.({ |y| f.(r.(y).(_)) }) }; )     // factorial k = { |f| { |x| if(x < 2, 1, { x * f.(x - 1) }) } };   g = z.(k);   g.(5) // 120   (1..10).collect(g) // [ 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800 ]       // fibonacci   k = { |f| { |x| if(x <= 2, 1, { f.(x - 1) + f.(x - 2) }) } };   g = z.(k);   g.(3)   (1..10).collect(g) // [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 ]      
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 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 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Tcl
Tcl
proc zigzag {size} { set m [lrepeat $size [lrepeat $size .]] set x 0; set dx -1 set y 0; set dy 1   for {set i 0} {$i < $size ** 2} {incr i} { if {$x >= $size} { incr x -1 incr y 2 negate dx dy } elseif {$y >= $size} { incr x 2 incr y -1 negate dx dy } elseif {$x < 0 && $y >= 0} { incr x negate dx dy } elseif {$x >= 0 && $y < 0} { incr y negate dx dy } lset m $x $y $i incr x $dx incr y $dy } return $m }   proc negate {args} { foreach varname $args { upvar 1 $varname var set var [expr {-1 * $var}] } }   print_matrix [zigzag 5]
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#Harbour
Harbour
#define ARRAY_ELEMENTS 100 PROCEDURE Main() LOCAL aDoors := Array( ARRAY_ELEMENTS ) LOCAL i, j   AFill( aDoors, .F. ) FOR i := 1 TO ARRAY_ELEMENTS FOR j := i TO ARRAY_ELEMENTS STEP i aDoors[ j ] = ! aDoors[ j ] NEXT NEXT AEval( aDoors, {|e, n| QQout( Padl(n,3) + " is " + Iif(aDoors[n], "*open*", "closed" ) + "|" ), Iif( n%5 == 0, Qout(), e:=NIL) } ) RETURN