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/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.
#Elixir
Elixir
defmodule HundredDoors do def doors(n \\ 100) do List.duplicate(false, n) end   def toggle(doors, n) do List.update_at(doors, n, &(!&1)) end   def toggle_every(doors, n) do Enum.reduce( Enum.take_every((n-1)..99, n), doors, fn(n, acc) -> toggle(acc, n) end ) end end   # unoptimized final_state = Enum.reduce(1..100, HundredDoors.doors, fn(n, acc) -> HundredDoors.toggle_every(acc, n) end)   open_doors = Enum.with_index(final_state) |> Enum.filter_map(fn {door,_} -> door end, fn {_,index} -> index+1 end)   IO.puts "All doors are closed except these: #{inspect open_doors}"     # optimized final_state = Enum.reduce(1..10, HundredDoors.doors, fn(n, acc) -> HundredDoors.toggle(acc, n*n-1) end)   open_doors = Enum.with_index(final_state) |> Enum.filter_map(fn {door,_} -> door end, fn {_,index} -> index+1 end)   IO.puts "All doors are closed except these: #{inspect open_doors}"
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)
#LFE
LFE
  ; Create a fixed-size array with entries 0-9 set to 'undefined' > (set a0 (: array new 10)) #(array 10 0 undefined 10) > (: array size a0) 10   ; Create an extendible array and set entry 17 to 'true', ; causing the array to grow automatically > (set a1 (: array set 17 'true (: array new))) #(array 18 ... (: array size a1) 18   ; Read back a stored value > (: array get 17 a1) true   ; Accessing an unset entry returns the default value > (: array get 3 a1) undefined   ; Accessing an entry beyond the last set entry also returns the ; default value, if the array does not have fixed size > (: array get 18 a1) undefined   ; "sparse" functions ignore default-valued entries > (set a2 (: array set 4 'false a1)) #(array 18 ... > (: array sparse_to_orddict a2) (#(4 false) #(17 true))   ; An extendible array can be made fixed-size later > (set a3 (: array fix a2)) #(array 18 ...   ; A fixed-size array does not grow automatically and does not ; allow accesses beyond the last set entry > (: array set 18 'true a3) exception error: badarg in (array set 3)   > (: array get 18 a3) exception error: badarg in (array get 2)    
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives in the red house.   The Swede has a dog.   The Dane drinks tea.   The green house is immediately to the left of the white house.   They drink coffee in the green house.   The man who smokes Pall Mall has birds.   In the yellow house they smoke Dunhill.   In the middle house they drink milk.   The Norwegian lives in the first house.   The man who smokes Blend lives in the house next to the house with cats.   In a house next to the house where they have a horse, they smoke Dunhill.   The man who smokes Blue Master drinks beer.   The German smokes Prince.   The Norwegian lives next to the blue house.   They drink water in a house next to the house where they smoke Blend. The question is, who owns the zebra? Additionally, list the solution for all the houses. Optionally, show the solution is unique. Related tasks   Dinesman's multiple-dwelling problem   Twelve statements
#Racket
Racket
#lang racket   (require racklog)   (define %select (%rel (x xs S S1) [(x (cons x xs) xs)] [(x (cons S xs) (cons S S1)) (%select x xs S1)] [((cons x xs) S) (%select x S S1) (%select xs S1)] [('() (_))]))   (define %next-to (%rel (A B C) [(A B C) (%or (%left-of A B C) (%left-of B A C))]))   (define %left-of (%rel (A B C) [(A B C) (%append (_) (cons A (cons B (_))) C)]))   (define %zebra (%rel (Owns HS) [(Owns HS) (%is HS (list (list (_) 'norwegian (_) (_) (_)) (_) (list (_) (_) (_) 'milk (_)) (_) (_))) (%select (list (list 'red 'englishman (_) (_) (_)) (list (_) 'swede 'dog (_) (_)) (list (_) 'dane (_) 'tea (_)) (list (_) 'german (_) (_) 'prince)) HS) (%select (list (list (_) (_) 'birds (_) 'pallmall) (list 'yellow (_) (_) (_) 'dunhill) (list (_) (_) (_) 'beer 'bluemaster)) HS) (%left-of (list 'green (_) (_) 'coffee (_)) (list 'white (_) (_) (_) (_)) HS) (%next-to (list (_) (_) (_) (_) 'dunhill) (list (_) (_) 'horse (_) (_)) HS) (%next-to (list (_) (_) (_) (_) 'blend) (list (_) (_) 'cats (_) (_)) HS) (%next-to (list (_) (_) (_) (_) 'blend) (list (_) (_) (_) 'water (_)) HS) (%next-to (list (_) 'norwegian (_) (_) (_)) (list 'blue (_) (_) (_) (_)) HS) (%member (list (_) Owns 'zebra (_) (_)) HS)]))   (%which (Who HS) (%zebra Who HS))
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#Rascal
Rascal
import util::Math; import vis::Render; import vis::Figure;   public void yinyang(){ template = ellipse(fillColor("white"));   smallWhite = ellipse(fillColor("white"), shrink(0.1), valign(0.75)); smallBlack = ellipse(fillColor("black"), shrink(0.1), valign(0.25));   dots= [ellipse(fillColor("white"), shrink(0.000001), align(0.5 + sin(0.0031415*n)/4, 0.25 + cos(0.0031415*n)/-4)) | n <- [1 .. 1000]]; dots2 = [ellipse(fillColor("black"), shrink(0.000001), align(0.5 + sin(0.0031415*n)/-4, 0.75 + cos(0.0031415*n)/-4)) | n <- [1 .. 1000]]; dots3= [ellipse(fillColor("black"), shrink(0.000001), align(0.5 + sin(0.0031415*n)/2, 0.5-cos(0.0031415*n)/-2)) | n <- [1 .. 1000]];   black= overlay([*dots, *dots2, *dots3], shapeConnected(true), shapeClosed(true), shapeCurved(true), fillColor("black"));   render(hcat([vcat([overlay([template, black, smallWhite, smallBlack], aspectRatio (1.0)), space(), space()]), overlay([template, black, smallWhite, smallBlack], aspectRatio (1.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
#Julia
Julia
  _ _ _ _(_)_ | Documentation: https://docs.julialang.org (_) | (_) (_) | _ _ _| |_ __ _ | Type "?" for help, "]?" for Pkg help. | | | | | | |/ _` | | | | |_| | | | (_| | | Version 1.6.3 (2021-09-23) _/ |\__'_|_|_|\__'_| | Official https://julialang.org/ release |__/ |   julia> using Markdown   julia> @doc md""" # Y Combinator   $λf. (λx. f (x x)) (λx. f (x x))$ """ -> Y = f -> (x -> x(x))(y -> f((t...) -> y(y)(t...))) Y  
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
#Ksh
Ksh
  #!/bin/ksh   # Produce a zig-zag array.   # # Variables: # integer DEF_SIZE=5 # Default size = 5 arr_size=${1:-$DEF_SIZE} # $1 = size, or default   # # Externals: #   # # Functions: #     ###### # main # ###### integer i j n typeset -a zzarr   for (( i=n=0; i<arr_size*2; i++ )); do for (( j= (i<arr_size) ? 0 : i-arr_size+1; j<=i && j<arr_size; j++ )); do (( zzarr[(i&1) ? j*(arr_size-1)+i : (i-j)*arr_size+j] = n++ )) done done   for ((i=0; i<arr_size*arr_size; i++)); do printf "%3d " ${zzarr[i]} (( (i+1)%arr_size == 0 )) && printf "\n" done
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
#Lasso
Lasso
  var( 'square' = array ,'size' = integer( 5 )// for a 5 X 5 square ,'row' = array ,'x' = integer( 1 ) ,'y' = integer( 1 ) ,'counter' = integer( 1 ) );   // create place-holder matrix loop( $size ); $row = array;   loop( $size ); $row->insert( 0 );   /loop;   $square->insert( $row );   /loop;   while( $counter < $size * $size ); // check downward diagonal if( $x > 1 && $y < $square->size && $square->get( $y + 1 )->get( $x - 1 ) == 0 );   $x -= 1; $y += 1;   // check upward diagonal else( $x < $square->size && $y > 1 && $square->get( $y - 1 )->get( $x + 1 ) == 0 );   $x += 1; $y -= 1;   // check right else( ( $y == 1 || $y == $square->size ) && $x < $square->size && $square->get( $y )->get( $x + 1 ) == 0 );   $x += 1;   // down else; $y += 1;   /if;   $square->get( $y )->get( $x ) = loop_count;   $counter += 1;   /while;   $square;  
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.
#Elm
Elm
-- Unoptimized import List exposing (indexedMap, foldl, repeat, range) import Html exposing (text) import Debug exposing (toString)   type Door = Open | Closed   toggle d = if d == Open then Closed else Open   toggleEvery : Int -> List Door -> List Door toggleEvery k doors = indexedMap (\i door -> if modBy k (i+1) == 0 then toggle door else door) doors   n = 100   main = text (toString (foldl toggleEvery (repeat n Closed) (range 1 n)))  
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)
#Liberty_BASIC
Liberty BASIC
  dim Array(10)   Array(0) = -1 Array(10) = 1   print Array( 0), Array( 10)   REDIM Array( 100)   print Array( 0), Array( 10)   Array( 0) = -1 print Array( 0), Array( 10)    
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives in the red house.   The Swede has a dog.   The Dane drinks tea.   The green house is immediately to the left of the white house.   They drink coffee in the green house.   The man who smokes Pall Mall has birds.   In the yellow house they smoke Dunhill.   In the middle house they drink milk.   The Norwegian lives in the first house.   The man who smokes Blend lives in the house next to the house with cats.   In a house next to the house where they have a horse, they smoke Dunhill.   The man who smokes Blue Master drinks beer.   The German smokes Prince.   The Norwegian lives next to the blue house.   They drink water in a house next to the house where they smoke Blend. The question is, who owns the zebra? Additionally, list the solution for all the houses. Optionally, show the solution is unique. Related tasks   Dinesman's multiple-dwelling problem   Twelve statements
#Raku
Raku
my Hash @houses = (1 .. 5).map: { %(:num($_)) }; # 1 there are five houses   my @facts = ( { :nat<English>, :color<red> }, # 2 The English man lives in the red house. { :nat<Swede>, :pet<dog> }, # 3 The Swede has a dog. { :nat<Dane>, :drink<tea> }, # 4 The Dane drinks tea. { :color<green>, :Left-Of(:color<white>) }, # 5 the green house is immediately to the left of the white house { :drink<coffee>, :color<green> }, # 6 They drink coffee in the green house. { :smoke<Pall-Mall>, :pet<birds> }, # 7 The man who smokes Pall Mall has birds. { :color<yellow>, :smoke<Dunhill> }, # 8 In the yellow house they smoke Dunhill. { :num(3), :drink<milk> }, # 9 In the middle house they drink milk. { :num(1), :nat<Norwegian> }, # 10 The Norwegian lives in the first house. { :smoke<Blend>, :Next-To(:pet<cats>) }, # 11 The man who smokes Blend lives in the house next to the house with cats. { :pet<horse>, :Next-To(:smoke<Dunhill>) }, # 12 In a house next to the house where they have a horse, they smoke Dunhill. { :smoke<Blue-Master>, :drink<beer> }, # 13 The man who smokes Blue Master drinks beer. { :nat<German>, :smoke<Prince> }, # 14 The German smokes Prince. { :nat<Norwegian>, :Next-To(:color<blue>) }, # 15 The Norwegian lives next to the blue house. { :drink<water>, :Next-To(:smoke<Blend>) }, # 16 They drink water in a house next to the house where they smoke Blend. { :pet<zebra> }, # who owns this? );   sub MAIN { for gather solve(@houses, @facts) { #-- output say .head.sort.map(*.key.uc.fmt("%-9s")).join(' | '); say .sort.map(*.value.fmt("%-9s")).join(' | ') for .list; last; # stop after first solution } }   #| a solution has been found that fits all the facts multi sub solve(@solution, @facts [ ]) { take @solution; }   #| extend this scenario to fit the next fact multi sub solve(@scenario, [ $fact, *@facts ]) { for gather match(@scenario, |$fact) -> @houses { solve(@houses, @facts) } }   #| find all possible solutions for pairs of houses with #| properties %b, left of a house with properties %a multi sub match(@houses, :Left-Of(%a)!, *%b) { for 1 ..^ @houses { my %left-house := @houses[$_-1]; my %right-house := @houses[$_];   if plausible(%left-house, %a) && plausible(%right-house, %b) { temp %left-house ,= %a; temp %right-house ,= %b; take @houses; } } }   #| match these houses are next to each other (left or right) multi sub match(@houses, :Next-To(%b)!, *%a ) { match(@houses, |%a, :Left-Of(%b) ); match(@houses, |%b, :Left-Of(%a) ); }   #| find all possible houses that match the given properties multi sub match(@houses, *%props) { for @houses.grep({plausible($_, %props)}) -> %house { temp %house ,= %props; take @houses; } }   #| plausible if doesn't conflict with anything sub plausible(%house, %props) { ! %props.first: {%house{.key} && %house{.key} ne .value }; }  
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#REXX
REXX
/*REXX program creates & displays an ASCII art version of the Yin─Yang (taijitu) symbol.*/ parse arg s1 s2 . /*obtain optional arguments from the CL*/ if s1=='' | s1=="," then s1= 17 /*Not defined? Then use the default. */ if s2=='' | s2=="," then s2= s1 % 2 /* " " " " " " */ if s1>0 then call Yin_Yang s1 /*create & display 1st Yin-Yang symbol.*/ if s2>0 then call Yin_Yang s2 /* " " " 2nd " " */ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ in@: procedure; parse arg cy,r,x,y; return x**2 + (y-cy)**2 <= r**2 big@: /*in big circle. */ return in@( 0 , r , x, y ) semi@: /*in semi circle. */ return in@( r/2, r/2, x, y ) sB@: /*in small black circle. */ return in@( r/2, r/6, x, y ) sW@: /*in small white circle. */ return in@(-r/2, r/6, x, y ) Bsemi@: /*in black semi circle. */ return in@(-r/2, r/2, x, y ) /*──────────────────────────────────────────────────────────────────────────────────────*/ Yin_Yang: procedure; parse arg r; mX= 2; mY= 1 /*aspect multiplier for the X,Y axis.*/ do sy= r*mY to -r*mY by -1; $= /*$ ≡ an output line*/ do sx=-r*mX to r*mX; x= sx / mX; y= sy / mY /*apply aspect ratio*/ if big@() then if semi@() then if sB@() then $= $'Θ'; else $= $"°" else if Bsemi@() then if sW@() then $= $'°'; else $= $"Θ" else if x<0 then $= $'°'; else $= $"Θ" else $= $' ' end /*sy*/ say strip($, 'T') /*display one line of a Yin─Yang symbol*/ end /*sx*/; return
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
#Kitten
Kitten
define y<S..., T...> (S..., (S..., (S... -> T...) -> T...) -> T...): -> f; { f y } f call   define fac (Int32, (Int32 -> Int32) -> Int32): -> x, rec; if (x <= 1) { 1 } else { (x - 1) rec call * x }   define fib (Int32, (Int32 -> Int32) -> Int32): -> x, rec; if (x <= 2): 1 else: (x - 1) rec call -> a; (x - 2) rec call -> b; a + b   5 \fac y say // 120 10 \fib y say // 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
#Lua
Lua
  local zigzag = {}   function zigzag.new(n) local a = {} local i -- cols local j -- rows   a.n = n a.val = {}   for j = 1, n do a.val[j] = {} for i = 1, n do a.val[j][i] = 0 end end   i = 1 j = 1   local di local dj local k = 0   while k < n * n do a.val[j][i] = k k = k + 1 if i == n then j = j + 1 a.val[j][i] = k k = k + 1 di = -1 dj = 1 end if j == 1 then i = i + 1 a.val[j][i] = k k = k + 1 di = -1 dj = 1 end if j == n then i = i + 1 a.val[j][i] = k k = k + 1 di = 1 dj = -1 end if i == 1 then j = j + 1 a.val[j][i] = k k = k + 1 di = 1 dj = -1 end i = i + di j = j + dj end   setmetatable(a, {__index = zigzag, __tostring = zigzag.__tostring}) return a end   function zigzag:__tostring() local s = {} for j = 1, self.n do local row = {} for i = 1, self.n do row[i] = string.format('%d', self.val[j][i]) end s[j] = table.concat(row, ' ') end return table.concat(s, '\n') end   print(zigzag.new(5))  
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.
#Emacs_Lisp
Emacs Lisp
(defun create-doors () "Returns a list of closed doors   Each door only has two status: open or closed. If a door is closed it has the value 0, if it's open it has the value 1." (let ((return_value '(0)) ;; There is already a door in the return_value, so k starts at 1 ;; otherwise we would need to compare k against 99 and not 100 in ;; the while loop (k 1)) (while (< k 100) (setq return_value (cons 0 return_value)) (setq k (+ 1 k))) return_value))   (defun toggle-single-door (doors) "Toggle the stat of the door at the `car' position of the DOORS list   DOORS is a list of integers with either the value 0 or 1 and it represents a row of doors.   Returns a list where the `car' of the list has it's value toggled (if open it becomes closed, if closed it becomes open)." (if (= (car doors) 1) (cons 0 (cdr doors)) (cons 1 (cdr doors))))   (defun toggle-doors (doors step original-step) "Step through all elements of the doors' list and toggle a door when step is 1   DOORS is a list of integers with either the value 0 or 1 and it represents a row of doors. STEP is the number of doors we still need to transverse before we arrive at a door that has to be toggled. ORIGINAL-STEP is the value of the argument step when this function is called for the first time.   Returns a list of doors" (cond ((null doors) '()) ((= step 1) (cons (car (toggle-single-door doors)) (toggle-doors (cdr doors) original-step original-step))) (t (cons (car doors) (toggle-doors (cdr doors) (- step 1) original-step)))))   (defun main-program () "The main loop for the program" (let ((doors_list (create-doors)) (k 1) ;; We need to define max-specpdl-size and max-specpdl-size to big ;; numbers otherwise the loop reaches the max recursion depth and ;; throws an error. ;; If you want more information about these variables, press Ctrl ;; and h at the same time and then press v and then type the name ;; of the variable that you want to read the documentation. (max-specpdl-size 5000) (max-lisp-eval-depth 2000)) (while (< k 101) (setq doors_list (toggle-doors doors_list k k)) (setq k (+ 1 k))) doors_list))   (defun print-doors (doors) "This function prints the values of the doors into the current buffer.   DOORS is a list of integers with either the value 0 or 1 and it represents a row of doors. " ;; As in the main-program function, we need to set the variable ;; max-lisp-eval-depth to a big number so it doesn't reach max recursion ;; depth. (let ((max-lisp-eval-depth 5000)) (unless (null doors) (insert (int-to-string (car doors))) (print-doors (cdr doors)))))   ;; Returns a list with the final solution (main-program)   ;; Print the final solution on the buffer (print-doors (main-program))
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)
#LIL
LIL
# (not) Arrays, in LIL set a [list abc def ghi] set b [list 4 5 6] print [index $a 0] print [index $b 1] print [count $a] append b [list 7 8 9] print [count $b] print $b
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives in the red house.   The Swede has a dog.   The Dane drinks tea.   The green house is immediately to the left of the white house.   They drink coffee in the green house.   The man who smokes Pall Mall has birds.   In the yellow house they smoke Dunhill.   In the middle house they drink milk.   The Norwegian lives in the first house.   The man who smokes Blend lives in the house next to the house with cats.   In a house next to the house where they have a horse, they smoke Dunhill.   The man who smokes Blue Master drinks beer.   The German smokes Prince.   The Norwegian lives next to the blue house.   They drink water in a house next to the house where they smoke Blend. The question is, who owns the zebra? Additionally, list the solution for all the houses. Optionally, show the solution is unique. Related tasks   Dinesman's multiple-dwelling problem   Twelve statements
#REXX
REXX
/* REXX --------------------------------------------------------------- * Solve the Zebra Puzzle *--------------------------------------------------------------------*/ Call mk_perm /* compute all permutations */ Call encode /* encode the elements of the specifications */ /* ex2 .. eg16 the formalized specifications */ solutions=0 Call time 'R' Do nation_i = 1 TO 120 Nations = perm.nation_i IF ex10() Then Do Do color_i = 1 TO 120 Colors = perm.color_i IF ex5() & ex2() & ex15() Then Do Do drink_i = 1 TO 120 Drinks = perm.drink_i IF ex9() & ex4() & ex6() Then Do Do smoke_i = 1 TO 120 Smokes = perm.smoke_i IF ex14() & ex13() & ex16() & ex8() Then Do Do animal_i = 1 TO 120 Animals = perm.animal_i IF ex3() & ex7() & ex11() & ex12() Then Do /* Call out 'Drinks =' Drinks 54321 Wat Tea Mil Cof Bee */ /* Call out 'Nations=' Nations 41235 Nor Den Eng Ger Swe */ /* Call out 'Colors =' Colors 51324 Yel Blu Red Gre Whi */ /* Call out 'Smokes =' Smokes 31452 Dun Ble Pal Pri Blu */ /* Call out 'Animals=' Animals 24153 Cat Hor Bir Zeb Dog */ Call out 'House Drink Nation Colour'||, ' Smoke Animal' Do i=1 To 5 di=substr(drinks,i,1) ni=substr(nations,i,1) ci=substr(colors,i,1) si=substr(smokes,i,1) ai=substr(animals,i,1) ol.i=right(i,3)' '||left(drink.di,11), ||left(nation.ni,11), ||left(color.ci,11), ||left(smoke.si,11), ||left(animal.ai,11) Call out ol.i End solutions=solutions+1 End End /* animal_i */ End End /* smoke_i */ End End /* drink_i */ End End /* color_i */ End End /* nation_i */ Say 'Number of solutions =' solutions Say 'Solved in' time('E') 'seconds' Exit   /*------------------------------------------------------------------------------ #There are five houses. ex2: #The English man lives in the red house. ex3: #The Swede has a dog. ex4: #The Dane drinks tea. ex5: #The green house is immediately to the left of the white house. ex6: #They drink coffee in the green house. ex7: #The man who smokes Pall Mall has birds. ex8: #In the yellow house they smoke Dunhill. ex9: #In the middle house they drink milk. ex10: #The Norwegian lives in the first house. ex11: #The man who smokes Blend lives in the house next to the house with cats. ex12: #In a house next to the house where they have a horse, they smoke Dunhill. ex13: #The man who smokes Blue Master drinks beer. ex14: #The German smokes Prince. ex15: #The Norwegian lives next to the blue house. ex16: #They drink water in a house next to the house where they smoke Blend. ------------------------------------------------------------------------------*/ ex2: Return pos(England,Nations)=pos(Red,Colors) ex3: Return pos(Sweden,Nations)=pos(Dog,Animals) ex4: Return pos(Denmark,Nations)=pos(Tea,Drinks) ex5: Return pos(Green,Colors)=pos(White,Colors)-1 ex6: Return pos(Coffee,Drinks)=pos(Green,Colors) ex7: Return pos(PallMall,Smokes)=pos(Birds,Animals) ex8: Return pos(Dunhill,Smokes)=pos(Yellow,Colors) ex9: Return substr(Drinks,3,1)=Milk ex10: Return left(Nations,1)=Norway ex11: Return abs(pos(Blend,Smokes)-pos(Cats,Animals))=1 ex12: Return abs(pos(Dunhill,Smokes)-pos(Horse,Animals))=1 ex13: Return pos(BlueMaster,Smokes)=pos(Beer,Drinks) ex14: Return pos(Germany,Nations)=pos(Prince,Smokes) ex15: Return abs(pos(Norway,Nations)-pos(Blue,Colors))=1 ex16: Return abs(pos(Blend,Smokes)-pos(Water,Drinks))=1   mk_perm: Procedure Expose perm. /*--------------------------------------------------------------------- * Make all permutations of 12345 in perm.* *--------------------------------------------------------------------*/ perm.=0 n=5 Do pop=1 For n p.pop=pop End Call store Do While nextperm(n,0) Call store End Return   nextperm: Procedure Expose p. perm. Parse Arg n,i nm=n-1 Do k=nm By-1 For nm kp=k+1 If p.k<p.kp Then Do i=k Leave End End Do j=i+1 While j<n Parse Value p.j p.n With p.n p.j n=n-1 End If i>0 Then Do Do j=i+1 While p.j<p.i End Parse Value p.j p.i With p.i p.j End Return i>0   store: Procedure Expose p. perm. z=perm.0+1 _='' Do j=1 To 5 _=_||p.j End perm.z=_ perm.0=z Return   encode: Beer=1  ; Drink.1='Beer' Coffee=2  ; Drink.2='Coffee' Milk=3  ; Drink.3='Milk' Tea=4  ; Drink.4='Tea' Water=5  ; Drink.5='Water' Denmark=1  ; Nation.1='Denmark' England=2  ; Nation.2='England' Germany=3  ; Nation.3='Germany' Norway=4  ; Nation.4='Norway' Sweden=5  ; Nation.5='Sweden' Blue=1  ; Color.1='Blue' Green=2  ; Color.2='Green' Red=3  ; Color.3='Red' White=4  ; Color.4='White' Yellow=5  ; Color.5='Yellow' Blend=1  ; Smoke.1='Blend' BlueMaster=2  ; Smoke.2='BlueMaster' Dunhill=3  ; Smoke.3='Dunhill' PallMall=4  ; Smoke.4='PallMall' Prince=5  ; Smoke.5='Prince' Birds=1  ; Animal.1='Birds' Cats=2  ; Animal.2='Cats' Dog=3  ; Animal.3='Dog' Horse=4  ; Animal.4='Horse' Zebra=5  ; Animal.5='Zebra' Return   out: Say arg(1) Return
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#Ruby
Ruby
Shoes.app(:width => 470, :height => 380) do PI = Shoes::TWO_PI/2   strokewidth 1   def yin_yang(x, y, radius) fill black; stroke black arc x, y, radius, radius, -PI/2, PI/2   fill white; stroke white arc x, y, radius, radius, PI/2, -PI/2 oval x-radius/4, y-radius/2, radius/2-1   fill black; stroke black oval x-radius/4, y, radius/2-1 oval x-radius/12, y-radius/4-radius/12, radius/6-1   fill white; stroke white oval x-radius/12, y+radius/4-radius/12, radius/6-1   nofill stroke black oval x-radius/2, y-radius/2, radius end   yin_yang 190, 190, 360 yin_yang 410, 90, 90 end
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
#Klingphix
Klingphix
:fac dup 1 great [dup 1 sub fac mult] if ;     :fib dup 1 great [dup 1 sub fib swap 2 sub fib add] if ;     :test print ": " print 10 [over exec print " " print] for nl ;     @fib "fib" test @fac "fac" test   "End " input
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
#M4
M4
divert(-1)   define(`set2d',`define(`$1[$2][$3]',`$4')') define(`get2d',`defn(`$1[$2][$3]')') define(`for', `ifelse($#,0,``$0'', `ifelse(eval($2<=$3),1, `pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')') define(`show2d', `for(`x',0,decr($2), `for(`y',0,decr($3),`format(`%2d',get2d($1,x,y)) ') ')')   dnl <name>,<size> define(`zigzag', `define(`j',1)`'define(`k',1)`'for(`e',0,eval($2*$2-1), `set2d($1,decr(j),decr(k),e)`'ifelse(eval((j+k)%2),0, `ifelse(eval(k<$2),1, `define(`k',incr(k))', `define(`j',eval(j+2))')`'ifelse(eval(j>1),1, `define(`j',decr(j))')', `ifelse(eval(j<$2),1, `define(`j',incr(j))', `define(`k',eval(k+2))')`'ifelse(eval(k>1),1, `define(`k',decr(k))')')')')   divert   zigzag(`a',5) show2d(`a',5,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.
#Erlang
Erlang
  -module(hundoors).   -export([go/0]).   toggle(closed) -> open; toggle(open) -> closed.   go() -> go([closed || _ <- lists:seq(1, 100)],[], 1, 1). go([], L, N, _I) when N =:= 101 -> lists:reverse(L); go([], L, N, _I) -> go(lists:reverse(L), [], N + 1, 1); go([H|T], L, N, I) -> H2 = case I rem N of 0 -> toggle(H); _ -> H end, go(T, [H2|L], N, I + 1).  
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)
#Lingo
Lingo
a = [1,2] -- or: a = list(1,2) put a[2] -- or: put a.getAt(2) -- 2 a.append(3) put a -- [1, 2, 3] a.deleteAt(2) put a -- [1, 3] a[1] = 5 -- or: a.setAt(1, 5) put a -- [5, 3] a.sort() put a -- [3, 5]
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives in the red house.   The Swede has a dog.   The Dane drinks tea.   The green house is immediately to the left of the white house.   They drink coffee in the green house.   The man who smokes Pall Mall has birds.   In the yellow house they smoke Dunhill.   In the middle house they drink milk.   The Norwegian lives in the first house.   The man who smokes Blend lives in the house next to the house with cats.   In a house next to the house where they have a horse, they smoke Dunhill.   The man who smokes Blue Master drinks beer.   The German smokes Prince.   The Norwegian lives next to the blue house.   They drink water in a house next to the house where they smoke Blend. The question is, who owns the zebra? Additionally, list the solution for all the houses. Optionally, show the solution is unique. Related tasks   Dinesman's multiple-dwelling problem   Twelve statements
#Ruby
Ruby
CONTENT = { House: '', Nationality: %i[English Swedish Danish Norwegian German], Colour: %i[Red Green White Blue Yellow], Pet: %i[Dog Birds Cats Horse Zebra], Drink: %i[Tea Coffee Milk Beer Water], Smoke: %i[PallMall Dunhill BlueMaster Prince Blend] }   def adjacent? (n,i,g,e) (0..3).any?{|x| (n[x]==i and g[x+1]==e) or (n[x+1]==i and g[x]==e)} end   def leftof? (n,i,g,e) (0..3).any?{|x| n[x]==i and g[x+1]==e} end   def coincident? (n,i,g,e) n.each_index.any?{|x| n[x]==i and g[x]==e} end   def solve_zebra_puzzle CONTENT[:Nationality].permutation{|nation| next unless nation.first == :Norwegian # 10 CONTENT[:Colour].permutation{|colour| next unless leftof?(colour, :Green, colour, :White) # 5 next unless coincident?(nation, :English, colour, :Red) # 2 next unless adjacent?(nation, :Norwegian, colour, :Blue) # 15 CONTENT[:Pet].permutation{|pet| next unless coincident?(nation, :Swedish, pet, :Dog) # 3 CONTENT[:Drink].permutation{|drink| next unless drink[2] == :Milk # 9 next unless coincident?(nation, :Danish, drink, :Tea) # 4 next unless coincident?(colour, :Green, drink, :Coffee) # 6 CONTENT[:Smoke].permutation{|smoke| next unless coincident?(smoke, :PallMall, pet, :Birds) # 7 next unless coincident?(smoke, :Dunhill, colour, :Yellow) # 8 next unless coincident?(smoke, :BlueMaster, drink, :Beer) # 13 next unless coincident?(smoke, :Prince, nation, :German) # 14 next unless adjacent?(smoke, :Blend, pet, :Cats) # 11 next unless adjacent?(smoke, :Blend, drink, :Water) # 16 next unless adjacent?(smoke, :Dunhill,pet, :Horse) # 12 print_out(nation, colour, pet, drink, smoke) } } } } } end   def print_out (nation, colour, pet, drink, smoke) width = CONTENT.map{|x| x.flatten.map{|y|y.size}.max} fmt = width.map{|w| "%-#{w}s"}.join(" ") national = nation[ pet.find_index(:Zebra) ] puts "The Zebra is owned by the man who is #{national}","" puts fmt % CONTENT.keys, fmt % width.map{|w| "-"*w} [nation,colour,pet,drink,smoke].transpose.each.with_index(1){|x,n| puts fmt % [n,*x]} end   solve_zebra_puzzle
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#Rust
Rust
use svg::node::element::Path;   fn main() { let doc = svg::Document::new() .add(yin_yang(15.0, 1.0).set("transform", "translate(20,20)")) .add(yin_yang(6.0, 1.0).set("transform", "translate(50,11)")); svg::save("yin_yang.svg", &doc).unwrap(); } /// th - the thickness of the outline around yang fn yin_yang(r: f32, th: f32) -> Path { let (cr, cw, ccw) = (",0,1,1,.1,0z", ",0,0,1,0,", ",0,0,0,0,"); let d = format!("M0,{0} a{0},{0}{cr} M0,{1} ", r + th, -r / 3.0) // main_circle + &format!("a{0},{0}{cr} m0,{r} a{0},{0}{cr} M0,0 ", r / 6.0) // eyes + &format!("A{0},{0}{ccw}{r} A{r},{r}{cw}-{r} A{0},{0}{cw}0", r / 2.0); // yang Path::new().set("d", d).set("fill-rule", "evenodd") }
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
#Kotlin
Kotlin
// version 1.1.2   typealias Func<T, R> = (T) -> R   class RecursiveFunc<T, R>(val p: (RecursiveFunc<T, R>) -> Func<T, R>)   fun <T, R> y(f: (Func<T, R>) -> Func<T, R>): Func<T, R> { val rec = RecursiveFunc<T, R> { r -> f { r.p(r)(it) } } return rec.p(rec) }   fun fac(f: Func<Int, Int>) = { x: Int -> if (x <= 1) 1 else x * f(x - 1) }   fun fib(f: Func<Int, Int>) = { x: Int -> if (x <= 2) 1 else f(x - 1) + f(x - 2) }   fun main(args: Array<String>) { print("Factorial(1..10)  : ") for (i in 1..10) print("${y(::fac)(i)} ") print("\nFibonacci(1..10)  : ") for (i in 1..10) print("${y(::fib)(i)} ") println() }
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
#Maple
Maple
zigzag1:=proc(n) uses ArrayTools; local i,u,v,a; u:=Replicate(<-1,1>,n): v:=Vector[row](1..n,i->i*(2*i-3)): v:=Reshape(<v+~1,v+~2>,2*n): a:=Matrix(n,n): for i to n do a[...,i]:=v[i+1..i+n]; v+=u od: a end:   zigzag2:=proc(n) local i,v,a; a:=zigzag1(n); v:=Vector(1..n-1,i->i^2); for i from 2 to n do a[n+2-i..n,i]-=v[1..i-1] od; a 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.
#ERRE
ERRE
  ! "100 Doors" program for ERRE LANGUAGE ! Author: Claudio Larini ! Date: 21-Nov-2014 ! ! PC Unoptimized version translated from a QB version   PROGRAM 100DOORS   !$INTEGER   CONST N=100   DIM DOOR[N]   BEGIN   FOR STRIDE=1 TO N DO FOR INDEX=STRIDE TO N STEP STRIDE DO DOOR[INDEX]=NOT(DOOR[INDEX]) END FOR END FOR   PRINT("Open doors:";) FOR INDEX=1 TO N DO IF DOOR[INDEX] THEN PRINT(INDEX;) END IF END FOR PRINT   END PROGRAM  
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)
#Lisaac
Lisaac
+ a : ARRAY(INTEGER); a := ARRAY(INTEGER).create 0 to 9; a.put 1 to 0; a.put 3 to 1; a.item(1).print;
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives in the red house.   The Swede has a dog.   The Dane drinks tea.   The green house is immediately to the left of the white house.   They drink coffee in the green house.   The man who smokes Pall Mall has birds.   In the yellow house they smoke Dunhill.   In the middle house they drink milk.   The Norwegian lives in the first house.   The man who smokes Blend lives in the house next to the house with cats.   In a house next to the house where they have a horse, they smoke Dunhill.   The man who smokes Blue Master drinks beer.   The German smokes Prince.   The Norwegian lives next to the blue house.   They drink water in a house next to the house where they smoke Blend. The question is, who owns the zebra? Additionally, list the solution for all the houses. Optionally, show the solution is unique. Related tasks   Dinesman's multiple-dwelling problem   Twelve statements
#Scala
Scala
/* Note to the rules: * * It can further concluded that: * 5a: The green house cannot be at the h1 position * 5b: The white house cannot be at the h5 position * * 16: This rule is redundant. */   object Einstein extends App { val possibleMembers = for { // pair clues results in 78 members nationality <- List("Norwegian", "German", "Dane", "Englishman", "Swede") color <- List("Red", "Green", "Yellow", "White", "Blue") beverage <- List("Milk", "Coffee", "Tea", "Beer", "Water") animal <- List("Dog", "Horse", "Birds", "Cats", "Zebra") brand <- List("Blend", "Pall Mall", "Prince", "Blue Master", "Dunhill") if (color == "Red") == (nationality == "Englishman") // #2 if (nationality == "Swede") == (animal == "Dog") // #3 if (nationality == "Dane") == (beverage == "Tea") // #4 if (color == "Green") == (beverage == "Coffee") // #6 if (brand == "Pall Mall") == (animal == "Birds") // #7 if (brand == "Dunhill") == (color == "Yellow") // #8 if (brand == "Blue Master") == (beverage == "Beer") // #13 if (brand == "Prince") == (nationality == "German") // #14 } yield new House(nationality, color, beverage, animal, brand) val members = for { // Neighborhood clues h1 <- housesLeftOver().filter(p => (p.nationality == "Norwegian" /* #10 */) && (p.color != "Green") /* #5a */) // 28 h3 <- housesLeftOver(h1).filter(p => p.beverage == "Milk") // #9 // 24 h2 <- housesLeftOver(h1, h3).filter(_.color == "Blue") // #15 if matchMiddleBrandAnimal(h1, h2, h3, "Blend", "Cats") // #11 if matchCornerBrandAnimal(h1, h2, "Horse", "Dunhill") // #12 h4 <- housesLeftOver(h1, h2, h3).filter(_.checkAdjacentWhite(h3) /* #5 */) h5 <- housesLeftOver(h1, h2, h3, h4)   // Redundant tests if h2.checkAdjacentWhite(h1) if h3.checkAdjacentWhite(h2) if matchCornerBrandAnimal(h5, h4, "Horse", "Dunhill") if matchMiddleBrandAnimal(h2, h3, h4, "Blend", "Cats") if matchMiddleBrandAnimal(h3, h4, h5, "Blend", "Cats") } yield Seq(h1, h2, h3, h4, h5)   def matchMiddleBrandAnimal(home1: House, home2: House, home3: House, brand: String, animal: String) = (home1.animal == animal || home2.brand != brand || home3.animal == animal) && (home1.brand == brand || home2.animal != animal || home3.brand == brand)   def matchCornerBrandAnimal(corner: House, inner: House, animal: String, brand: String) = (corner.brand != brand || inner.animal == animal) && (corner.animal == animal || inner.brand != brand)   def housesLeftOver(pickedHouses: House*): List[House] = { possibleMembers.filter(house => pickedHouses.forall(_.totalUnEqual(house))) }   class House(val nationality: String, val color: String, val beverage: String, val animal: String, val brand: String) { override def toString = { f"$nationality%10s, ${color + ", "}%-8s$beverage,\t$animal,\t$brand." }   def totalUnEqual(home2: House) = this.animal != home2.animal && this.beverage != home2.beverage && this.brand != home2.brand && this.color != home2.color && this.nationality != home2.nationality   //** Checks if the this green house is next to the other white house*/ def checkAdjacentWhite(home2: House) = (this.color == "Green") == (home2.color == "White") // #5 }   { // Main program val beest = "Zebra" members.flatMap(p => p.filter(p => p.animal == beest)). foreach(s => println(s"The ${s.nationality} is the owner of the ${beest.toLowerCase}."))   println(s"The ${members.size} solution(s) are:") members.foreach(solution => solution.zipWithIndex.foreach(h => println(s"House ${h._2 + 1} ${h._1}"))) } } // loc 58
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#Scala
Scala
import scala.swing.Swing.pair2Dimension import scala.swing.{ MainFrame, Panel } import java.awt.{ Color, Graphics2D }   object YinYang extends scala.swing.SimpleSwingApplication { var preferedSize = 500   /** Draw a Taijitu symbol on the given graphics context. */ def drawTaijitu(g: Graphics2D, size: Int) { val sizeMinsOne = size - 1 // Preserve the color for the caller val colorSave = g.getColor()   g.setColor(Color.WHITE) // Use fillOval to draw a filled in circle g.fillOval(0, 0, sizeMinsOne, sizeMinsOne)   g.setColor(Color.BLACK) // Use fillArc to draw part of a filled in circle g.fillArc(0, 0, sizeMinsOne, sizeMinsOne, 270, 180) g.fillOval(size / 4, size / 2, size / 2, size / 2)   g.setColor(Color.WHITE) g.fillOval(size / 4, 0, size / 2, size / 2) g.fillOval(7 * size / 16, 11 * size / 16, size / 8, size / 8)   g.setColor(Color.BLACK) g.fillOval(7 * size / 16, 3 * size / 16, size / 8, size / 8) // Use drawOval to draw an empty circle for the outside border g.drawOval(0, 0, sizeMinsOne, sizeMinsOne)   // Restore the color for the caller g.setColor(colorSave) }   def top = new MainFrame { title = "Rosetta Code >>> Yin Yang Generator | Language: Scala" contents = gui(preferedSize)   def gui(sizeInterior: Int) = new Panel() { preferredSize = (sizeInterior, sizeInterior)   /** Draw a Taijitu symbol in this graphics context. */ override def paintComponent(graphics: Graphics2D) = { super.paintComponent(graphics)   // Color in the background of the image background = Color.RED drawTaijitu(graphics, sizeInterior) } } // def gui( }   override def main(args: Array[String]) = { preferedSize = args.headOption.map(_.toInt).getOrElse(preferedSize) super.main(args) } }
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
#Lambdatalk
Lambdatalk
  1) defining the Ycombinator {def Y {lambda {:f} {:f :f}}}   2) defining non recursive functions 2.1) factorial {def almost-fac {lambda {:f :n} {if {= :n 1} then 1 else {* :n {:f :f {- :n 1}}}}}}   2.2) fibonacci {def almost-fibo {lambda {:f :n} {if {<  :n 2} then 1 else {+ {:f :f {- :n 1}} {:f :f {- :n 2}}}}}}   3) testing {{Y almost-fac} 6} -> 720 {{Y almost-fibo} 8} -> 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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ZigZag[size_Integer/;size>0]:=Module[{empty=ConstantArray[0,{size,size}]}, empty=ReplacePart[empty,{i_,j_}:>1/2 (i+j)^2-(i+j)/2-i (1-Mod[i+j,2])-j Mod[i+j,2]]; ReplacePart[empty,{i_,j_}/;i+j>size+1:> size^2-tmp[[size-i+1,size-j+1]]-1] ]
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.
#Euler_Math_Toolbox
Euler Math Toolbox
  >function Doors () ... $ doors:=zeros(1,100); $ for i=1 to 100 $ for j=i to 100 step i $ doors[j]=!doors[j]; $ end; $ end; $ return doors $endfunction >nonzeros(Doors()) [ 1 4 9 16 25 36 49 64 81 100 ]  
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)
#Little
Little
String fruit[] = {"apple", "orange", "Pear"}
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives in the red house.   The Swede has a dog.   The Dane drinks tea.   The green house is immediately to the left of the white house.   They drink coffee in the green house.   The man who smokes Pall Mall has birds.   In the yellow house they smoke Dunhill.   In the middle house they drink milk.   The Norwegian lives in the first house.   The man who smokes Blend lives in the house next to the house with cats.   In a house next to the house where they have a horse, they smoke Dunhill.   The man who smokes Blue Master drinks beer.   The German smokes Prince.   The Norwegian lives next to the blue house.   They drink water in a house next to the house where they smoke Blend. The question is, who owns the zebra? Additionally, list the solution for all the houses. Optionally, show the solution is unique. Related tasks   Dinesman's multiple-dwelling problem   Twelve statements
#Sidef
Sidef
var CONTENT = Hash( :House => nil, :Nationality => [:English, :Swedish, :Danish, :Norwegian, :German], :Colour => [:Red, :Green, :White, :Blue, :Yellow], :Pet => [:Dog, :Birds, :Cats, :Horse, :Zebra], :Drink => [:Tea, :Coffee, :Milk, :Beer, :Water], :Smoke => [:PallMall, :Dunhill, :BlueMaster, :Prince, :Blend] )   func adjacent(n,i,g,e) { (0..3).any {|x| (n[x]==i && g[x+1]==e) || (n[x+1]==i && g[x]==e) } }   func leftof(n,i,g,e) { (0..3).any {|x| n[x]==i && g[x+1]==e } }   func coincident(n,i,g,e) { n.indices.any {|x| n[x]==i && g[x]==e } }   func solve { CONTENT{:Nationality}.permutations{|*nation| nation.first == :Norwegian -> && CONTENT{:Colour}.permutations {|*colour| leftof(colour,:Green,colour,:White) -> && coincident(nation,:English,colour,:Red) -> && adjacent(nation,:Norwegian,colour,:Blue) -> && CONTENT{:Pet}.permutations {|*pet| coincident(nation,:Swedish,pet,:Dog) -> && CONTENT{:Drink}.permutations {|*drink| drink[2] == :Milk -> && coincident(nation,:Danish,drink,:Tea) -> && coincident(colour,:Green,drink,:Coffee) -> && CONTENT{:Smoke}.permutations {|*smoke| coincident(smoke,:PallMall,pet,:Birds) -> && coincident(smoke,:Dunhill,colour,:Yellow) -> && coincident(smoke,:BlueMaster,drink,:Beer) -> && coincident(smoke,:Prince,nation,:German) -> && adjacent(smoke,:Blend,pet,:Cats) -> && adjacent(smoke,:Blend,drink,:Water) -> && adjacent(smoke,:Dunhill,pet,:Horse) -> && return [nation,colour,pet,drink,smoke] } } } } } }   var res = solve(); var keys = [:House, :Nationality, :Colour, :Pet, :Drink, :Smoke] var width = keys.map{ .len } var fmt = width.map{|w| "%-#{w+2}s" }.join(" ") say "The Zebra is owned by the man who is #{res[0][res[2].first_index(:Zebra)]}\n" say (fmt % keys..., "\n", fmt % width.map{|w| "-"*w }...) res[0].indices.map{|i| res.map{|a| a[i] }}.each_kv {|k,v| say fmt%(k,v...) }
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#Scilab
Scilab
R = 1; //outer radius of first image scale = 0.5; //scale of the second image   scf(0); clf(); set(gca(),'isoview','on'); xname('Yin and Yang');   //First one n_p = 100; //number of points per arc angles = []; //angles for each arc angles = linspace(%pi/2, 3*%pi/2, n_p); Arcs = zeros(7,n_p);   Arcs(1,:) = R * exp(%i * angles); plot2d(real(Arcs(1,:)),imag(Arcs(1,:))); line = gce(); set(line.children,'polyline_style',5); set(line.children,'foreground',8);   Arcs(2,:) = -%i*R/2 + R/2 * exp(%i * angles); plot2d(real(Arcs(2,:)),imag(Arcs(2,:))); line = gce(); set(line.children,'polyline_style',5);   angles = []; angles = linspace(-%pi/2, %pi/2, n_p);   Arcs(3,:) = R * exp(%i * angles); plot2d(real(Arcs(3,:)), imag(Arcs(3,:))); line = gce(); set(line.children,'polyline_style',5);   Arcs(4,:) = %i*R/2 + R/2 * exp(%i * angles); plot2d(real(Arcs(4,:)),imag(Arcs(4,:))); line = gce(); set(line.children,'polyline_style',5); set(line.children,'foreground',8);   angles = []; angles = linspace(0, 2*%pi, n_p);   Arcs(5,:) = %i*R/2 + R/8 * exp(%i * angles); plot2d(real(Arcs(5,:)),imag(Arcs(5,:))); line = gce(); set(line.children,'polyline_style',5);   Arcs(6,:) = -%i*R/2 + R/8 * exp(%i * angles); plot2d(real(Arcs(6,:)),imag(Arcs(6,:))); line = gce(); set(line.children,'polyline_style',5); set(line.children,'foreground',8);   Arcs(7,:) = R * exp(%i * angles); plot2d(real(Arcs(7,:)),imag(Arcs(7,:))); set(gca(),'axes_visible',['off','off','off']);   //Scaling new_pos = R + 2*R*scale; Arcs = new_pos + Arcs .* scale;   plot2d(real(Arcs(1,:)),imag(Arcs(1,:))); line = gce(); set(line.children,'polyline_style',5); set(line.children,'foreground',8);   plot2d(real(Arcs(2,:)),imag(Arcs(2,:))); line = gce(); set(line.children,'polyline_style',5);   plot2d(real(Arcs(3,:)), imag(Arcs(3,:))); line = gce(); set(line.children,'polyline_style',5);   plot2d(real(Arcs(4,:)),imag(Arcs(4,:))); line = gce(); set(line.children,'polyline_style',5); set(line.children,'foreground',8);   plot2d(real(Arcs(5,:)),imag(Arcs(5,:))); line = gce(); set(line.children,'polyline_style',5);   plot2d(real(Arcs(6,:)),imag(Arcs(6,:))); line = gce(); set(line.children,'polyline_style',5); set(line.children,'foreground',8);   plot2d(real(Arcs(7,:)),imag(Arcs(7,:))); set(gca(),'axes_visible',['off','off','off']);
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i"; include "math.s7i"; include "draw.s7i"; include "keybd.s7i";   const proc: yinYang (in integer: xPos, in integer: yPos, in integer: size) is func begin pieslice(xPos, yPos, size, 3.0 * PI / 2.0, PI, black); pieslice(xPos, yPos, size, PI / 2.0, PI, white); fcircle(xPos, yPos - size div 2, size div 2, white); fcircle(xPos, yPos + size div 2, size div 2, black); fcircle(xPos, yPos - size div 2, size div 6, black); fcircle(xPos, yPos + size div 2, size div 6, white); circle(xPos, yPos, size, black); end func;   const proc: main is func begin screen(640, 480); clear(white); KEYBOARD := GRAPH_KEYBOARD; yinYang(100, 100, 80); yinYang(400, 250, 200); readln(KEYBOARD); end func;
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
#Lua
Lua
Y = function (f) return function(...) return (function(x) return x(x) end)(function(x) return f(function(y) return x(x)(y) end) end)(...) end end  
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
#MATLAB
MATLAB
function matrix = zigZag(n)   %This is very unintiutive. This algorithm parameterizes the %zig-zagging movement along the matrix indicies. The easiest way to see %what this algorithm does is to go through line-by-line and write out %what the algorithm does on a peace of paper.   matrix = zeros(n); counter = 1; flipCol = true; flipRow = false;   %This for loop does the top-diagonal of the matrix for i = (2:n) row = (1:i); column = (1:i);   %Causes the zig-zagging. Without these conditionals, %you would end up with a diagonal matrix. %To see what happens, comment these conditionals out. if flipCol column = fliplr(column); flipRow = true; flipCol = false; elseif flipRow row = fliplr(row); flipRow = false; flipCol = true; end   %Selects a diagonal of the zig-zag matrix and places the %correct integer value in each index along that diagonal for j = (1:numel(row)) matrix(row(j),column(j)) = counter; counter = counter + 1; end end   %This for loop does the bottom-diagonal of the matrix for i = (2:n) row = (i:n); column = (i:n);   %Causes the zig-zagging. Without these conditionals, %you would end up with a diagonal matrix. %To see what happens comment these conditionals out. if flipCol column = fliplr(column); flipRow = true; flipCol = false; elseif flipRow row = fliplr(row); flipRow = false; flipCol = true; end   %Selects a diagonal of the zig-zag matrix and places the %correct integer value in each index along that diagonal for j = (1:numel(row)) matrix(row(j),column(j)) = counter; counter = counter + 1; end 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.
#Euphoria
Euphoria
-- doors.ex include std/console.e sequence doors doors = repeat( 0, 100 ) -- 1 to 100, initialised to false   for pass = 1 to 100 do for door = pass to 100 by pass do --printf( 1, "%d", doors[door] ) --printf( 1, "%d", not doors[door] ) doors[door] = not doors[door] end for end for   sequence oc   for i = 1 to 100 do if doors[i] then oc = "open" else oc = "closed" end if printf( 1, "door %d is %s\n", { i, oc } ) end for  
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)
#Logo
Logo
array 5  ; default origin is 1, every item is empty (array 5 0)  ; custom origin make "a {1 2 3 4 5}  ; array literal setitem 1 :a "ten  ; Logo is dynamic; arrays can contain different types print item 1 :a  ; ten
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives in the red house.   The Swede has a dog.   The Dane drinks tea.   The green house is immediately to the left of the white house.   They drink coffee in the green house.   The man who smokes Pall Mall has birds.   In the yellow house they smoke Dunhill.   In the middle house they drink milk.   The Norwegian lives in the first house.   The man who smokes Blend lives in the house next to the house with cats.   In a house next to the house where they have a horse, they smoke Dunhill.   The man who smokes Blue Master drinks beer.   The German smokes Prince.   The Norwegian lives next to the blue house.   They drink water in a house next to the house where they smoke Blend. The question is, who owns the zebra? Additionally, list the solution for all the houses. Optionally, show the solution is unique. Related tasks   Dinesman's multiple-dwelling problem   Twelve statements
#Standard_ML
Standard ML
  (* Attributes and values *) val str_attributes = Vector.fromList ["Color", "Nation", "Drink", "Pet", "Smoke"] val str_colors = Vector.fromList ["Red", "Green", "White", "Yellow", "Blue"] val str_nations = Vector.fromList ["English", "Swede", "Dane", "German", "Norwegian"] val str_drinks = Vector.fromList ["Tea", "Coffee", "Milk", "Beer", "Water"] val str_pets = Vector.fromList ["Dog", "Birds", "Cats", "Horse", "Zebra"] val str_smokes = Vector.fromList ["PallMall", "Dunhill", "Blend", "BlueMaster", "Prince"]   val (Color, Nation, Drink, Pet, Smoke) = (0, 1, 2, 3, 4) (* Attributes *) val (Red, Green, White, Yellow, Blue) = (0, 1, 2, 3, 4) (* Color *) val (English, Swede, Dane, German, Norwegian) = (0, 1, 2, 3, 4) (* Nation *) val (Tea, Coffee, Milk, Beer, Water) = (0, 1, 2, 3, 4) (* Drink *) val (Dog, Birds, Cats, Horse, Zebra) = (0, 1, 2, 3, 4) (* Pet *) val (PallMall, Dunhill, Blend, BlueMaster, Prince) = (0, 1, 2, 3, 4) (* Smoke *)   type attr = int type value = int type houseno = int   (* Rules *) datatype rule = AttrPairRule of (attr * value) * (attr * value) | NextToRule of (attr * value) * (attr * value) | LeftOfRule of (attr * value) * (attr * value)   (* Conditions *) val rules = [ AttrPairRule ((Nation, English), (Color, Red)), (* #02 *) AttrPairRule ((Nation, Swede), (Pet, Dog)), (* #03 *) AttrPairRule ((Nation, Dane), (Drink, Tea)), (* #04 *) LeftOfRule ((Color, Green), (Color, White)), (* #05 *) AttrPairRule ((Color, Green), (Drink, Coffee)), (* #06 *) AttrPairRule ((Smoke, PallMall), (Pet, Birds)), (* #07 *) AttrPairRule ((Smoke, Dunhill), (Color, Yellow)), (* #08 *) NextToRule ((Smoke, Blend), (Pet, Cats)), (* #11 *) NextToRule ((Smoke, Dunhill), (Pet, Horse)), (* #12 *) AttrPairRule ((Smoke, BlueMaster), (Drink, Beer)), (* #13 *) AttrPairRule ((Nation, German), (Smoke, Prince)), (* #14 *) NextToRule ((Nation, Norwegian), (Color, Blue)), (* #15 *) NextToRule ((Smoke, Blend), (Drink, Water))] (* #16 *)     type house = value option * value option * value option * value option * value option   fun houseval ((a, b, c, d, e) : house, 0 : attr) = a | houseval ((a, b, c, d, e) : house, 1 : attr) = b | houseval ((a, b, c, d, e) : house, 2 : attr) = c | houseval ((a, b, c, d, e) : house, 3 : attr) = d | houseval ((a, b, c, d, e) : house, 4 : attr) = e | houseval _ = raise Domain   fun sethouseval ((a, b, c, d, e) : house, 0 : attr, a2 : value option) = (a2, b, c, d, e ) | sethouseval ((a, b, c, d, e) : house, 1 : attr, b2 : value option) = (a, b2, c, d, e ) | sethouseval ((a, b, c, d, e) : house, 2 : attr, c2 : value option) = (a, b, c2, d, e ) | sethouseval ((a, b, c, d, e) : house, 3 : attr, d2 : value option) = (a, b, c, d2, e ) | sethouseval ((a, b, c, d, e) : house, 4 : attr, e2 : value option) = (a, b, c, d, e2) | sethouseval _ = raise Domain   fun getHouseVal houses (no, attr) = houseval (Array.sub (houses, no), attr) fun setHouseVal houses (no, attr, newval) = Array.update (houses, no, sethouseval (Array.sub (houses, no), attr, newval))     fun match (house, (rule_attr, rule_val)) = let val value = houseval (house, rule_attr) in isSome value andalso valOf value = rule_val end   fun matchNo houses (no, rule) = match (Array.sub (houses, no), rule)   fun compare (house1, house2, ((rule_attr1, rule_val1), (rule_attr2, rule_val2))) = let val val1 = houseval (house1, rule_attr1) val val2 = houseval (house2, rule_attr2) in if isSome val1 andalso isSome val2 then (valOf val1 = rule_val1 andalso valOf val2 <> rule_val2) orelse (valOf val1 <> rule_val1 andalso valOf val2 = rule_val2) else false end   fun compareNo houses (no1, no2, rulepair) = compare (Array.sub (houses, no1), Array.sub (houses, no2), rulepair)     fun invalid houses no (AttrPairRule rulepair) = compareNo houses (no, no, rulepair)   | invalid houses no (NextToRule rulepair) = (if no > 0 then compareNo houses (no, no-1, rulepair) else true) andalso (if no < 4 then compareNo houses (no, no+1, rulepair) else true)   | invalid houses no (LeftOfRule rulepair) = if no > 0 then compareNo houses (no-1, no, rulepair) else matchNo houses (no, #1rulepair)     (* * val checkRulesForNo : house vector -> houseno -> bool * Check all rules for a house; * Returns true, when one rule was invalid. *) fun checkRulesForNo (houses : house array) no = let exception RuleError in (map (fn rule => if invalid houses no rule then raise RuleError else ()) rules; false) handle RuleError => true end   (* * val checkAll : house vector -> bool * Check all rules; * return true if everything is ok. *) fun checkAll (houses : house array) = let exception RuleError in (map (fn no => if checkRulesForNo houses no then raise RuleError else ()) [0,1,2,3,4]; true) handle RuleError => false end     (* * * House printing for debugging * *)   fun valToString (0, SOME a) = Vector.sub (str_colors, a) | valToString (1, SOME b) = Vector.sub (str_nations, b) | valToString (2, SOME c) = Vector.sub (str_drinks, c) | valToString (3, SOME d) = Vector.sub (str_pets, d) | valToString (4, SOME e) = Vector.sub (str_smokes, e) | valToString _ = "-"   (* * Note: * Format needs SML NJ *) fun printHouse no ((a, b, c, d, e) : house) = ( print (Format.format "%12d" [Format.LEFT (12, Format.INT no)]); print (Format.format "%12s%12s%12s%12s%12s" (map (fn (x, y) => Format.LEFT (12, Format.STR (valToString (x, y)))) [(0,a), (1,b), (2,c), (3,d), (4,e)])); print ("\n") )   fun printHouses houses = ( print (Format.format "%12s" [Format.LEFT (12, Format.STR "House")]); Vector.map (fn a => print (Format.format "%12s" [Format.LEFT (12, Format.STR a)])) str_attributes; print "\n"; Array.foldli (fn (no, house, _) => printHouse no house) () houses )   (* * * Solving * *)   exception SolutionFound   fun search (houses : house array, used : bool Array2.array) (no : houseno, attr : attr) = let val i = ref 0 val (nextno, nextattr) = if attr < 4 then (no, attr + 1) else (no + 1, 0) in if isSome (getHouseVal houses (no, attr)) then ( search (houses, used) (nextno, nextattr) ) else ( while (!i < 5) do ( if Array2.sub (used, attr, !i) then () else ( Array2.update (used, attr, !i, true); setHouseVal houses (no, attr, SOME (!i));   if checkAll houses then ( if no = 4 andalso attr = 4 then raise SolutionFound else search (houses, used) (nextno, nextattr) ) else (); Array2.update (used, attr, !i, false) ); (* else *) i := !i + 1 ); (* do *) setHouseVal houses (no, attr, NONE) ) (* else *) end   fun init () = let val unknown : house = (NONE, NONE, NONE, NONE, NONE) val houses = Array.fromList [unknown, unknown, unknown, unknown, unknown] val used = Array2.array (5, 5, false) in (houses, used) end   fun solve () = let val (houses, used) = init() in setHouseVal houses (2, Drink, SOME Milk); (* #09 *) Array2.update (used, Drink, Milk, true); setHouseVal houses (0, Nation, SOME Norwegian); (* #10 *) Array2.update (used, Nation, Norwegian, true); (search (houses, used) (0, 0); NONE) handle SolutionFound => SOME houses end   (* * * Execution * *)   fun main () = let val solution = solve() in if isSome solution then printHouses (valOf solution) else print "No solution found!\n" end  
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#Sidef
Sidef
func circle (rad, cx, cy, fill='white', stroke='black') { say "<circle cx='#{cx}' cy='#{cy}' r='#{rad}' fill='#{fill}' stroke='#{stroke}' stroke-width='1'/>"; }   func yin_yang (rad, cx, cy, fill='white', stroke='black', angle=90) { var (c, w) = (1, 0); angle != 0 && say "<g transform='rotate(#{angle}, #{cx}, #{cy})'>"; circle(rad, cx, cy, fill, stroke); say("<path d='M #{cx} #{cy + rad}A #{rad/2} #{rad/2} 0 0 #{c} #{cx} #{cy} ", "#{rad/2} #{rad/2} 0 0 #{w} #{cx} #{cy - rad} #{rad} #{rad} 0 0 #{c} #{cx} ", "#{cy + rad} z' fill='#{stroke}' stroke='none' />"); circle(rad/5, cx, cy + rad/2, fill, stroke); circle(rad/5, cx, cy - rad/2, stroke, fill); angle != 0 && say "</g>"; }   say '<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink">';   yin_yang(40, 50, 50); yin_yang(20, 120, 120);   say '</svg>';
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
#M2000_Interpreter
M2000 Interpreter
  Module Ycombinator { \\ y() return value. no use of closure y=lambda (g, x)->g(g, x) Print y(lambda (g, n as decimal)->if(n=0->1, n*g(g, n-1)), 10)=3628800 ' true Print y(lambda (g, n)->if(n<=1->n,g(g, n-1)+g(g, n-2)), 10)=55 ' true   \\ Using closure in y, y() return function y=lambda (g)->lambda g (x) -> g(g, x) fact=y((lambda (g, n as decimal)-> if(n=0->1, n*g(g, n-1)))) Print fact(6)=720, fact(24)=620448401733239439360000@ fib=y(lambda (g, n)->if(n<=1->n, g(g, n-1)+g(g, n-2))) Print fib(10)=55 } Ycombinator  
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
#Maxima
Maxima
zigzag(n) := block([a, i, j], a: zeromatrix(n, n), i: 1, j: 1, for k from 0 thru n*n - 1 do ( a[i, j]: k, if evenp(i + j) then ( if j < n then j: j + 1 else i: i + 2, if i > 1 then i: i - 1 ) else ( if i < n then i: i + 1 else j: j + 2, if j > 1 then j: j - 1 ) ), a)$   zigzag(5); /* matrix([ 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.
#Excel
Excel
  =IF($A2/C$1=INT($A2/C$1),IF(B2=0,1,IF(B2=1,0)),B2)  
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)
#LOLCODE
LOLCODE
HAI 1.4 BTW declaring array I HAS A array ITZ A BUKKIT BTW store values in array array HAS A one ITZ 1 array HAS A two ITZ 2 array HAS A three ITZ 3 array HAS A string ITZ "MEOW" OBTW there is no way to get an element of an array at a specified index in LOLCODE therefore, you can't really iterate through an array TLDR BTW get the element of array VISIBLE array'Z one VISIBLE array'Z two VISIBLE array'Z three VISIBLE array'Z string KTHXBYE
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives in the red house.   The Swede has a dog.   The Dane drinks tea.   The green house is immediately to the left of the white house.   They drink coffee in the green house.   The man who smokes Pall Mall has birds.   In the yellow house they smoke Dunhill.   In the middle house they drink milk.   The Norwegian lives in the first house.   The man who smokes Blend lives in the house next to the house with cats.   In a house next to the house where they have a horse, they smoke Dunhill.   The man who smokes Blue Master drinks beer.   The German smokes Prince.   The Norwegian lives next to the blue house.   They drink water in a house next to the house where they smoke Blend. The question is, who owns the zebra? Additionally, list the solution for all the houses. Optionally, show the solution is unique. Related tasks   Dinesman's multiple-dwelling problem   Twelve statements
#Tailspin
Tailspin
  processor EinsteinSolver @: [{|{}|}]; // A list of possible relations, start with one relation with an empty tuple $ -> \( when <[](1..)> do def variableRange: $(1); @EinsteinSolver: [($@EinsteinSolver(1) join {|{by $variableRange...}|})]; $(2..last) -> # \) -> !VOID   sink isFact def fact: $; def parts: [$... -> {$}]; @EinsteinSolver: [$@EinsteinSolver... -> \( def new: ($ matching {|$fact|}); @: $; $parts... -> @: ($@ notMatching {| $ |}); ($new union $@) ! \)]; end isFact   operator (a nextTo&{byField:, bMinusA:} b) data ES_temp__ <"1"> local @EinsteinSolver: [$@EinsteinSolver... -> \( def in: $; def temp: {| $... -> {$, ES_temp__: $(byField)::raw} |}; def numbers: [$temp({ES_temp__:})... -> $.ES_temp__]; $numbers... -> \( def aNumber: $; def bNumbers: [$bMinusA... -> $ + $aNumber]; def new: ($temp matching {| {$a, ES_temp__: $aNumber} |}); @: ($new union (($temp notMatching {| $a |}) notMatching {| {ES_temp__: $aNumber} |})); $numbers... -> \(<~ ?($bNumbers <[<=$>]>)> $! \) -> @: ($@ notMatching {| {$b, ES_temp__: $} |}); ($in matching $@) ! \) ! \)]; end nextTo   source solutions&{required:} templates resolve&{rows:} when <?($rows <=1>)?($::count <=1>)> do $ ! when <?($::count <$rows..>)> do def in: $; def selected: [$...] -> $(1); ($in minus {|$selected|}) -> resolve&{rows: $rows} ! // Alternative solutions @: $; $selected... -> {$} -> @: ($@ notMatching {| $ |}); [$@ -> resolve&{rows: $rows-1}] -> \( when <~=[]> do $... -> {| $..., $selected |} ! \) ! end resolve [$@EinsteinSolver... -> resolve&{rows: $required}] ! end solutions end EinsteinSolver   def numbers: [1..5 -> (no: $)]; def nationalities: [['Englishman', 'Swede', 'Dane', 'Norwegian', 'German']... -> (nationality:$)]; def colours: [['red', 'green', 'white', 'yellow', 'blue']... -> (colour:$)]; def pets: [['dog', 'birds', 'cats', 'horse', 'zebra']... -> (pet:$)]; def drinks: [['tea', 'coffee', 'milk', 'beer', 'water']... -> (drink:$)]; def smokes: [['Pall Mall', 'Dunhill', 'Blend', 'Blue Master', 'Prince']... -> (smoke: $)];     def solutions: [$numbers, $nationalities, $colours, $pets, $drinks, $smokes] -> \( def solver: $ -> EinsteinSolver;   {nationality: 'Englishman', colour: 'red'} -> !solver::isFact {nationality: 'Swede', pet: 'dog'} -> !solver::isFact {nationality: 'Dane', drink: 'tea'} -> !solver::isFact ({colour: 'green'} solver::nextTo&{byField: :(no:), bMinusA: [1]} {colour: 'white'}) -> !VOID {drink: 'coffee', colour: 'green'} -> !solver::isFact {smoke: 'Pall Mall', pet: 'birds'} -> !solver::isFact {colour: 'yellow', smoke: 'Dunhill'} -> !solver::isFact {no: 3, drink: 'milk'} -> !solver::isFact {nationality: 'Norwegian', no: 1} -> !solver::isFact ({smoke: 'Blend'} solver::nextTo&{byField: :(no:), bMinusA: [-1, 1]} {pet: 'cats'}) -> !VOID ({smoke: 'Dunhill'} solver::nextTo&{byField: :(no:), bMinusA: [-1, 1]} {pet: 'horse'}) -> !VOID {smoke: 'Blue Master', drink: 'beer'} -> !solver::isFact {nationality: 'German', smoke: 'Prince'} -> !solver::isFact ({nationality: 'Norwegian'} solver::nextTo&{byField: :(no:), bMinusA: [-1, 1]} {colour: 'blue'}) -> !VOID ({drink: 'water'} solver::nextTo&{byField: :(no:), bMinusA: [-1, 1]} {smoke: 'Blend'}) -> !VOID   $solver::solutions&{required: 5}! \);   $solutions... -> ($ matching {| {pet: 'zebra'} |}) ... -> 'The $.nationality; owns the zebra.   ' -> !OUT::write   $solutions -> \[i]('Solution $i;: $... -> '$; '; '! \)... -> !OUT::write 'No more solutions ' -> !OUT::write  
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#SVG_3
SVG
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="600" height="600">   <!-- We create the symbol in the rectangle from (0, 0) to (1, 1) and then translate it so it's centered on the origin. --> <symbol id="yinyang"> <g transform="translate(-0.5, -0.5)"> <!-- A white circle, for the bulk of the left-hand part --> <circle cx="0.5" cy="0.5" r="0.5" fill="white"/> <!-- A black semicircle, for the bulk of the right-hand part --> <path d="M 0.5,0 A 0.5,0.5 0 0,1 0.5,1 z" fill="black"/> <!-- Circles to extend each part --> <circle cx="0.5" cy="0.25" r="0.25" fill="white"/> <circle cx="0.5" cy="0.75" r="0.25" fill="black"/> <!-- The spots --> <circle cx="0.5" cy="0.25" r="0.1" fill="black"/> <circle cx="0.5" cy="0.75" r="0.1" fill="white"/> <!-- An outline for the whole shape --> <circle cx="0.5" cy="0.5" r="0.5" fill="none" stroke="gray" stroke-width=".01"/> </g> </symbol>   <use xlink:href="#yinyang" transform="translate(125, 125) scale(200, 200)"/>   <use xlink:href="#yinyang" transform="translate(375, 375) scale(400, 400)"/>   </svg>
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
#MANOOL
MANOOL
  { {extern "manool.org.18/std/0.3/all"} in : let { Y = {proc {F} as {proc {X} as X[X]}[{proc {X} with {F} as F[{proc {Y} with {X} as X[X][Y]}]}]} } in { for { N = Range[10] } do  : (WriteLine) Out; N "! = " {Y: proc {Rec} as {proc {N} with {Rec} as: if N == 0 then 1 else N * Rec[N - 1]}}$[N] } { for { N = Range[10] } do  : (WriteLine) Out; "Fib " N " = " {Y: proc {Rec} as {proc {N} with {Rec} as: if N == 0 then 0 else: if N == 1 then 1 else Rec[N - 2] + Rec[N - 1]}}$[N] } }  
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
#Maple
Maple
  > Y:=f->(x->x(x))(g->f((()->g(g)(args)))): > Yfac:=Y(f->(x->`if`(x<2,1,x*f(x-1)))): > seq( Yfac( i ), i = 1 .. 10 ); 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800 > Yfib:=Y(f->(x->`if`(x<2,x,f(x-1)+f(x-2)))): > seq( Yfib( i ), i = 1 .. 10 ); 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
#MiniZinc
MiniZinc
  %Zigzag Matrix. Nigel Galloway, February 3rd., 2020 int: Size; array [1..Size,1..Size] of var 1..Size*Size: zigzag; constraint zigzag[1,1]=1 /\ zigzag[Size,Size]=Size*Size; constraint forall(n in {2*g | g in 1..Size div 2})(zigzag[1,n]=zigzag[1,n-1]+1 /\ forall(g in 2..n)(zigzag[g,n-g+1]=zigzag[g-1,n-g+2]+1)); constraint forall(n in {2*g + ((Size-1) mod 2) | g in 1..(Size-1) div 2})(zigzag[n,Size]=zigzag[n-1,Size]+1 /\ forall(g in 1..Size-n)(zigzag[n+g,Size-g]=zigzag[n+g-1,Size-g+1]+1)); constraint forall(n in {2*g+1 | g in 1..(Size-1) div 2})(zigzag[n,1]=zigzag[n-1,1]+1 /\ forall(g in 2..n)(zigzag[n-g+1,g]=zigzag[n-g+2,g-1]+1)); constraint forall(n in {2*g+((Size) mod 2) | g in 1..(Size-1) div 2})(zigzag[Size,n]=zigzag[Size,n-1]+1 /\ forall(g in 1..Size-n)(zigzag[Size-g,n+g]=zigzag[Size-g+1,n+g-1]+1)); output [show2d(zigzag)];  
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.23
F#
let answerDoors = let ToggleNth n (lst:bool array) = // Toggle every n'th door [(n-1) .. n .. 99] // For each appropriate door |> Seq.iter (fun i -> lst.[i] <- not lst.[i]) // toggle it let doors = Array.create 100 false // Initialize all doors to closed Seq.iter (fun n -> ToggleNth n doors) [1..100] // toggle the appropriate doors for each pass doors // Initialize all doors to closed  
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)
#LSE64
LSE64
10 myArray :array 0 array 5 [] ! # store 0 at the sixth cell in the array array 5 [] @ # contents of sixth cell in array
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives in the red house.   The Swede has a dog.   The Dane drinks tea.   The green house is immediately to the left of the white house.   They drink coffee in the green house.   The man who smokes Pall Mall has birds.   In the yellow house they smoke Dunhill.   In the middle house they drink milk.   The Norwegian lives in the first house.   The man who smokes Blend lives in the house next to the house with cats.   In a house next to the house where they have a horse, they smoke Dunhill.   The man who smokes Blue Master drinks beer.   The German smokes Prince.   The Norwegian lives next to the blue house.   They drink water in a house next to the house where they smoke Blend. The question is, who owns the zebra? Additionally, list the solution for all the houses. Optionally, show the solution is unique. Related tasks   Dinesman's multiple-dwelling problem   Twelve statements
#Tcl
Tcl
package require struct::list   # Implements the constants by binding them directly into the named procedures. # This is much faster than the alternatives! proc initConstants {args} { global {} set remap {} foreach {class elems} { Number {One Two Three Four Five} Color {Red Green Blue White Yellow} Drink {Milk Coffee Water Beer Tea} Smoke {PallMall Dunhill Blend BlueMaster Prince} Pet {Dog Cat Horse Bird Zebra} Nation {British Swedish Danish Norwegian German} } { set i -1 foreach e $elems {lappend remap "\$${class}($e)" [incr i]} set ($class) $elems } foreach procedure $args { proc $procedure [info args $procedure] \ [string map $remap [info body $procedure]] } }   proc isPossible {number color drink smoke pet} { if {[llength $number] && [lindex $number $Nation(Norwegian)] != $Number(One)} { return false } elseif {[llength $color] && [lindex $color $Nation(British)] != $Color(Red)} { return false } elseif {[llength $drink] && [lindex $drink $Nation(Danish)] != $Drink(Tea)} { return false } elseif {[llength $smoke] && [lindex $smoke $Nation(German)] != $Smoke(Prince)} { return false } elseif {[llength $pet] && [lindex $pet $Nation(Swedish)] != $Pet(Dog)} { return false }   if {!([llength $number] && [llength $color] && [llength $drink] && [llength $smoke] && [llength $pet])} { return true }   for {set i 0} {$i < 5} {incr i} { if {[lindex $color $i] == $Color(Green) && [lindex $drink $i] != $Drink(Coffee)} { return false } elseif {[lindex $smoke $i] == $Smoke(PallMall) && [lindex $pet $i] != $Pet(Bird)} { return false } elseif {[lindex $color $i] == $Color(Yellow) && [lindex $smoke $i] != $Smoke(Dunhill)} { return false } elseif {[lindex $number $i] == $Number(Three) && [lindex $drink $i] != $Drink(Milk)} { return false } elseif {[lindex $smoke $i] == $Smoke(BlueMaster) && [lindex $drink $i] != $Drink(Beer)} { return false } elseif {[lindex $color $i] == $Color(Blue) && [lindex $number $i] != $Number(Two)} { return false }   for {set j 0} {$j < 5} {incr j} { if {[lindex $color $i] == $Color(Green) && [lindex $color $j] == $Color(White) && [lindex $number $j] - [lindex $number $i] != 1} { return false }   set diff [expr {abs([lindex $number $i] - [lindex $number $j])}] if {[lindex $smoke $i] == $Smoke(Blend) && [lindex $pet $j] == $Pet(Cat) && $diff != 1} { return false } elseif {[lindex $pet $i] == $Pet(Horse) && [lindex $smoke $j] == $Smoke(Dunhill) && $diff != 1} { return false } elseif {[lindex $smoke $i] == $Smoke(Blend) && [lindex $drink $j] == $Drink(Water) && $diff != 1} { return false } } }   return true }   proc showRow {t data} { upvar #0 ($t) elems puts [format "%6s: %12s%12s%12s%12s%12s" $t \ [lindex $elems [lindex $data 0]] \ [lindex $elems [lindex $data 1]] \ [lindex $elems [lindex $data 2]] \ [lindex $elems [lindex $data 3]] \ [lindex $elems [lindex $data 4]]] }   proc main {} { set perms [struct::list permutations {0 1 2 3 4}] foreach number $perms { if {![isPossible $number {} {} {} {}]} continue foreach color $perms { if {![isPossible $number $color {} {} {}]} continue foreach drink $perms { if {![isPossible $number $color $drink {} {}]} continue foreach smoke $perms { if {![isPossible $number $color $drink $smoke {}]} continue foreach pet $perms { if {[isPossible $number $color $drink $smoke $pet]} { puts "Found a solution:" showRow Nation {0 1 2 3 4} showRow Number $number showRow Color $color showRow Drink $drink showRow Smoke $smoke showRow Pet $pet puts "" } } } } } } }   initConstants isPossible main
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#Tcl
Tcl
package require Tcl 8.5 package require Tk   namespace import tcl::mathop::\[-+\] ;# Shorter coordinate math proc yinyang {c x y r {colors {white black}}} { lassign $colors a b set tt [expr {$r * 2 / 3.0}] set h [expr {$r / 2.0}] set t [expr {$r / 3.0}] set s [expr {$r / 6.0}] $c create arc [- $x $r] [- $y $r] [+ $x $r] [+ $y $r] \ -fill $a -outline {} -extent 180 -start 90 $c create arc [- $x $r] [- $y $r] [+ $x $r] [+ $y $r] \ -fill $b -outline {} -extent 180 -start 270 $c create oval [- $x $h] [- $y $r] [+ $x $h] $y \ -fill $a -outline {} $c create oval [- $x $h] [+ $y $r] [+ $x $h] $y \ -fill $b -outline {} $c create oval [- $x $s] [- $y $tt] [+ $x $s] [- $y $t] \ -fill $b -outline {} $c create oval [- $x $s] [+ $y $tt] [+ $x $s] [+ $y $t] \ -fill $a -outline {} }   pack [canvas .c -width 300 -height 300 -background gray50] yinyang .c 110 110 90 yinyang .c 240 240 40
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Y = Function[f, #[#] &[Function[g, f[g[g][##] &]]]]; factorial = Y[Function[f, If[# < 1, 1, # f[# - 1]] &]]; fibonacci = Y[Function[f, If[# < 2, #, f[# - 1] + f[# - 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
#Modula-3
Modula-3
MODULE ZigZag EXPORTS Main;   IMPORT IO, Fmt;   TYPE Matrix = REF ARRAY OF ARRAY OF CARDINAL;   PROCEDURE Create(size: CARDINAL): Matrix = PROCEDURE move(VAR i, j: INTEGER) = BEGIN IF j < (size - 1) THEN IF (i - 1) < 0 THEN i := 0; ELSE i := i - 1; END; INC(j); ELSE INC(i); END; END move;   VAR data := NEW(Matrix, size, size); x, y: INTEGER := 0; BEGIN FOR v := 0 TO size * size - 1 DO data[y, x] := v; IF (x + y) MOD 2 = 0 THEN move(y, x); ELSE move(x, y); END; END; RETURN data; END Create;   PROCEDURE Print(data: Matrix) = BEGIN FOR i := FIRST(data^) TO LAST(data^) DO FOR j := FIRST(data[0]) TO LAST(data[0]) DO IO.Put(Fmt.F("%3s", Fmt.Int(data[i, j]))); END; IO.Put("\n"); END; END Print;   BEGIN Print(Create(5)); END ZigZag.
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.
#Factor
Factor
USING: bit-arrays formatting fry kernel math math.ranges sequences ; IN: rosetta.doors   CONSTANT: number-of-doors 100   : multiples ( n -- range ) 0 number-of-doors rot <range> ;   : toggle-multiples ( n doors -- ) [ multiples ] dip '[ _ [ not ] change-nth ] each ;   : toggle-all-multiples ( doors -- ) [ number-of-doors [1,b] ] dip '[ _ toggle-multiples ] each ;   : print-doors ( doors -- ) [ swap "open" "closed" ? "Door %d is %s\n" printf ] each-index ;   : main ( -- ) number-of-doors 1 + <bit-array> [ toggle-all-multiples ] [ print-doors ] bi ;   main
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)
#LSL
LSL
  default { state_entry() { list lst = ["1", "2", "3"]; llSay(0, "Create and Initialize a List\nList=["+llList2CSV(lst)+"]\n");   lst += ["A", "B", "C"]; llSay(0, "Append to List\nList=["+llList2CSV(lst)+"]\n");   lst = llListInsertList(lst, ["4", "5", "6"], 3); llSay(0, "List Insertion\nList=["+llList2CSV(lst)+"]\n");   lst = llListReplaceList(lst, ["a", "b", "c"], 3, 5); llSay(0, "Replace a portion of a list\nList=["+llList2CSV(lst)+"]\n");   lst = llListRandomize(lst, 1); llSay(0, "Randomize a List\nList=["+llList2CSV(lst)+"]\n");   lst = llListSort(lst, 1, TRUE); llSay(0, "Sort a List\nList=["+llList2CSV(lst)+"]\n");   lst = [1, 2.0, "string", (key)NULL_KEY, ZERO_VECTOR, ZERO_ROTATION]; string sCSV = llList2CSV(lst); llSay(0, "Serialize a List of different datatypes to a string\n(integer, float, string, key, vector, rotation)\nCSV=\""+sCSV+"\"\n");   lst = llCSV2List(sCSV); llSay(0, "Deserialize a string CSV List\n(note that all elements are now string datatype)\nList=["+llList2CSV(lst)+"]\n"); } }
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives in the red house.   The Swede has a dog.   The Dane drinks tea.   The green house is immediately to the left of the white house.   They drink coffee in the green house.   The man who smokes Pall Mall has birds.   In the yellow house they smoke Dunhill.   In the middle house they drink milk.   The Norwegian lives in the first house.   The man who smokes Blend lives in the house next to the house with cats.   In a house next to the house where they have a horse, they smoke Dunhill.   The man who smokes Blue Master drinks beer.   The German smokes Prince.   The Norwegian lives next to the blue house.   They drink water in a house next to the house where they smoke Blend. The question is, who owns the zebra? Additionally, list the solution for all the houses. Optionally, show the solution is unique. Related tasks   Dinesman's multiple-dwelling problem   Twelve statements
#VBA
VBA
Option Base 1 Public Enum attr Colour = 1 Nationality Beverage Smoke Pet End Enum Public Enum Drinks_ Beer = 1 Coffee Milk Tea Water End Enum Public Enum nations Danish = 1 English German Norwegian Swedish End Enum Public Enum colors Blue = 1 Green Red White Yellow End Enum Public Enum tobaccos Blend = 1 BlueMaster Dunhill PallMall Prince End Enum Public Enum animals Bird = 1 Cat Dog Horse Zebra End Enum Public permutation As New Collection Public perm(5) As Variant Const factorial5 = 120 Public Colours As Variant, Nationalities As Variant, Drinks As Variant, Smokes As Variant, Pets As Variant   Private Sub generate(n As Integer, A As Variant) If n = 1 Then permutation.Add A Else For i = 1 To n generate n - 1, A If n Mod 2 = 0 Then tmp = A(i) A(i) = A(n) A(n) = tmp Else tmp = A(1) A(1) = A(n) A(n) = tmp End If Next i End If End Sub   Function house(i As Integer, name As Variant) As Integer Dim x As Integer For x = 1 To 5 If perm(i)(x) = name Then house = x Exit For End If Next x End Function   Function left_of(h1 As Integer, h2 As Integer) As Boolean left_of = (h1 - h2) = -1 End Function   Function next_to(h1 As Integer, h2 As Integer) As Boolean next_to = Abs(h1 - h2) = 1 End Function   Private Sub print_house(i As Integer) Debug.Print i & ": "; Colours(perm(Colour)(i)), Nationalities(perm(Nationality)(i)), _ Drinks(perm(Beverage)(i)), Smokes(perm(Smoke)(i)), Pets(perm(Pet)(i)) End Sub Public Sub Zebra_puzzle() Colours = [{"blue","green","red","white","yellow"}] Nationalities = [{"Dane","English","German","Norwegian","Swede"}] Drinks = [{"beer","coffee","milk","tea","water"}] Smokes = [{"Blend","Blue Master","Dunhill","Pall Mall","Prince"}] Pets = [{"birds","cats","dog","horse","zebra"}] Dim solperms As New Collection Dim solutions As Integer Dim b(5) As Integer, i As Integer For i = 1 To 5: b(i) = i: Next i 'There are five houses. generate 5, b For c = 1 To factorial5 perm(Colour) = permutation(c) 'The green house is immediately to the left of the white house. If left_of(house(Colour, Green), house(Colour, White)) Then For n = 1 To factorial5 perm(Nationality) = permutation(n) 'The Norwegian lives in the first house. 'The English man lives in the red house. 'The Norwegian lives next to the blue house. If house(Nationality, Norwegian) = 1 _ And house(Nationality, English) = house(Colour, Red) _ And next_to(house(Nationality, Norwegian), house(Colour, Blue)) Then For d = 1 To factorial5 perm(Beverage) = permutation(d) 'The Dane drinks tea. 'They drink coffee in the green house. 'In the middle house they drink milk. If house(Nationality, Danish) = house(Beverage, Tea) _ And house(Beverage, Coffee) = house(Colour, Green) _ And house(Beverage, Milk) = 3 Then For s = 1 To factorial5 perm(Smoke) = permutation(s) 'In the yellow house they smoke Dunhill. 'The German smokes Prince. 'The man who smokes Blue Master drinks beer. 'They Drink water in a house next to the house where they smoke Blend. If house(Colour, Yellow) = house(Smoke, Dunhill) _ And house(Nationality, German) = house(Smoke, Prince) _ And house(Smoke, BlueMaster) = house(Beverage, Beer) _ And next_to(house(Beverage, Water), house(Smoke, Blend)) Then For p = 1 To factorial5 perm(Pet) = permutation(p) 'The Swede has a dog. 'The man who smokes Pall Mall has birds. 'The man who smokes Blend lives in the house next to the house with cats. 'In a house next to the house where they have a horse, they smoke Dunhill. If house(Nationality, Swedish) = house(Pet, Dog) _ And house(Smoke, PallMall) = house(Pet, Bird) _ And next_to(house(Smoke, Blend), house(Pet, Cat)) _ And next_to(house(Pet, Horse), house(Smoke, Dunhill)) Then For i = 1 To 5 print_house i Next i Debug.Print solutions = solutions + 1 solperms.Add perm End If Next p End If Next s End If Next d End If Next n End If Next c Debug.Print Format(solutions, "@"); " solution" & IIf(solutions > 1, "s", "") & " found" For i = 1 To solperms.Count For j = 1 To 5 perm(j) = solperms(i)(j) Next j Debug.Print "The " & Nationalities(perm(Nationality)(house(Pet, Zebra))) & " owns the Zebra" Next i End Sub
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#UNIX_Shell
UNIX Shell
#!/usr/bin/env bash in_circle() { #(cx, cy, r, x y) # return true if the point (x,y) lies within the circle of radius r centered # on (cx,cy) # (but really scaled to an ellipse with vertical minor semiaxis r and # horizontal major semiaxis 2r) local -i cx=$1 cy=$2 r=$3 x=$4 y=$5 local -i dx dy (( dx=(x-cx)/2, dy=y-cy, dx*dx + dy*dy <= r*r )) }   taijitu() { #radius local -i radius=${1:-17} local -i x1=0 y1=0 r1=radius # outer circle local -i x2=0 y2=-radius/2 r2=radius/6 # upper eye local -i x3=0 y3=-radius/2 r3=radius/2 # upper half local -i x4=0 y4=+radius/2 r4=radius/6 # lower eye local -i x5=0 y5=+radius/2 r5=radius/2 # lower half local -i x y for (( y=radius; y>=-radius; --y )); do for (( x=-2*radius; x<=2*radius; ++x)); do if ! in_circle $x1 $y1 $r1 $x $y; then printf ' ' elif in_circle $x2 $y2 $r2 $x $y; then printf '#' elif in_circle $x3 $y3 $r3 $x $y; then printf '.' elif in_circle $x4 $y4 $r4 $x $y; then printf '.' elif in_circle $x5 $y5 $r5 $x $y; then printf '#' elif (( x <= 0 )); then printf '.' else printf '#' fi done printf '\n' done }
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
#Moonscript
Moonscript
Z = (f using nil) -> ((x) -> x x) (x) -> f (...) -> (x x) ... factorial = Z (f using nil) -> (n) -> if n == 0 then 1 else n * f n - 1
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
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols binary   zigzag(5)   return   method zigzag(msize) public static   row = 1 col = 1   ziggy = Rexx(0) loop j_ = 0 for msize * msize ziggy[row, col] = j_ if (row + col) // 2 == 0 then do if col < msize then - col = col + 1 else row = row + 2 if row \== 1 then - row = row - 1 end else do if row < msize then - row = row + 1 else col = col + 2 if col \== 1 then - col = col - 1 end end j_   L = (msize * msize - 1).length /*for a constant element width. */ loop row = 1 for msize /*show all the matrix's rows. */ rowOut = '' loop col = 1 for msize rowOut = rowOut ziggy[row, col].right(L) end col say rowOut end row   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.
#Falcon
Falcon
doors = arrayBuffer( 101, false )   for pass in [ 0 : doors.len() ] for door in [ 0 : doors.len() : pass+1 ] doors[ door ] = not doors[ door ] end end   for door in [ 1 : doors.len() ] // Show Output > "Door ", $door, " is: ", ( doors[ door ] ) ? "open" : "closed" end  
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)
#Lua
Lua
l = {} l[1] = 1 -- Index starts with 1, not 0. l[0] = 'zero' -- But you can use 0 if you want l[10] = 2 -- Indexes need not be continuous l.a = 3 -- Treated as l['a']. Any object can be used as index l[l] = l -- Again, any object can be used as an index. Even other tables for i,v in next,l do print (i,v) end
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives in the red house.   The Swede has a dog.   The Dane drinks tea.   The green house is immediately to the left of the white house.   They drink coffee in the green house.   The man who smokes Pall Mall has birds.   In the yellow house they smoke Dunhill.   In the middle house they drink milk.   The Norwegian lives in the first house.   The man who smokes Blend lives in the house next to the house with cats.   In a house next to the house where they have a horse, they smoke Dunhill.   The man who smokes Blue Master drinks beer.   The German smokes Prince.   The Norwegian lives next to the blue house.   They drink water in a house next to the house where they smoke Blend. The question is, who owns the zebra? Additionally, list the solution for all the houses. Optionally, show the solution is unique. Related tasks   Dinesman's multiple-dwelling problem   Twelve statements
#Vlang
Vlang
type HouseSet = []House struct House { n Nationality c Colour a Animal d Drink s Smoke }   // Define the possible values enum Nationality { english = 0 swede dane norwegian german } enum Colour { red = 0 green white yellow blue } enum Animal { dog = 0 birds cats horse zebra } enum Drink { tea = 0 coffee milk beer water } enum Smoke { pall_mall = 0 dunhill blend blue_master prince }   // And how to print them   const nationalities = [Nationality.english, Nationality.swede, Nationality.dane, Nationality.norwegian, Nationality.german] const colours = [Colour.red, Colour.green, Colour.white, Colour.yellow, Colour.blue] const animals = [Animal.dog, Animal.birds, Animal.cats, Animal.horse, Animal.zebra] const drinks = [Drink.tea, Drink.coffee, Drink.milk, Drink.beer, Drink.water] const smokes = [Smoke.pall_mall, Smoke.dunhill, Smoke.blend, Smoke.blue_master, Smoke.prince]   fn (h House) str() string { return "${h.n:-9} ${h.c:-6} ${h.a:-5} ${h.d:-6} $h.s" } fn (hs HouseSet) str() string { mut lines := []string{len: 0, cap: 5} for i, h in hs { s := "$i $h" lines << s } return lines.join("\n") }   // Simple brute force solution   fn simple_brute_force() (int, HouseSet) { mut v := []House{} for n in nationalities { for c in colours { for a in animals { for d in drinks { for s in smokes { h := House{ n: n, c: c, a: a, d: d, s: s, } if !h.valid() { continue } v << h } } } } } n := v.len println("Generated $n valid houses")   mut combos := 0 mut first := 0 mut valid := 0 mut valid_set := []House{} for a := 0; a < n; a++ { if v[a].n != Nationality.norwegian { // Condition 10: continue } for b := 0; b < n; b++ { if b == a { continue } if v[b].any_dups(v[a]) { continue } for c := 0; c < n; c++ { if c == b || c == a { continue } if v[c].d != Drink.milk { // Condition 9: continue } if v[c].any_dups(v[b], v[a]) { continue } for d := 0; d < n; d++ { if d == c || d == b || d == a { continue } if v[d].any_dups(v[c], v[b], v[a]) { continue } for e := 0; e < n; e++ { if e == d || e == c || e == b || e == a { continue } if v[e].any_dups(v[d], v[c], v[b], v[a]) { continue } combos++ set := HouseSet([v[a], v[b], v[c], v[d], v[e]]) if set.valid() { valid++ if valid == 1 { first = combos } valid_set = set //return set } } } } } } println("Tested $first different combinations of valid houses before finding solution") println("Tested $combos different combinations of valid houses in total") return valid, valid_set }   // any_dups returns true if h as any duplicate attributes with any of the specified houses fn (h House) any_dups(list ...House) bool { for b in list { if h.n == b.n || h.c == b.c || h.a == b.a || h.d == b.d || h.s == b.s { return true } } return false }   fn (h House) valid() bool { // Condition 2: if (h.n == Nationality.english && h.c != Colour.red) || (h.n != Nationality.english && h.c == Colour.red) { return false } // Condition 3: if (h.n == Nationality.swede && h.a != Animal.dog) || (h.n != Nationality.swede && h.a == Animal.dog) { return false } // Condition 4: if (h.n == Nationality.dane && h.d != Drink.tea) || (h.n != Nationality.dane && h.d == Drink.tea ){ return false } // Condition 6: if (h.c == Colour.green && h.d != Drink.coffee) || (h.c != Colour.green && h.d == Drink.coffee) { return false } // Condition 7: if (h.a == Animal.birds && h.s != Smoke.pall_mall) || (h.a != Animal.birds && h.s == Smoke.pall_mall) { return false } // Condition 8: if (h.c == Colour.yellow && h.s != Smoke.dunhill) || (h.c != Colour.yellow && h.s == Smoke.dunhill) { return false } // Condition 11: if h.a == Animal.cats && h.s == Smoke.blend { return false } // Condition 12: if h.a == Animal.horse && h.s == Smoke.dunhill { return false } // Condition 13: if (h.d == Drink.beer && h.s != Smoke.blue_master) || (h.d != Drink.beer && h.s == Smoke.blue_master) { return false } // Condition 14: if (h.n == Nationality.german && h.s != Smoke.prince) || (h.n != Nationality.german && h.s == Smoke.prince) { return false } // Condition 15: if h.n == Nationality.norwegian && h.c == Colour.blue { return false } // Condition 16: if h.d == Drink.water && h.s == Smoke.blend { return false } return true }   fn (hs HouseSet) valid() bool { mut ni := map[Nationality]int{} mut ci := map[Colour]int{} mut ai := map[Animal]int{} mut di := map[Drink]int{} mut si := map[Smoke]int{} for i, h in hs { ni[h.n] = i ci[h.c] = i ai[h.a] = i di[h.d] = i si[h.s] = i } // Condition 5: if ci[Colour.green]+1 != ci[Colour.white] { return false } // Condition 11: if dist(ai[Animal.cats], si[Smoke.blend]) != 1 { return false } // Condition 12: if dist(ai[Animal.horse], si[Smoke.dunhill]) != 1 { return false } // Condition 15: if dist(ni[Nationality.norwegian], ci[Colour.blue]) != 1 { return false } // Condition 16: if dist(di[Drink.water], si[Smoke.blend]) != 1 { return false }   // Condition 9: (already tested elsewhere) if hs[2].d != Drink.milk { return false } // Condition 10: (already tested elsewhere) if hs[0].n != Nationality.norwegian { return false } return true }   fn dist(a int, b int) int { if a > b { return a - b } return b - a }   fn main() { n, sol := simple_brute_force() println("$n solution found") println(sol) }
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#Wren
Wren
var inCircle = Fn.new { |centerX, centerY, radius, x, y| return (x-centerX)*(x-centerX)+(y-centerY)*(y-centerY) <= radius*radius }   var inBigCircle = Fn.new { |radius, x, y| inCircle.call(0, 0, radius, x, y) }   var inBlackSemiCircle = Fn.new { |radius, x, y| inCircle.call(0, -radius/2, radius/2, x, y) }   var inWhiteSemiCircle = Fn.new { |radius, x, y| inCircle.call(0, radius/2, radius/2, x, y) }   var inSmallBlackCircle = Fn.new { |radius, x, y| inCircle.call(0, radius/2, radius/6, x, y) }   var inSmallWhiteCircle = Fn.new { |radius, x, y| inCircle.call(0, -radius/2, radius/6, x, y) }   var yinAndYang = Fn.new { |radius| var black = "#" var white = "." var scaleX = 2 var scaleY = 1 for (sy in radius*scaleY..-(radius*scaleY)) { for (sx in -(radius*scaleX)..(radius*scaleX)) { var x = sx / scaleX var y = sy / scaleY if (inBigCircle.call(radius, x, y)) { if (inWhiteSemiCircle.call(radius, x, y)) { System.write(inSmallBlackCircle.call(radius, x, y) ? black : white) } else if (inBlackSemiCircle.call(radius, x, y)) { System.write(inSmallWhiteCircle.call(radius, x, y) ? white : black) } else { System.write((x < 0) ? white : black) } } else { System.write(" ") } } System.print() } }   yinAndYang.call(16) yinAndYang.call(8)
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
#Nim
Nim
# The following is implemented for a strict language as a Z-Combinator; # Z-combinators differ from Y-combinators in lacking one Beta reduction of # the extra `T` argument to the function to be recursed...   import sugar   proc fixz[T, TResult](f: ((T) -> TResult) -> ((T) -> TResult)): (T) -> TResult = type RecursiveFunc = object # any entity that wraps the recursion! recfnc: ((RecursiveFunc) -> ((T) -> TResult)) let g = (x: RecursiveFunc) => f ((a: T) => x.recfnc(x)(a)) g(RecursiveFunc(recfnc: g))   let facz = fixz((f: (int) -> int) => ((n: int) => (if n <= 1: 1 else: n * f(n - 1)))) let fibz = fixz((f: (int) -> int) => ((n: int) => (if n < 2: n else: f(n - 2) + f(n - 1))))   echo facz(10) echo fibz(10)   # by adding some laziness, we can get a true Y-Combinator... # note that there is no specified parmater(s) - truly fix point!...   #[ proc fixy[T](f: () -> T -> T): T = type RecursiveFunc = object # any entity that wraps the recursion! recfnc: ((RecursiveFunc) -> T) let g = ((x: RecursiveFunc) => f(() => x.recfnc(x))) g(RecursiveFunc(recfnc: g)) # ]#   # same thing using direct recursion as Nim has... # note that this version of fix uses function recursion in its own definition; # thus its use just means that the recursion has been "pulled" into the "fix" function, # instead of the function that uses it... proc fixy[T](f: () -> T -> T): T = f(() => (fixy(f)))   # these are dreadfully inefficient as they becursively build stack!... let facy = fixy((f: () -> (int -> int)) => ((n: int) => (if n <= 1: 1 else: n * f()(n - 1))))   let fiby = fixy((f: () -> (int -> int)) => ((n: int) => (if n < 2: n else: f()(n - 2) + f()(n - 1))))   echo facy 10 echo fiby 10   # something that can be done with the Y-Combinator that con't be done with the Z... # given the following Co-Inductive Stream (CIS) definition... type CIS[T] = object head: T tail: () -> CIS[T]   # Using a double Y-Combinator recursion... # defines a continuous stream of Fibonacci numbers; there are other simpler ways, # this way implements recursion by using the Y-combinator, although it is # much slower than other ways due to the many additional function calls, # it demonstrates something that can't be done with the Z-combinator... iterator fibsy: int {.closure.} = # two recursions... let fbsfnc: (CIS[(int, int)] -> CIS[(int, int)]) = # first one... fixy((fnc: () -> (CIS[(int,int)] -> CIS[(int,int)])) => ((cis: CIS[(int,int)]) => ( let (f,s) = cis.head; CIS[(int,int)](head: (s, f + s), tail: () => fnc()(cis.tail()))))) var fbsgen: CIS[(int, int)] = # second recursion fixy((cis: () -> CIS[(int,int)]) => # cis is a lazy thunk used directly below! fbsfnc(CIS[(int,int)](head: (1,0), tail: cis))) while true: yield fbsgen.head[0]; fbsgen = fbsgen.tail()   let fibs = fibsy for _ in 1 .. 20: stdout.write fibs(), " " echo()
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
#Nim
Nim
from algorithm import sort from strutils import align from sequtils import newSeqWith   type Pos = tuple[x, y: int]   proc `<` (a, b: Pos): bool = a.x + a.y < b.x + b.y or a.x + a.y == b.x + b.y and (a.x < b.x xor (a.x + a.y) mod 2 == 0)   proc zigzagMatrix(n: int): auto = var indices = newSeqOfCap[Pos](n*n)   for x in 0 ..< n: for y in 0 ..< n: indices.add((x,y))   sort(indices)   result = newSeqWith(n, newSeq[int](n)) for i, p in indices: result[p.x][p.y] = i   proc `$`(m: seq[seq[int]]): string = let Width = len($m[0][^1]) + 1 for r in m: for c in r: result.add align($c, Width) result.add "\n"   echo zigzagMatrix(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.
#FALSE
FALSE
100[$][0 1ø:1-]# {initialize doors} % [s;[$101\>][$$;~\:s;+]#%]d: {function d, switch door state function} 1s:[s;101\>][d;!s;1+s:]# {increment step width from 1 to 100, execute function d each time} 1[$101\>][$$." ";$["open "]?~["closed "]?1+]# {loop through doors, print door number and state}
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)
#M2000_Interpreter
M2000 Interpreter
  Module CheckArray { \\ Array with parenthesis in name Dim A(10)=1 Global B(10)=1 For This { Local A(10)=5 Print A(4)=5 } Print A(4)=1   \\ Auto Array M=(1,2,3,4,5) Link M to M() Print M(2)=3 Return M, 0:=100, 5-4:=300   \\ Retrieve an Element of an Array k=Each(M, 1, 2) \\ print 100 300 While k { Print Array(k),} Print Print Array(M, 2)=3 Print Array("M", 2)=3 Print Array(B(), 1)=1 \\ arrays are containers for every value/object/pointer B(0):="Hello",100,"Good Morning", 200 \\ using set to make B$() global too Set Link B() to B$() Print B$(0), B(1), B$(2), B(3) Swap B(0), B(2) Swap B(1), B(3) Print B$(0), B(1), B$(2), B(3) Print B() \\ Reduce B() to 4 elements - and change dimensions \\ we have to redim the global array, using set to send line to console \\ all globals are part of level 0, at console input. Set Dim B(4) Module CheckGlobal { Print B$(0), B(1), B$(2), B(3) } CheckGlobal Print B() Dim BB(4) \\ Copy 4 items from B() to BB(), from B(0), to BB(0) Stock B(0) keep 4, BB(0) Link BB() to BB$() Print BB$(0), BB(1), BB$(2), BB(3) \\ Arrays of structures in Buffers   Structure TwoByte { { ab as integer } a as byte b as byte } Print Len(TwoByte) = 2 \ Use clear to clear memory \\ Mem is a pointer to a Buffer object Buffer Clear Mem as TwoByte*20 Print Len(Mem)=40 Return Mem, 0!ab:=0xFFAA Print Eval(Mem, 0!a)=0xAA, Eval(Mem, 0!b)=0xFF Return Mem, 0!b:=0xF2 Hex Eval(Mem,0!ab) ' print 0xF2AA \\ Redim with preserve Buffer Mem as TwoByte*40 \\ copy 40 bytes at index 20 (40 bytes from start) Return Mem, 20:=Eval$(Mem, 0, 20*2) Hex Eval(Mem,20!ab) ' print 0xF2AA A(3)=Mem Hex Eval(A(3),20!ab) ' print 0xF2AA \\ now Mem change pointer Clear Mem Print Len(Mem) \\ old Mem is in A(3) Hex Eval(A(3),20!ab) ' print 0xF2AA \\ we can change Buffer Clear Mem as Integer * 200 Print Len(Mem)=400 Return Mem, 0:=Eval$(A(3), 0, 80) Hex Eval(Mem,20) ' print 0xF2AA \\ change type without use of clear Buffer Mem as TwoByte * 200 Hex Eval(Mem,20!ab) ' print 0xF2AA } CheckArray  
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives in the red house.   The Swede has a dog.   The Dane drinks tea.   The green house is immediately to the left of the white house.   They drink coffee in the green house.   The man who smokes Pall Mall has birds.   In the yellow house they smoke Dunhill.   In the middle house they drink milk.   The Norwegian lives in the first house.   The man who smokes Blend lives in the house next to the house with cats.   In a house next to the house where they have a horse, they smoke Dunhill.   The man who smokes Blue Master drinks beer.   The German smokes Prince.   The Norwegian lives next to the blue house.   They drink water in a house next to the house where they smoke Blend. The question is, who owns the zebra? Additionally, list the solution for all the houses. Optionally, show the solution is unique. Related tasks   Dinesman's multiple-dwelling problem   Twelve statements
#Wren
Wren
import "/fmt" for Fmt   var colors = ["Red", "Green", "White", "Yellow", "Blue"] var nations = ["English", "Swede", "Danish", "Norwegian", "German"] var animals = ["Dog", "Birds", "Cats", "Horse", "Zebra"] var drinks = ["Tea", "Coffee", "Milk", "Beer", "Water"] var smokes = ["Pall Mall", "Dunhill", "Blend", "Blue Master", "Prince"]   var p = List.filled(120, null) // stores all permutations of numbers 0..4 for (i in 0..119) p[i] = List.filled(5, -1)   var nextPerm = Fn.new { |perm| var size = perm.count var k = -1 for (i in size-2..0) { if (perm[i] < perm[i + 1]) { k = i break } } if (k == -1) return false // last permutation for (l in size-1..k) { if (perm[k] < perm[l]) { perm.swap(k, l) var m = k + 1 var n = size - 1 while (m < n) { perm.swap(m, n) m = m + 1 n = n - 1 } break } } return true }   var check = Fn.new { |a1, a2, v1, v2| for (i in 0..4) { if (p[a1][i] == v1) return p[a2][i] == v2 } return false }   var checkLeft = Fn.new { |a1, a2, v1, v2| for (i in 0..3) { if (p[a1][i] == v1) return p[a2][i + 1] == v2 } return false }   var checkRight = Fn.new { |a1, a2, v1, v2| for (i in 1..4) { if (p[a1][i] == v1) return p[a2][i - 1] == v2 } return false }   var checkAdjacent = Fn.new { |a1, a2, v1, v2| return checkLeft.call(a1, a2, v1, v2) || checkRight.call(a1, a2, v1, v2) }   var printHouses = Fn.new { |c, n, a, d, s| var owner = "" System.print("House Color Nation Animal Drink Smokes") System.print("===== ====== ========= ====== ====== ===========") for (i in 0..4) { var f = "$3d $-6s $-9s $-6s $-6s $-11s" var l = [i + 1, colors[p[c][i]], nations[p[n][i]], animals[p[a][i]], drinks[p[d][i]], smokes[p[s][i]]] Fmt.lprint(f, l) if (animals[p[a][i]] == "Zebra") owner = nations[p[n][i]] } System.print("\nThe %(owner) owns the Zebra\n") }   var fillHouses = Fn.new { var solutions = 0 for (c in 0..119) { if (!checkLeft.call(c, c, 1, 2)) continue // C5 : Green left of white for (n in 0..119) { if (p[n][0] != 3) continue // C10: Norwegian in First if (!check.call(n, c, 0, 0)) continue // C2 : English in Red if (!checkAdjacent.call(n, c, 3, 4)) continue // C15: Norwegian next to Blue for (a in 0..119) { if (!check.call(a, n, 0, 1)) continue // C3 : Swede has Dog for (d in 0..119) { if (p[d][2] != 2) continue // C9 : Middle drinks Milk if (!check.call(d, n, 0, 2)) continue // C4 : Dane drinks Tea if (!check.call(d, c, 1, 1)) continue // C6 : Green drinks Coffee for (s in 0..119) { if (!check.call(s, a, 0, 1)) continue // C7 : Pall Mall has Birds if (!check.call(s, c, 1, 3)) continue // C8 : Yellow smokes Dunhill if (!check.call(s, d, 3, 3)) continue // C13: Blue Master drinks Beer if (!check.call(s, n, 4, 4)) continue // C14: German smokes Prince if (!checkAdjacent.call(s, a, 2, 2)) continue // C11: Blend next to Cats if (!checkAdjacent.call(s, a, 1, 3)) continue // C12: Dunhill next to Horse if (!checkAdjacent.call(s, d, 2, 4)) continue // C16: Blend next to Water solutions = solutions + 1 printHouses.call(c, n, a, d, s) } } } } } return solutions }   var perm = [0, 1, 2, 3, 4] for (i in 0..119) { for (j in 0..4) p[i][j] = perm[j] nextPerm.call(perm) } var solutions = fillHouses.call() var plural = (solutions == 1) ? "" : "s" System.print("%(solutions) solution%(plural) found")
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations   def Black=0, Red=4, White=$F;   proc Circle(X0, Y0, R, CL, CR); \Show a filled circle int X0, Y0, R, CL, CR; \left and right half colors int X, Y; [for Y:= -R to R do for X:= -R to R do if X*X + Y*Y <= R*R then Point(X+X0, Y+Y0, if X<0 then CL else CR); ]; \Circle   proc YinYang(X0, Y0, R); int X0, Y0, R; [Circle(X0, Y0, R, White, Black); Circle(X0, Y0-R/2, R/2, White, White); Circle(X0, Y0-R/2, R/6, Black, Black); Circle(X0, Y0+R/2, R/2, Black, Black); Circle(X0, Y0+R/2, R/6, White, White); ]; \YinYang   [SetVid($101); \640x480 graphics Circle(320, 240, 400, Red, Red);\fill screen with background color YinYang(80, 80, 70); YinYang(240, 240, 150); if ChIn(1) then []; \wait for keystroke SetVid(3); \restore normal text mode ]
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#zkl
zkl
fcn draw_yinyang(trans,scale){ 0'|<use xlink:href="#y" transform="translate(%d,%d) scale(%g)"/>| .fmt(trans,trans,scale).print(); }   print( "<?xml version='1.0' encoding='UTF-8' standalone='no'?>\n" "<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN'\n" " 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>\n" "<svg xmlns='http://www.w3.org/2000/svg' version='1.1'\n" " xmlns:xlink='http://www.w3.org/1999/xlink'\n" " width='30' height='30'>\n" " <defs><g id='y'>\n" " <circle cx='0' cy='0' r='200' stroke='black'\n" " fill='white' stroke-width='1'/>\n" " <path d='M0 -200 A 200 200 0 0 0 0 200\n" " 100 100 0 0 0 0 0 100 100 0 0 1 0 -200\n" " z' fill='black'/>\n" " <circle cx='0' cy='100' r='33' fill='white'/>\n" " <circle cx='0' cy='-100' r='33' fill='black'/>\n" " </g></defs>\n");   draw_yinyang(20, 0.05); draw_yinyang( 8, 0.02); print("</svg>");
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
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   typedef int (^Func)(int); typedef Func (^FuncFunc)(Func); typedef Func (^RecursiveFunc)(id); // hide recursive typing behind dynamic typing   Func Y(FuncFunc f) { RecursiveFunc r = ^(id y) { RecursiveFunc w = y; // cast value back into desired type return f(^(int x) { return w(w)(x); }); }; return r(r); }   int main (int argc, const char *argv[]) { @autoreleasepool {   Func fib = Y(^Func(Func f) { return ^(int n) { if (n <= 2) return 1; return f(n - 1) + f(n - 2); }; }); Func fac = Y(^Func(Func f) { return ^(int n) { if (n <= 1) return 1; return n * f(n - 1); }; });   Func fib = fix(almost_fib); Func fac = fix(almost_fac); NSLog(@"fib(10) = %d", fib(10)); NSLog(@"fac(10) = %d", fac(10));   } return 0; }
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
#Objeck
Objeck
  function : native : ZigZag(size : Int) ~ Int[,] { data := Int->New[size, size]; i := 1; j := 1;   max := size * size; for(element := 0; element < max ; element += 1;) { data[i - 1, j - 1] := element;   if((i + j) % 2 = 0) { # even stripes if(j < size){ j += 1; } else{ i+= 2; };   if(i > 1) { i -= 1; }; } else{ # ddd stripes if(i < size){ i += 1; } else{ j+= 2; };   if(j > 1){ j -= 1; }; }; };   return data; }  
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.
#Fantom
Fantom
  states := (1..100).toList 100.times |i| { states = states.map |state| { state % (i+1) == 0 ? -state : +state } } echo("Open doors are " + states.findAll { it < 0 }.map { -it })  
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)
#Maple
Maple
#defining an array of a certain length a := Array (1..5); a := [ 0 0 0 0 0 ] #can also define with a list of entries a := Array ([1, 2, 3, 4, 5]); a := [ 1 2 3 4 5 ] a[1] := 9; a a[1] := 9 [ 9 2 3 4 5 ] a[5]; 5 #can only grow arrays using () a(6) := 6; a := [ 9 2 3 4 5 6 ] a[7] := 7; Error, Array index out of range
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives in the red house.   The Swede has a dog.   The Dane drinks tea.   The green house is immediately to the left of the white house.   They drink coffee in the green house.   The man who smokes Pall Mall has birds.   In the yellow house they smoke Dunhill.   In the middle house they drink milk.   The Norwegian lives in the first house.   The man who smokes Blend lives in the house next to the house with cats.   In a house next to the house where they have a horse, they smoke Dunhill.   The man who smokes Blue Master drinks beer.   The German smokes Prince.   The Norwegian lives next to the blue house.   They drink water in a house next to the house where they smoke Blend. The question is, who owns the zebra? Additionally, list the solution for all the houses. Optionally, show the solution is unique. Related tasks   Dinesman's multiple-dwelling problem   Twelve statements
#zkl
zkl
var people,drinks,houses,smokes,pets; // lists treated as associated arrays fcn c2 { people.find(English)==houses.find(Red) } fcn c3 { people.find(Swede)==pets.find(Dog) } fcn c4 { people.find(Dane)==drinks.find(Tea) } fcn c5 { (houses.find(Green) + 1)==houses.find(White) } fcn c5a{ houses.find(Green)!=4 } // deduced constraint (from c5) fcn c5b{ houses.find(White)!=0 } // deduced constraint (from c5) fcn c6 { drinks.find(Coffee)==houses.find(Green) } fcn c7 { smokes.find(PallMall)==pets.find(Bird) } fcn c8 { houses.find(Yellow)==smokes.find(Dunhill) } fcn c9 { drinks[2]==Milk } // 0,1,2,3,4 fcn c10{ people[0]==Norwegian } fcn c11{ (smokes.find(Blend) - pets.find(Cat)).abs()==1 } fcn c12{ (pets.find(Horse) - smokes.find(Dunhill)).abs()==1 } fcn c13{ smokes.find(BlueMaster)==drinks.find(Beer) } fcn c14{ people.find(German)==smokes.find(Prince) } fcn c15{ (people.find(Norwegian) - houses.find(Blue)).abs()==1 } fcn c16{ (drinks.find(Water) - smokes.find(Blend)).abs()==1 } #<<<#////////////////////////////////////////////////////////////////////// Showing a solution to c2,c5,c10,c15: |0 1 2 3 4 --------+------------------------------------------- houses: |Yellow Blue Red Green White people: |Norwegian Dane English German Swede #<<<#//////////////////////////////////////////////////////////////////////   const Blue =0,Green =1,Red =2,White =3,Yellow=4, Dane =0,English =1,German =2,Norwegian=3,Swede =4, Beer =0,Coffee =1,Milk =2,Tea =3,Water =4, Blend=0,BlueMaster=1,Dunhill=2,PallMall =3,Prince=4, Bird =0,Cat =1,Dog =2,Horse =3,Zebra =4; perm5:=T(0,1,2,3,4) : Utils.Helpers.permute(_); // 120 sets   constraints:=T(c2,c3,c4,c5,c5a,c5b,c6,c7,c8,c9,c10,c11,c12,c13,c14,c15,c16); constraints1:=T(c2,c5,c10,c15); // houses,people: 12 solutions constraints2:=T(c4,c6,c9); // houses,people,drinks: down to 8 solutions foreach _houses,_people in (perm5,perm5){ houses,people=_houses,_people; if(not constraints1.runNFilter(False)){ // all constraints are True foreach _drinks in (perm5){ drinks=_drinks; if(not constraints2.runNFilter(False)){ foreach _smokes,_pets in (perm5,perm5){ smokes,pets=_smokes,_pets; if(not constraints.runNFilter(False)) printSolution(); }// smokes,pets } } // drinks } // houses,people } fcn printSolution{ var titles=T("Houses:","People:","Drinks:","Smokes:","Pets:"), names=T( T("Blue", "Green", "Red", "White", "Yellow",), T("Dane", "English", "German", "Norwegian","Swede",), T("Beer", "Coffee", "Milk", "Tea", "Water",), T("Blend","Blue Master","Dunhill","Pall Mall","Prince",), T("Bird", "Cat", "Dog", "Horse", "Zebra",) ),  ; fmt:=("%-7s " + "%-11s "*5).fmt; foreach list,title,names in (T(houses,people,drinks,smokes,pets) .zip(titles,names)) { println(list.apply(names.get):fmt(title,_.xplode())) } }
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
#OCaml
OCaml
let fix f g = (fun x a -> f (x x) a) (fun x a -> f (x x) a) 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
#OCaml
OCaml
let zigzag n = (* move takes references and modifies them directly *) let move i j = if !j < n - 1 then begin i := max 0 (!i - 1); incr j end else incr i in let a = Array.make_matrix n n 0 and x = ref 0 and y = ref 0 in for v = 0 to n * n - 1 do a.(!x).(!y) <- v; if (!x + !y) mod 2 = 0 then move x y else move y x done; a
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.
#FBSL
FBSL
#AppType Console   DIM doors[], n AS INTEGER = 100   FOR DIM i = 1 TO n FOR DIM j = i TO n STEP i doors[j] = NOT doors[j] NEXT NEXT   FOR i = 1 TO n IF doors[i] THEN PRINT "Door ", i, " is open" NEXT   Pause
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)
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
a = Array[Sin, 10] a[[1]] Delete[a, 2]
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
#Oforth
Oforth
: Y(f) #[ f Y f perform ] ;
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
#Octave
Octave
function a = zigzag1(n) j = 1:n; u = repmat([-1; 1], n, 1); v = j.*(2*j-3); v = reshape([v; v+1], 2*n, 1); a = zeros(n, n); for i = 1:n a(:, i) = v(i+j); v += u; endfor endfunction   function a = zigzag2(n) a = zigzag1(n); v = (1:n-1)'.^2; for i = 2:n a(n+2-i:n, i) -= v(1:i-1); endfor endfunction   >> zigzag2(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.
#Fhidwfe
Fhidwfe
  doors = malloc$ 100u for uint [0u, sizeof$ doors) with l1 { put_byte$ + doors l1 as false byte } function void pass(step:uint) { location = step while <= location sizeof$ doors { ac = - + doors location 1u put_byte$ ac ~ deref_byte$ ac// true is represented as 255 (0xff) location = + location step } } for uint (0u, sizeof$ doors] with l2 {//range exclusive of 0, inclusive of 100 pass$ l2 } count = 1u for ubyte as doors listubyte with isopen {// list for-each if as isopen bool {// cast byte to bool puts$ "door " putui$ count puts$ " is open\n" } ; count = + count 1u } free$ doors  
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)
#MATLAB_.2F_Octave
MATLAB / Octave
>> a = [1 2 35] %Declaring a vector (i.e. one-dimensional array)   a =   1 2 35   >> a = [1 2 35;5 7 9] % Declaring a matrix (i.e. two-dimensional array)   a =   1 2 35 5 7 9   >> a3 = reshape(1:2*3*4,[2,3,4]); % declaring a three-dimensional array of size 2x3x4   a3 =   ans(:,:,1) =   1 3 5 2 4 6   ans(:,:,2) =   7 9 11 8 10 12   ans(:,:,3) =   13 15 17 14 16 18   ans(:,:,4) =   19 21 23 20 22 24     >> a(2,3) %Retrieving value using row and column indicies   9   >> a(6) %Retrieving value using array subscript   ans =   9   >> a = [a [10;42]] %Added a column vector to the array   a =   1 2 35 10 5 7 9 42   >> a(:,1) = [] %Deleting array elements   a =   2 35 10 7 9 42
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
#Order
Order
#include <order/interpreter.h>   #define ORDER_PP_DEF_8y \ ORDER_PP_FN(8fn(8F, \ 8let((8R, 8fn(8G, \ 8ap(8F, 8fn(8A, 8ap(8ap(8G, 8G), 8A))))), \ 8ap(8R, 8R))))   #define ORDER_PP_DEF_8fac \ ORDER_PP_FN(8fn(8F, 8X, \ 8if(8less_eq(8X, 0), 1, 8times(8X, 8ap(8F, 8minus(8X, 1))))))   #define ORDER_PP_DEF_8fib \ ORDER_PP_FN(8fn(8F, 8X, \ 8if(8less(8X, 2), 8X, 8plus(8ap(8F, 8minus(8X, 1)), \ 8ap(8F, 8minus(8X, 2))))))   ORDER_PP(8to_lit(8ap(8y(8fac), 10))) // 3628800 ORDER_PP(8ap(8y(8fib), 10)) // 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
#Inspired_by_Rascal
Inspired by Rascal
#{ Produce a zigzag matrix. Nigel Galloway, January 26th., 2020. At the time of writing the Rascal solution is yellow flagged for producing a striped matrix. Let me make the same faux pas. #} n=5; g=1; for e=1:n i=1; for l=e:-1:1 zig(i++,l)=g++; endfor endfor for e=2:n i=e; for l=n:-1:e zig(i++,l)=g++; endfor endfor #{ I then have the following, let me call it zig. 1 2 4 7 11 3 5 8 12 16 6 9 13 17 20 10 14 18 21 23 15 19 22 24 25   To avoid being yellow flagged I must convert this striped matrix into a zigzag matrix. #} zag=zig' #{ So zag is the transpose of zig. 1 3 6 10 15 2 5 9 14 19 4 8 13 18 22 7 12 17 21 24 11 16 20 23 25 #} for e=1:n for g=1:n if(mod(e+g,2))==0 zagM(e,g)=1; endif endfor endfor; zigM=1-zagM; #{ I now have 2 masks:   zigM =   0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0   zagM =   1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 #} zigzag=zag.*zagM+zig.*zigM; #{ zigzag =   1 2 6 7 15 3 5 8 14 16 4 9 13 17 22 10 12 18 21 23 11 19 20 24 25 #}  
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.
#Fish
Fish
1001-p01. >0101-p02. >101-g001-g+:::aa*)?v101-p03. >02-g?v1}02-p02. >05. >0}02-p02. >~~~0101-p001-g:1+001-paa*)?v02. >07. >0101-p08. >101-g::02-g?v >1+:101-paa*=?; >n" "o^
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)
#Maxima
Maxima
/* Declare an array, subscripts run from 0 to max value */ array(a, flonum, 20, 20, 3)$   arrayinfo(a); /* [complete, 3, [20, 20, 3]] */   a[0, 0]: 1.0;   listarray(a); /* [1.0, 0.0, 0.0, ..., 0.0] */   /* Show all declared arrays */ arrays; /* [a] */     /* One may also use an array without declaring it, it's a hashed array */ b[1]: 1000; b['x]: 3/4; /* hashed array may have any subscript */   arrayinfo(b); /* [hashed, 1, [1], [x]] */   listarray(b); /* [1000, 3/4] */
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
#Oz
Oz
declare Y = fun {$ F} {fun {$ X} {X X} end fun {$ X} {F fun {$ Z} {{X X} Z} end} end} end   Fac = {Y fun {$ F} fun {$ N} if N == 0 then 1 else N*{F N-1} end end end}   Fib = {Y fun {$ F} fun {$ N} case N of 0 then 0 [] 1 then 1 else {F N-1} + {F N-2} end end end} in {Show {Fac 5}} {Show {Fib 8}}
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
#ooRexx
ooRexx
  call printArray zigzag(3) say call printArray zigzag(4) say call printArray zigzag(5)   ::routine zigzag use strict arg size   data = .array~new(size, size) row = 1 col = 1   loop element = 0 to (size * size) - 1 data[row, col] = element -- even stripes if (row + col) // 2 = 0 then do if col < size then col += 1 else row += 2 if row > 1 then row -= 1 end -- odd rows else do if row < size then row += 1 else col += 2 if col > 1 then col -= 1 end end   return data   ::routine printArray use arg array dimension = array~dimension(1) loop i = 1 to dimension line = "|" loop j = 1 to dimension line = line array[i, j]~right(2) end line = line "|" say line 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.
#FOCAL
FOCAL
1.1 F N=1,100;S D(N)=0 1.2 F M=1,100;F N=M,M,100;S D(N)=1-D(N) 1.3 F N=1,100;D 2.0 1.4 Q 2.1 I (D(N)),,2.2;R 2.2 T "OPEN DOOR ",%3.0,N,!
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)
#Mercury
Mercury
:- module array_example. :- interface. :- import_module io. :- pred main(io::di, io::uo) is det. :- implementation. :- import_module array, int. :- use_module exception.   :- type example_error ---> impossible.   main(!IO) :- some [!A] ( % needed to introduce a state variable not present in the head  % Create an array(int) of length 10, with initial values of 0 array.init(10, 0, !:A),    % create an empty array (with no initial value)  % since the created array is never used, type inference can't tell what  % kind of array it is, and there's an unresolved polymorphism warning. array.make_empty_array(_Empty),    % resize our first array, so that we can then set its 17th member  % new values are set to -1 array.resize(20, -1, !A),  !A ^ elem(17) := 5,    % Mercury data structures tend to have deterministic (exception thrown  % on error), semideterministic (logical failure on error), and unsafe  % (undefined behavior on error) access methods. array.lookup(!.A, 5, _), % det ( if array.semidet_lookup(!.A, 100, _) then  % semidet exception.throw(impossible) else true ), array.unsafe_lookup(!.A, 5, _), % could cause a segfault on a smaller array    % output: array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, 5, -1, -1]) io.print_line(!.A, !IO),   plusminus(2, 0, !A),    % output: array([2, -2, 2, -2, 2, -2, 2, -2, 2, -2, 1, -3, 1, -3, 1, -3, 1, 3, 1, -3]) io.print_line(!.A, !IO) ).    % Sample predicate operating on an array.  % Note the array_* modes instead of in/out. :- pred plusminus(int, int, array(int), array(int)). :- mode plusminus(in, in, array_di, array_uo) is det. plusminus(N, I, !A) :- ( if array.semidet_lookup(!.A, I, X) then  !A ^ unsafe_elem(I) := X + N, plusminus(-N, I+1, !A) else true ).
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
#PARI.2FGP
PARI/GP
Y(f)=x->f(f,x); fact=Y((f,n)->if(n,n*f(f,n-1),1)); fib=Y((f,n)->if(n>1,f(f,n-1)+f(f,n-2),n)); apply(fact, [1..10]) apply(fib, [1..10])
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
#Oz
Oz
declare %% state move success failure States = unit(right: [ 1# 0 downLeft downInstead] downInstead: [ 0# 1 downLeft terminate] downLeft: [~1# 1 downLeft down] down: [ 0# 1 topRight rightInstead] rightInstead: [ 1# 0 topRight terminate] topRight: [ 1#~1 topRight right])   fun {CreateZigZag N} ZZ = {Create2DTuple N N}   %% recursively walk through 2D tuple and set values proc {Walk Pos=X#Y Count State} [Dir Success Failure] = States.State NextPos = {Record.zip Pos Dir Number.'+'} Valid = {Record.all NextPos fun {$ C} C > 0 andthen C =< N end} NewPos = if Valid then NextPos else Pos end NewCount = if Valid then Count + 1 else Count end NewState = if Valid then Success else Failure end in ZZ.Y.X = Count if NewState \= terminate then {Walk NewPos NewCount NewState} end end in {Walk 1#1 0 right} ZZ end   fun {Create2DTuple W H} T = {MakeTuple unit H} in {Record.forAll T fun {$} {MakeTuple unit W} end} T end in {Inspect {CreateZigZag 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.
#Forth
Forth
: toggle ( c-addr -- ) \ toggle the byte at c-addr dup c@ 1 xor swap c! ;   100 1+ ( 1-based indexing ) constant ndoors create doors ndoors allot   : init ( -- ) doors ndoors erase ; \ close all doors   : pass ( n -- ) \ toggle every nth door ndoors over do doors i + toggle dup ( n ) +loop drop ;   : run ( -- ) ndoors 1 do i pass loop ; : display ( -- ) \ display open doors ndoors 1 do doors i + c@ if i . then loop cr ;   init run display
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)
#MiniScript
MiniScript
+ list concatenation * replication (i.e. repeat the list some number of times) / division (get some fraction of a list) ==, != comparison (for equality) [i] get/set item i (first item is 0) [i:j] get sublist ("slice") from i up to j
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
#Perl
Perl
sub Y { my $f = shift; # λf. sub { my $x = shift; $x->($x) }->( # (λx.x x) sub {my $y = shift; $f->(sub {$y->($y)(@_)})} # λy.f λz.y y z ) } my $fac = sub {my $f = shift; sub {my $n = shift; $n < 2 ? 1 : $n * $f->($n-1)} }; my $fib = sub {my $f = shift; sub {my $n = shift; $n == 0 ? 0 : $n == 1 ? 1 : $f->($n-1) + $f->($n-2)} }; for my $f ($fac, $fib) { print join(' ', map Y($f)->($_), 0..9), "\n"; }