task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 0 1 5 6 14 2 4 7 13 15 3 8 12 16 21 9 11 17 20 22 10 18 19 23 24 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Icon_and_Unicon
Icon and Unicon
procedure main(args) n := integer(!args) | 5 every !(A := list(n)) := list(n) A := zigzag(A) show(A) end   procedure show(A) every writes(right(!A,5) | "\n") end   procedure zigzag(A) x := [0,0] every i := 0 to (*A^2 -1) do { x := nextIndices(*A, x) A[x[1]][x[2]] := i } return A end   procedure nextIndices(n, x) return if (x[1]+x[2])%2 = 0 then if x[2] = n then [x[1]+1, x[2]] else [max(1, x[1]-1), x[2]+1] else if x[1] = n then [x[1], x[2]+1] else [x[1]+1, max(1, x[2]-1)] end
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 {\displaystyle 5^{4^{3^{2}}}} Confirm that the first and last twenty digits of the answer are: 62060698786608744707...92256259918212890625 Find and show the number of decimal digits in the answer. Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead. Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value. Related tasks   Long multiplication   Exponentiation order   exponentiation operator   Exponentiation with infix operators in (or operating on) the base
#SIMPOL
SIMPOL
constant FIRST20 "62060698786608744707" constant LAST20 "92256259918212890625"   function main() integer i string s, s2   i = .ipower(5, .ipower(4, .ipower(3, 2))) s2 = .tostr(i, 10) if .lstr(s2, 20) == FIRST20 and .rstr(s2, 20) == LAST20 s = "Success! The integer matches both the first 20 and the last 20 digits. There are " + .tostr(.len(s2), 10) + " digits in the result.{d}{a}" else s = "" if .lstr(s2, 20) != FIRST20 s = "Failure! The first 20 digits are: " + .lstr(s2, 20) + " but they should be: " + FIRST20 + "{d}{a}" end if if .rstr(s2, 20) != LAST20 s = s + "Failure! The first 20 digits are: " + .lstr(s2, 20) + " but they should be: " + LAST20 + "{d}{a}" end if end if end function s
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 {\displaystyle 5^{4^{3^{2}}}} Confirm that the first and last twenty digits of the answer are: 62060698786608744707...92256259918212890625 Find and show the number of decimal digits in the answer. Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead. Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value. Related tasks   Long multiplication   Exponentiation order   exponentiation operator   Exponentiation with infix operators in (or operating on) the base
#Smalltalk
Smalltalk
|num| num := (5 raisedTo: (4 raisedTo: (3 raisedTo: 2))) asString. Transcript show: (num first: 20), '...', (num last: 20); cr; show: 'digits: ', num size asString.
http://rosettacode.org/wiki/Zeckendorf_number_representation
Zeckendorf number representation
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100. 10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution. Task Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. Also see   OEIS A014417   for the the sequence of required results.   Brown's Criterion - Numberphile Related task   Fibonacci sequence
#Standard_ML
Standard ML
  val zeckList = fn from => fn to =>   let open IntInf   val rec npow = fn n => fn 0 => fromInt 1 | m => n* (npow n (m-1)) ;   val fib = fn 0 => 1 | 1 => 1 | n => let val rec fb = fn x => fn y => fn 1=>y | n=> fb y (x+y) (n-1) in fb 0 1 n end;   val argminfi = fn n => (* lowest k with fibonacci number over n *) let val rec afb = fn k => if fib k > n then k else afb (k+1) in afb 0 end;   val Zeck = fn n => let val rec calzk = fn (0,z) => (0,z) | (n,z) => let val k = argminfi n in calzk ( n - fib (k-1) , z + (npow 10 (k-3) ) ) end in #2 (calzk (n,0)) end   in List.tabulate (toInt ( to - from) , fn i:Int.int => ( from + (fromInt i), Zeck ( from + (fromInt i) ))) end;  
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.
#EchoLisp
EchoLisp
  ; initial state = closed = #f (define doors (make-vector 101 #f)) ; run pass 100 to 1 (for* ((pass (in-range 100 0 -1)) (door (in-range 0 101 pass))) (when (and (vector-set! doors door (not (vector-ref doors door))) (= pass 1)) (writeln door "is open")))   1 "is open" 4 "is open" 9 "is open" 16 "is open" 25 "is open" 36 "is open" 49 "is open" 64 "is open" 81 "is open" 100 "is open"  
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)
#Julia
Julia
julia> A = cell(3) # create an heterogeneous array of length 3 3-element Array{Any,1}: #undef #undef #undef julia> A[1] = 4.5 ; A[3] = "some string" ; show(A) {4.5,#undef,"some string"} julia> A[1] # access a value. Arrays are 1-indexed 4.5 julia> push!(A, :symbol) ; show(A) # append an element {4.5,#undef,"some string",:symbol} julia> A[10] # error if the index is out of range ERROR: BoundsError()
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time,   you may also try something like: x = 0 y = 0 z = x**y say 'z=' z Show the result here. And of course use any symbols or notation that is supported in your computer programming language for exponentiation. See also The Wiki entry: Zero to the power of zero. The Wiki entry: History of differing points of view. The MathWorld™ entry: exponent laws. Also, in the above MathWorld™ entry, see formula (9): x 0 = 1 {\displaystyle x^{0}=1} . The OEIS entry: The special case of zero to the zeroth power
#XLISP
XLISP
XLISP 3.3, September 6, 2002 Copyright (c) 1984-2002, by David Betz [1] (expt 0 0)   1 [2]
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time,   you may also try something like: x = 0 y = 0 z = x**y say 'z=' z Show the result here. And of course use any symbols or notation that is supported in your computer programming language for exponentiation. See also The Wiki entry: Zero to the power of zero. The Wiki entry: History of differing points of view. The MathWorld™ entry: exponent laws. Also, in the above MathWorld™ entry, see formula (9): x 0 = 1 {\displaystyle x^{0}=1} . The OEIS entry: The special case of zero to the zeroth power
#XPL0
XPL0
RlOut(0, Pow(0., 0.))
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
#Nim
Nim
import algorithm, strformat, sequtils   type   Color {.pure.} = enum Blue, Green, Red, White, Yellow Person {.pure.} = enum Dane, English, German, Norwegian, Swede Pet {.pure.} = enum Birds, Cats, Dog, Horse, Zebra Drink {.pure.} = enum Beer, Coffee, Milk, Tea, Water Cigarettes {.pure.} = enum Blend, BlueMaster = "Blue Master", Dunhill, PallMall = "Pall Mall", Prince   House = tuple color: Color person: Person pet: Pet drink: Drink cigarettes: Cigarettes   Houses = array[5, House]     iterator permutations[T](): array[5, T] = ## Yield the successive permutations of values of type T. var term = [T(0), T(1), T(2), T(3), T(4)] yield term while term.nextPermutation(): yield term     proc findSolutions(): seq[Houses] = ## Return all the solutions.   for colors in permutations[Color](): if colors.find(White) != colors.find(Green) + 1: continue # 5 for persons in permutations[Person](): if persons[0] != Norwegian: continue # 10 if colors.find(Red) != persons.find(English): continue # 2 if abs(persons.find(Norwegian) - colors.find(Blue)) != 1: continue # 15 for pets in permutations[Pet](): if persons.find(Swede) != pets.find(Dog): continue # 3 for drinks in permutations[Drink](): if drinks[2] != Milk: continue # 9 if persons.find(Dane) != drinks.find(Tea): continue # 4 if colors.find(Green) != drinks.find(Coffee): continue # 6 for cigarettes in permutations[Cigarettes](): if cigarettes.find(PallMall) != pets.find(Birds): continue # 7 if cigarettes.find(Dunhill) != colors.find(Yellow): continue # 8 if cigarettes.find(BlueMaster) != drinks.find(Beer): continue # 13 if cigarettes.find(Prince) != persons.find(German): continue # 14 if abs(cigarettes.find(Blend) - pets.find(Cats)) != 1: continue # 11 if abs(cigarettes.find(Dunhill) - pets.find(Horse)) != 1: continue # 12 if abs(cigarettes.find(Blend) - drinks.find(Water)) != 1: continue # 16 var houses: Houses for i in 0..4: houses[i] = (colors[i], persons[i], pets[i], drinks[i], cigarettes[i]) result.add houses   let solutions = findSolutions() echo "Number of solutions: ", solutions.len let sol = solutions[0] echo()   echo "Number Color Person Pet Drink Cigarettes" echo "—————— —————— ————————— ————— —————— ———————————" for i in 0..4: echo &"{i + 1:3} {sol[i].color:6} {sol[i].person:9} ", &"{sol[i].pet:5} {sol[i].drink:6} {sol[i].cigarettes: 11}"   let owner = sol.filterIt(it.pet == Zebra)[0].person echo &"\nThe {owner} owns the zebra."
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="health"> <item upc="123456789" stock="12"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item upc="445322344" stock="18"> <name>Levitation Salve</name> <price>23.99</price> <description>Levitate yourself for up to 3 hours per application</description> </item> </section> <section name="food"> <item upc="485672034" stock="653"> <name>Blork and Freen Instameal</name> <price>4.95</price> <description>A tasty meal in a tablet; just add water</description> </item> <item upc="132957764" stock="44"> <name>Grob winglets</name> <price>3.56</price> <description>Tender winglets of Grob. Just add water</description> </item> </section> </inventory>
#Ruby
Ruby
#Example taken from the REXML tutorial (http://www.germane-software.com/software/rexml/docs/tutorial.html) require "rexml/document" include REXML #create the REXML Document from the string (%q is Ruby's multiline string, everything between the two @-characters is the string) doc = Document.new( %q@<inventory title="OmniCorp Store #45x10^3"> ... </inventory> @ ) # The invisibility cream is the first <item> invisibility = XPath.first( doc, "//item" ) # Prints out all of the prices XPath.each( doc, "//price") { |element| puts element.text } # Gets an array of all of the "name" elements in the document. names = XPath.match( doc, "//name" )
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="health"> <item upc="123456789" stock="12"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item upc="445322344" stock="18"> <name>Levitation Salve</name> <price>23.99</price> <description>Levitate yourself for up to 3 hours per application</description> </item> </section> <section name="food"> <item upc="485672034" stock="653"> <name>Blork and Freen Instameal</name> <price>4.95</price> <description>A tasty meal in a tablet; just add water</description> </item> <item upc="132957764" stock="44"> <name>Grob winglets</name> <price>3.56</price> <description>Tender winglets of Grob. Just add water</description> </item> </section> </inventory>
#Scala
Scala
  scala> val xml: scala.xml.Elem = | <inventory title="OmniCorp Store #45x10^3"> | <section name="health"> | <item upc="123456789" stock="12"> | <name>Invisibility Cream</name> | <price>14.50</price> | <description>Makes you invisible</description> | </item> | <item upc="445322344" stock="18"> | <name>Levitation Salve</name> | <price>23.99</price> | <description>Levitate yourself for up to 3 hours per application</description> | </item> | </section> | <section name="food"> | <item upc="485672034" stock="653"> | <name>Blork and Freen Instameal</name> | <price>4.95</price> | <description>A tasty meal in a tablet; just add water</description> | </item> | <item upc="132957764" stock="44"> | <name>Grob winglets</name> | <price>3.56</price> | <description>Tender winglets of Grob. Just add water</description> | </item> | </section> | </inventory>   scala> val firstItem = xml \\ "item" take 1 firstItem: scala.xml.NodeSeq = NodeSeq(<item upc="123456789" stock="12"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item>)   scala> xml \\ "price" map (_.text) foreach println 14.50 23.99 4.95 3.56   scala> val names = (xml \\ "name").toArray names: Array[scala.xml.Node] = Array(<name>Invisibility Cream</name>, <name>Levitation Salve</name>, <name>Blork and Freen Instameal</name>, <name>Grob winglets</name>)
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.
#Perl
Perl
sub circle { my ($radius, $cx, $cy, $fill, $stroke) = @_; print "<circle cx='$cx' cy='$cy' r='$radius' ", "fill='$fill' stroke='$stroke' stroke-width='1'/>\n"; }   sub yin_yang { my ($rad, $cx, $cy, %opt) = @_; my ($c, $w) = (1, 0); $opt{fill} //= 'white'; $opt{stroke} //= 'black'; $opt{recurangle} //= 0;   print "<g transform='rotate($opt{angle}, $cx, $cy)'>" if $opt{angle};   if ($opt{flip}) { ($c, $w) = ($w, $c) };   circle($rad, $cx, $cy, $opt{fill}, $opt{stroke});   print "<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='$opt{stroke}' stroke='none' />";   if ($opt{recur} and $rad > 1) { # recursive "eyes" are slightly larger yin_yang($rad/4, $cx, $cy + $rad/2, %opt, angle => $opt{recurangle}, fill => $opt{stroke}, stroke => $opt{fill} ); yin_yang($rad/4, $cx, $cy - $rad/2, %opt, angle => 180 + $opt{recurangle}); } else { circle($rad/5, $cx, $cy + $rad/2, $opt{fill}, $opt{stroke}); circle($rad/5, $cx, $cy - $rad/2, $opt{stroke}, $opt{fill}); } print "</g>" if $opt{angle}; }   print <<'HEAD'; <?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"> HEAD   yin_yang(200, 250, 250, recur=>1, angle=>0, recurangle=>90, fill=>'white', stroke=>'black'); yin_yang(100, 500, 500);   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
#GAP
GAP
Y := function(f) local u; u := x -> x(x); return u(y -> f(a -> y(y)(a))); end;   fib := function(f) local u; u := function(n) if n < 2 then return n; else return f(n-1) + f(n-2); fi; end; return u; end;   Y(fib)(10); # 55   fac := function(f) local u; u := function(n) if n < 2 then return 1; else return n*f(n-1); fi; end; return u; end;   Y(fac)(8); # 40320
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
#IS-BASIC
IS-BASIC
100 PROGRAM "ZigZag.bas" 110 LET SIZE=5 120 NUMERIC A(1 TO SIZE,1 TO SIZE) 130 LET I,J=1 140 FOR E=0 TO SIZE^2-1 150 LET A(I,J)=E 160 IF ((I+J) BAND 1)=0 THEN 170 IF J<SIZE THEN 180 LET J=J+1 190 ELSE 200 LET I=I+2 210 END IF 220 IF I>1 THEN LET I=I-1 230 ELSE 240 IF I<SIZE THEN 250 LET I=I+1 260 ELSE 270 LET J=J+2 280 END IF 290 IF J>1 THEN LET J=J-1 300 END IF 310 NEXT 320 FOR ROW=1 TO SIZE 330 FOR COL=1 TO SIZE 340 PRINT USING " ##":A(ROW,COL); 350 NEXT 360 PRINT 370 NEXT
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 {\displaystyle 5^{4^{3^{2}}}} Confirm that the first and last twenty digits of the answer are: 62060698786608744707...92256259918212890625 Find and show the number of decimal digits in the answer. Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead. Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value. Related tasks   Long multiplication   Exponentiation order   exponentiation operator   Exponentiation with infix operators in (or operating on) the base
#SPL
SPL
t = #.str(5^(4^(3^2))) n = #.size(t) #.output(n," digits") #.output(#.mid(t,1,20),"...",#.mid(t,n-19,20))
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 {\displaystyle 5^{4^{3^{2}}}} Confirm that the first and last twenty digits of the answer are: 62060698786608744707...92256259918212890625 Find and show the number of decimal digits in the answer. Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead. Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value. Related tasks   Long multiplication   Exponentiation order   exponentiation operator   Exponentiation with infix operators in (or operating on) the base
#Standard_ML
Standard ML
let val answer = IntInf.pow (5, IntInf.toInt (IntInf.pow (4, IntInf.toInt (IntInf.pow (3, 2))))) val s = IntInf.toString answer val len = size s in print ("has " ^ Int.toString len ^ " digits: " ^ substring (s, 0, 20) ^ " ... " ^ substring (s, len-20, 20) ^ "\n") end;
http://rosettacode.org/wiki/Zeckendorf_number_representation
Zeckendorf number representation
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100. 10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution. Task Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. Also see   OEIS A014417   for the the sequence of required results.   Brown's Criterion - Numberphile Related task   Fibonacci sequence
#Tcl
Tcl
package require Tcl 8.5   # Generates the Fibonacci sequence (starting at 1) up to the largest item that # is no larger than the target value. Could use tricks to precompute, but this # is actually a pretty cheap linear operation. proc fibseq target { set seq {}; set prev 1; set fib 1 for {set n 1;set i 1} {$fib <= $target} {incr n} { for {} {$i < $n} {incr i} { lassign [list $fib [incr fib $prev]] prev fib } if {$fib <= $target} { lappend seq $fib } } return $seq }   # Produce the given Zeckendorf number. proc zeckendorf n { # Special case: only value that begins with 0 if {$n == 0} {return 0} set zs {} foreach f [lreverse [fibseq $n]] { lappend zs [set z [expr {$f <= $n}]] if {$z} {incr n [expr {-$f}]} } return [join $zs ""] }
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.
#ECL
ECL
  Doors := RECORD UNSIGNED1 DoorNumber; STRING6 State; END;   AllDoors := DATASET([{0,0}],Doors);   Doors OpenThem(AllDoors L,INTEGER Cnt) := TRANSFORM SELF.DoorNumber := Cnt; SELF.State  := IF((CNT * 10) % (SQRT(CNT)*10)<>0,'Closed','Opened'); END;   OpenDoors := NORMALIZE(AllDoors,100,OpenThem(LEFT,COUNTER));   OpenDoors;  
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)
#KonsolScript
KonsolScript
//creates an array of length 3 Array:New array[3]:Number;   function main() { Var:Number length; Array:GetLength(array, length) //retrieve length of array Konsol:Log(length)   array[0] = 5; //assign value Konsol:Log(array[0]) //retrieve value and display }
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time,   you may also try something like: x = 0 y = 0 z = x**y say 'z=' z Show the result here. And of course use any symbols or notation that is supported in your computer programming language for exponentiation. See also The Wiki entry: Zero to the power of zero. The Wiki entry: History of differing points of view. The MathWorld™ entry: exponent laws. Also, in the above MathWorld™ entry, see formula (9): x 0 = 1 {\displaystyle x^{0}=1} . The OEIS entry: The special case of zero to the zeroth power
#Zig
Zig
const std = @import("std");   pub fn main() !void { const stdout = std.io.getStdOut().writer(); try stdout.print("0^0 = {d:.8}\n", .{std.math.pow(f32, 0, 0)}); }
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time,   you may also try something like: x = 0 y = 0 z = x**y say 'z=' z Show the result here. And of course use any symbols or notation that is supported in your computer programming language for exponentiation. See also The Wiki entry: Zero to the power of zero. The Wiki entry: History of differing points of view. The MathWorld™ entry: exponent laws. Also, in the above MathWorld™ entry, see formula (9): x 0 = 1 {\displaystyle x^{0}=1} . The OEIS entry: The special case of zero to the zeroth power
#zkl
zkl
(0.0).pow(0) //--> 1.0 var BN=Import("zklBigNum"); // big ints BN(0).pow(0) //--> 1
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
#Pari.2FGp
Pari/Gp
  perm(arr) = { n=#arr;i=n-1; while(i > -1,if (arr[i] < arr[i+1],break);i--); j=n; while(arr[j]<= arr[i],j -=1); tmp = arr[i] ;arr[i]=arr[j];arr[j]=tmp; i +=1; j = n; while(i < j ,tmp = arr[i] ;arr[i]=arr[j];arr[j]=tmp; i +=1; j -=1); return(arr); } perms(arr)={ n=#arr; result = List(); listput(result,arr); for(i=1,n!-1,arr=perm(arr);listput(result,arr)); return(result); }   adj(x,xs,y,ys)={ abs(select(z->z==x,xs,1)[1] - select(z->z==y,ys,1)[1])==1; } eq(x,xs,y,ys)={ select(z->z==x,xs,1) == select(z->z==y,ys,1); }   colors =Vec(perms( ["Blue", "Green", "Red", "White", "Yellow"]));; drinks =Vec(perms( ["Beer", "Coffee", "Milk", "Tea", "Water"]));; nations =Vec(perms( ["Denmark", "England", "Germany", "Norway", "Sweden"]));; smokes =Vec(perms( ["Blend", "BlueMaster", "Dunhill", "PallMall", "Prince"]));; pets =Vec(perms( ["Birds", "Cats", "Dog", "Horse", "Zebra"]));;; colors= select(x->select(z->z=="White",x,1)[1] - select(z->z=="Green",x,1)[1]==1,colors); drinks=select(x->x[3]=="Milk",drinks); nations=select(x->x[1]=="Norway",nations);   for(n=1,#nations,for(c=1,#colors,\ if(eq("Red",colors[c],"England",nations[n]) && adj("Norway",nations[n],"Blue",colors[c]),\ for(d=1,#drinks,\ if(eq("Denmark",nations[n],"Tea",drinks[d])&& eq("Coffee",drinks[d],"Green",colors[c]),\ for(s=1,#smokes,\ if(eq("Yellow",colors[c],"Dunhill",smokes[s]) &&\ eq("BlueMaster",smokes[s],"Beer",drinks[d]) &&\ eq("Germany",nations[n],"Prince",smokes[s]),\ for(p=1,#pets,\ if(eq("Birds",pets[p],"PallMall",smokes[s]) &&\ eq("Sweden",nations[n],"Dog",pets[p]) &&\ adj("Blend",smokes[s],"Cats",pets[p]) &&\ adj("Horse",pets[p],"Dunhill",smokes[s]),\ print("Zebra is owned by ",nations[n][select(z->z=="Zebra",pets[p],1)[1]]);print();\ for(i=1,5,printf("House:%s %6s %10s %10s %10s %10s\n",i,colors[c][i],nations[n][i],pets[p][i],drinks[d][i],smokes[s][i]));\ )))))))));  
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="health"> <item upc="123456789" stock="12"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item upc="445322344" stock="18"> <name>Levitation Salve</name> <price>23.99</price> <description>Levitate yourself for up to 3 hours per application</description> </item> </section> <section name="food"> <item upc="485672034" stock="653"> <name>Blork and Freen Instameal</name> <price>4.95</price> <description>A tasty meal in a tablet; just add water</description> </item> <item upc="132957764" stock="44"> <name>Grob winglets</name> <price>3.56</price> <description>Tender winglets of Grob. Just add water</description> </item> </section> </inventory>
#SenseTalk
SenseTalk
Set XMLSource to {{ <inventory title="OmniCorp Store #45x10^3"> <section name="health"> <item upc="123456789" stock="12"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item upc="445322344" stock="18"> <name>Levitation Salve</name> <price>23.99</price> <description>Levitate yourself for up to 3 hours per application</description> </item> </section> <section name="food"> <item upc="485672034" stock="653"> <name>Blork and Freen Instameal</name> <price>4.95</price> <description>A tasty meal in a tablet; just add water</description> </item> <item upc="132957764" stock="44"> <name>Grob winglets</name> <price>3.56</price> <description>Tender winglets of Grob. Just add water</description> </item> </section> </inventory> }}   put node "//item[1]" of XMLSource put node "//price/text()" of XMLSource put all nodes "//name" of XMLSource
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="health"> <item upc="123456789" stock="12"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item upc="445322344" stock="18"> <name>Levitation Salve</name> <price>23.99</price> <description>Levitate yourself for up to 3 hours per application</description> </item> </section> <section name="food"> <item upc="485672034" stock="653"> <name>Blork and Freen Instameal</name> <price>4.95</price> <description>A tasty meal in a tablet; just add water</description> </item> <item upc="132957764" stock="44"> <name>Grob winglets</name> <price>3.56</price> <description>Tender winglets of Grob. Just add water</description> </item> </section> </inventory>
#Sidef
Sidef
require('XML::XPath');   var x = %s'XML::XPath'.new(ARGF.slurp);   [x.findnodes('//item[1]')][0]; say [x.findnodes('//price')].map{x.getNodeText(_)}; [x.findnodes('//name')];
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.
#Phix
Phix
-- -- demo\rosetta\Yin_and_yang.exw -- ============================= -- with javascript_semantics include pGUI.e Ihandle dlg, canvas cdCanvas cd_canvas procedure cdCanvasSecArc(cdCanvas hCdCanvas, atom xc, atom yc, atom w, atom h, atom angle1, atom angle2) -- cdCanvasSector does not draw anti-aliased edges, but cdCanvasArc does, so over-draw... cdCanvasSector(hCdCanvas, xc, yc, w, h, angle1, angle2) cdCanvasArc (hCdCanvas, xc, yc, w, h, angle1, angle2) end procedure procedure yinyang(atom cx, cy, r) cdCanvasArc(cd_canvas, cx, cy, r, r, 0, 360) cdCanvasSecArc(cd_canvas, cx, cy, r, r, 270, 90) cdCanvasSecArc(cd_canvas, cx, cy-r/4, r/2-1, r/2-1, 0, 360) cdCanvasSetForeground(cd_canvas, CD_WHITE) cdCanvasSecArc(cd_canvas, cx, cy+r/4, r/2-1, r/2-1, 0, 360) cdCanvasSecArc(cd_canvas, cx, cy-r/4, r/8, r/8, 0, 360) cdCanvasSetForeground(cd_canvas, CD_BLACK) cdCanvasSecArc(cd_canvas, cx, cy+r/4, r/8, r/8, 0, 360) end procedure function redraw_cb(Ihandle /*ih*/) integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE"), r = min(width,height)-40, cx = floor(width/2), cy = floor(height/2) cdCanvasActivate(cd_canvas) cdCanvasClear(cd_canvas) yinyang(cx-r*.43,cy+r*.43,r/6) yinyang(cx,cy,r) cdCanvasFlush(cd_canvas) return IUP_DEFAULT end function function map_cb(Ihandle ih) IupGLMakeCurrent(canvas) if platform()=JS then cd_canvas = cdCreateCanvas(CD_IUP, canvas) else atom res = IupGetDouble(NULL, "SCREENDPI")/25.4 cd_canvas = cdCreateCanvas(CD_GL, "10x10 %g", {res}) end if cdCanvasSetBackground(cd_canvas, CD_WHITE) cdCanvasSetForeground(cd_canvas, CD_BLACK) return IUP_DEFAULT end function function canvas_resize_cb(Ihandle /*canvas*/) integer {canvas_width, canvas_height} = IupGetIntInt(canvas, "DRAWSIZE") atom res = IupGetDouble(NULL, "SCREENDPI")/25.4 cdCanvasSetAttribute(cd_canvas, "SIZE", "%dx%d %g", {canvas_width, canvas_height, res}) return IUP_DEFAULT end function procedure main() IupOpen() canvas = IupGLCanvas("RASTERSIZE=340x340") IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"), "RESIZE_CB", Icallback("canvas_resize_cb"), "ACTION", Icallback("redraw_cb")}) dlg = IupDialog(canvas, `TITLE="Yin and Yang"`) IupShow(dlg) IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation if platform()!=JS then IupMainLoop() IupClose() end if end procedure main()
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
#Genyris
Genyris
def fac (f) function (n) if (equal? n 0) 1 * n (f (- n 1)) def fib (f) function (n) cond (equal? n 0) 0 (equal? n 1) 1 else (+ (f (- n 1)) (f (- n 2)))   def Y (f) (function (x) (x x)) function (y) f function (&rest args) (apply (y y) args)   assertEqual ((Y fac) 5) 120 assertEqual ((Y fib) 8) 21
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
#J
J
($ [: /:@; <@|.`</.@i.)@,~ 5 0 1 5 6 14 2 4 7 13 15 3 8 12 16 21 9 11 17 20 22 10 18 19 23 24
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 {\displaystyle 5^{4^{3^{2}}}} Confirm that the first and last twenty digits of the answer are: 62060698786608744707...92256259918212890625 Find and show the number of decimal digits in the answer. Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead. Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value. Related tasks   Long multiplication   Exponentiation order   exponentiation operator   Exponentiation with infix operators in (or operating on) the base
#Stata
Stata
set bigValue [expr {5**4**3**2}] puts "5**4**3**2 has [string length $bigValue] digits" if {[string match "62060698786608744707*92256259918212890625" $bigValue]} { puts "Value starts with 62060698786608744707, ends with 92256259918212890625" } else { puts "Value does not match 62060698786608744707...92256259918212890625" }
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 {\displaystyle 5^{4^{3^{2}}}} Confirm that the first and last twenty digits of the answer are: 62060698786608744707...92256259918212890625 Find and show the number of decimal digits in the answer. Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead. Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value. Related tasks   Long multiplication   Exponentiation order   exponentiation operator   Exponentiation with infix operators in (or operating on) the base
#Tcl
Tcl
set bigValue [expr {5**4**3**2}] puts "5**4**3**2 has [string length $bigValue] digits" if {[string match "62060698786608744707*92256259918212890625" $bigValue]} { puts "Value starts with 62060698786608744707, ends with 92256259918212890625" } else { puts "Value does not match 62060698786608744707...92256259918212890625" }
http://rosettacode.org/wiki/Zeckendorf_number_representation
Zeckendorf number representation
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100. 10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution. Task Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. Also see   OEIS A014417   for the the sequence of required results.   Brown's Criterion - Numberphile Related task   Fibonacci sequence
#uBasic.2F4tH
uBasic/4tH
For x = 0 to 20 ' Print Zeckendorf numbers 0 - 20 Print x, Push x : Gosub _Zeckendorf ' get Zeckendorf number repres. Print ' terminate line Next   End   _Fibonacci Push Tos() ' duplicate TOS() @(0) = 0 ' This function returns the @(1) = 1 ' Fibonacci number which is smaller ' or equal to TOS() Do While @(1) < Tos() + 1 Push (@(1)) @(1) = @(0) + @(1) ' get next Fibonacci number @(0) = Pop() Loop ' loop if not exceeded TOS()   Gosub _Drop ' clear TOS() Push @(0) ' return Fibonacci number Return   _Zeckendorf GoSub _Fibonacci ' This function breaks TOS() up Print Tos(); ' into its Zeckendorf components Push -(Pop() - Pop()) ' first digit is always there ' the remainder to resolve Do While Tos() ' now go for the next digits GoSub _Fibonacci Print " + ";Tos(); ' print the next digit Push -(Pop() - Pop()) Loop   Gosub _Drop ' clear TOS() Return ' and return   _Drop If Pop()%1 = 0 Then Return ' This function clears TOS()
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.
#EDSAC_order_code
EDSAC order code
  [Hundred doors problem from Rosetta Code website] [EDSAC program, Initial Orders 2]   [Library subroutine M3. Prints header and is then overwritten. Here, the last character sets the teleprinter to figures.] PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF @&*THE!OPEN!DOORS!ARE@&# ..PZ [blank tape, needed to mark end of header text]   [Library subroutine P6. Prints strictly positive integer. 32 locations; working locations 1, 4, 5] T56K [define load address for subroutine] GKA3FT25@H29@VFT4DA3@TFH30@S6@T1F V4DU4DAFG26@TFTFO5FA4DF4FS4F L4FT4DA1FS3@G9@EFSFO31@E20@J995FJF!F   T88K [define load address for main program] GK [set @ (theta) for relative addresses]   [The 100 doors are at locations 200..299. Doors are numbered 0..99 internally, and 1..100 for output. The base address and the number of doors can be varied. The value of a door is 0 if open, negative if closed.]   [Constants. Program also uses order 'P 1 F' which is permanently at absolute address 2.] [0] P200F [address of door #0] [1] P100F [number of doors, as an address] [2] UF [makes S order from T, since 'S' = 'T' + 'U'] [3] MF [makes A order from T, since 'A' = 'T' + 'M'] [4] V2047D [all 1's for "closed" (any negative value will do)] [5] &F [line feed] [6] @F [carriage return] [7] K4096F [teleprinter null[   [Variables] [8] PF [pass number; step when toggling doors] [9] PF [door number, as address, 0-based] [10] PF [order referring to door 0]   [Enter with acc = 0] [Part 1 : close all the doors] [11] T8@ [pass := 0 (used in part 2)] T9@ [door number := 0] A16@ [load 'T F' order] A@ [add base address] T10@ [store T order for door #0] [16] TF [clear acc; also serves as constant] A9@ [load door number] A10@ [make T order] T21@ [plant in code] A4@ [load value for "closed"] [21] TF [store in current door] A9@ [load door number] A2F [add 1] U9@ [update door number] S1@ [done all doors yet?] G16@ [if not, loop back]   [Part 2 : 100 passes, toggling the doors] [27] TF [clear acc] A8@ [load pass number] A2F [add 1] T8@ [save updated pass number] S2F [make -1] U9@ [door number := -1] A8@ [add pass number to get first door toggled on this pass] S1@ [gone beyond end?] E50@ [if so, move on to part 3] [36] A1@ [restore acc after test] U9@ [store current door number] A10@ [make T order to load status] U44@ [plant T order for first door in pass] A2@ [convert to S order] T43@ [plant S order] A4@ [load value for "closed"] [43] SF [subtract status; toggles status] [44] TF [update status] A9@ [load door number just toggled] A8@ [add pass number to get next door in pass] S1@ [gone beyond end?] G36@ [no, loop to do next door] E27@ [yes, loop to do next pass]   [Part 3 : Print list of open doors. Header has set teleprinter to figures.] [50] TF [clear acc] T9@ [door nr := 0] A10@ [T order for door 0] A3@ [convert to A order] T10@ [55] TF A9@ [load door number] A10@ [make A order to load value] T59@ [plant in next order] [59] AF [acc := 0 if open, < 0 if closed] G69@ [skip if closed] A9@ [door number as address] A2F [add 1 for 1-based output] RD [shift 1 right, address --> integer] TF [store integer at 0 for printing] [65] A65@ [for return from subroutine] G56F [call subroutine to print door number] O6@ [followed by CRLF] O5@ [69] TF [clear acc] A9@ [load door number] A2F [add 1] U9@ [update door number] S1@ [done all doors yet?] G55@ [if not, loop back] [75] O7@ [output null to flush teleprinter buffer] ZF [stop] E11Z [define relative start address] PF  
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)
#Kotlin
Kotlin
fun main(x: Array<String>) { var a = arrayOf(1, 2, 3, 4) println(a.asList()) a += 5 println(a.asList()) println(a.reversedArray().asList()) }
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
#Perl
Perl
#!/usr/bin/perl   use utf8; use strict; binmode STDOUT, ":utf8";   my (@tgt, %names); sub setprops { my %h = @_; my @p = keys %h; for my $p (@p) { my @v = @{ $h{$p} }; @tgt = map(+{idx=>$_-1, map{ ($_, undef) } @p}, 1 .. @v) unless @tgt; $names{$_} = $p for @v; } }   my $solve = sub { for my $i (@tgt) { printf("%12s", ucfirst($i->{$_} // "¿Qué?")) for reverse sort keys %$i; print "\n"; } "there is only one" # <--- change this to a false value to find all solutions (if any) };   sub pair { my ($a, $b, @v) = @_; if ($a =~ /^(\d+)$/) { $tgt[$1]{ $names{$b} } = $b; return; }   @v = (0) unless @v; my %allowed; $allowed{$_} = 1 for @v;   my ($p1, $p2) = ($names{$a}, $names{$b});   my $e = $solve; $solve = sub { # <--- sorta like how TeX \let...\def macro my ($x, $y);   ($x) = grep { $_->{$p1} eq $a } @tgt; ($y) = grep { $_->{$p2} eq $b } @tgt;   $x and $y and return $allowed{ $x->{idx} - $y->{idx} } && $e->();   my $try_stuff = sub { my ($this, $p, $v, $sign) = @_; for (@v) { my $i = $this->{idx} + $sign * $_; next unless $i >= 0 && $i < @tgt && !$tgt[$i]{$p}; local $tgt[$i]{$p} = $v; $e->() and return 1; } return };   $x and return $try_stuff->($x, $p2, $b, 1); $y and return $try_stuff->($y, $p1, $a, -1);   for $x (@tgt) { next if $x->{$p1}; local $x->{$p1} = $a; $try_stuff->($x, $p2, $b, 1) and return 1; } }; }   # ---- above should be generic for all similar puzzles ---- #   # ---- below: per puzzle setup ---- # # property names and values setprops ( # Svensk n. a Swede, not a swede (kålrot). # AEnglisk (from middle Viking "Æŋløsåksen") n. a Brit. 'Who' => [ qw(Deutsch Svensk Norske Danske AEnglisk) ], 'Pet' => [ qw(birds dog horse zebra cats) ], 'Drink' => [ qw(water tea milk beer coffee) ], 'Smoke' => [ qw(dunhill blue_master prince blend pall_mall) ], 'Color' => [ qw(red green yellow white blue) ] );   # constraints pair qw( AEnglisk red ); pair qw( Svensk dog ); pair qw( Danske tea ); pair qw( green white 1 ); # "to the left of" can mean either 1 or -1: ambiguous pair qw( coffee green ); pair qw( pall_mall birds ); pair qw( yellow dunhill ); pair qw( 2 milk ); pair qw( 0 Norske ); pair qw( blend cats -1 1 ); pair qw( horse dunhill -1 1 ); pair qw( blue_master beer ); # Nicht das Deutsche Bier trinken? Huh. pair qw( Deutsch prince ); pair qw( Norske blue -1 1 ); pair qw( water blend -1 1 );   $solve->();
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="health"> <item upc="123456789" stock="12"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item upc="445322344" stock="18"> <name>Levitation Salve</name> <price>23.99</price> <description>Levitate yourself for up to 3 hours per application</description> </item> </section> <section name="food"> <item upc="485672034" stock="653"> <name>Blork and Freen Instameal</name> <price>4.95</price> <description>A tasty meal in a tablet; just add water</description> </item> <item upc="132957764" stock="44"> <name>Grob winglets</name> <price>3.56</price> <description>Tender winglets of Grob. Just add water</description> </item> </section> </inventory>
#Tcl
Tcl
# assume $xml holds the XML data package require tdom set doc [dom parse $xml] set root [$doc documentElement]   set allNames [$root selectNodes //name] puts [llength $allNames] ;# ==> 4   set firstItem [lindex [$root selectNodes //item] 0] puts [$firstItem @upc] ;# ==> 123456789   foreach node [$root selectNodes //price] { puts [$node text] }
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="health"> <item upc="123456789" stock="12"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item upc="445322344" stock="18"> <name>Levitation Salve</name> <price>23.99</price> <description>Levitate yourself for up to 3 hours per application</description> </item> </section> <section name="food"> <item upc="485672034" stock="653"> <name>Blork and Freen Instameal</name> <price>4.95</price> <description>A tasty meal in a tablet; just add water</description> </item> <item upc="132957764" stock="44"> <name>Grob winglets</name> <price>3.56</price> <description>Tender winglets of Grob. Just add water</description> </item> </section> </inventory>
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT,{} MODE DATA $$ XML=* <inventory title="OmniCorp Store #45x10³"> <section name="health"> <item upc="123456789" stock="12"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item upc="445322344" stock="18"> <name>Levitation Salve</name> <price>23.99</price> <description>Levitate yourself for up to 3 hours per application</description> </item> </section> <section name="food"> <item upc="485672034" stock="653"> <name>Blork and Freen Instameal</name> <price>4.95</price> <description>A tasty meal in a tablet; just add water</description> </item> <item upc="132957764" stock="44"> <name>Grob winglets</name> <price>3.56</price> <description>Tender winglets of Grob. Just add water</description> </item> </section> </inventory> $$ MODE TUSCRIPT   FILE = "test.xml" ERROR/STOP CREATE (file,fdf-o,-std-) FILE/ERASE/UTF8 $FILE = xml   BUILD S_TABLE beg=":<item*>:<name>:<price>:" BUILD S_TABLE end=":</item>:</name>:</price>:" BUILD S_TABLE modifiedbeg=":<name>:<price>:" BUILD S_TABLE modifiedend=":</name>:</price>:" firstitem=names="",countitem=0 ACCESS q: READ/STREAM/UTF8 $FILE s,a/beg+t+e/end LOOP READ/EXIT q IF (a=="<name>") names=APPEND(names,t) IF (a=="<price>") PRINT t IF (a.sw."<item") countitem=1 IF (countitem==1) THEN firstitem=CONCAT(firstitem,a) firstitem=CONCAT(firstitem,t) firstitem=CONCAT(firstitem,e) IF (e=="</item>") THEN COUNTITEM=0 MODIFY ACCESS q s_TABLE modifiedbeg,-,modifiedend ENDIF ENDIF ENDLOOP ENDACCESS q ERROR/STOP CLOSE (file) firstitem=EXCHANGE (firstitem,":{2-00} ::") firstitem=INDENT_TAGS (firstitem,-," ") names=SPLIT(names) TRACE *firstitem,names  
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.
#PHL
PHL
module circles;   extern printf;   @Boolean in_circle(@Integer centre_x, @Integer centre_y, @Integer radius, @Integer x, @Integer y) [ return (x-centre_x)*(x-centre_x)+(y-centre_y)*(y-centre_y) <= radius*radius; ]   @Boolean in_big_circle (@Integer radius, @Integer x, @Integer y) [ return in_circle(0, 0, radius, x, y); ]   @Boolean in_while_semi_circle (@Integer radius, @Integer x, @Integer y) [ return in_circle(0, radius/2, radius/2, x, y); ]   @Boolean in_small_white_circle (@Integer radius, @Integer x, @Integer y) [ return in_circle(0, 0-radius/2, radius/6, x, y); ]   @Boolean in_black_semi_circle (@Integer radius, @Integer x, @Integer y) [ return in_circle(0, 0-radius/2, radius/2, x, y); ]   @Boolean in_small_black_circle (@Integer radius, @Integer x, @Integer y) [ return in_circle(0, radius/2, radius/6, x, y); ]   @Void print_yin_yang(@Integer radius) [ var white = '.'; var black = '#'; var clear = ' ';   var scale_y = 1; var scale_x = 2; for (var sy = radius*scale_y; sy >= -(radius*scale_y); sy=sy-1) { for (var sx = -(radius*scale_x); sx <= radius*scale_x; sx=sx+1) { var x = sx/(scale_x); var y = sy/(scale_y);   if (in_big_circle(radius, x, y)) { if (in_while_semi_circle(radius, x, y)) if (in_small_black_circle(radius, x, y)) printf("%c", black); else printf("%c", white); else if (in_black_semi_circle(radius, x, y)) if (in_small_white_circle(radius, x, y)) printf("%c", white); else printf("%c", black); else if (x < 0) printf("%c", white); else printf("%c", black); } else printf("%c", clear); } printf("\n"); } ]   @Integer main [ print_yin_yang(17); print_yin_yang(8); return 0; ]
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.
#PicoLisp
PicoLisp
(de circle (X Y C R) (>= (* R R) (+ (* (setq X (/ X 2)) X) (* (dec 'Y C) Y) ) ) )   (de yinYang (R) (for Y (range (- R) R) (for X (range (- 0 R R) (+ R R)) (prin (cond ((circle X Y (- (/ R 2)) (/ R 6)) "#" ) ((circle X Y (/ R 2) (/ R 6)) "." ) ((circle X Y (- (/ R 2)) (/ R 2)) "." ) ((circle X Y (/ R 2) (/ R 2)) "#" ) ((circle X Y 0 R) (if (lt0 X) "." "#") ) (T " ") ) ) ) (prinl) ) )
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
#Go_2
Go
package main   import "fmt"   type Func func(int) int type FuncFunc func(Func) Func type RecursiveFunc func (RecursiveFunc) Func   func main() { fac := Y(almost_fac) fib := Y(almost_fib) fmt.Println("fac(10) = ", fac(10)) fmt.Println("fib(10) = ", fib(10)) }   func Y(f FuncFunc) Func { g := func(r RecursiveFunc) Func { return f(func(x int) int { return r(r)(x) }) } return g(g) }   func almost_fac(f Func) Func { return func(x int) int { if x <= 1 { return 1 } return x * f(x-1) } }   func almost_fib(f Func) Func { return func(x int) int { if x <= 2 { return 1 } return f(x-1)+f(x-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
#Java
Java
public static int[][] Zig_Zag(final int size) { int[][] data = new int[size][size]; int i = 1; int j = 1; for (int element = 0; element < size * size; element++) { data[i - 1][j - 1] = element; if ((i + j) % 2 == 0) { // Even stripes if (j < size) j++; else i+= 2; if (i > 1) i--; } else { // Odd stripes if (i < size) i++; else j+= 2; if (j > 1) j--; } } return data; }
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 {\displaystyle 5^{4^{3^{2}}}} Confirm that the first and last twenty digits of the answer are: 62060698786608744707...92256259918212890625 Find and show the number of decimal digits in the answer. Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead. Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value. Related tasks   Long multiplication   Exponentiation order   exponentiation operator   Exponentiation with infix operators in (or operating on) the base
#TXR
TXR
@(bind (f20 l20 ndig) @(let* ((str (tostring (expt 5 4 3 2))) (len (length str))) (list [str :..20] [str -20..:] len))) @(bind f20 "62060698786608744707") @(bind l20 "92256259918212890625") @(output) @f20...@l20 ndigits=@ndig @(end)
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 {\displaystyle 5^{4^{3^{2}}}} Confirm that the first and last twenty digits of the answer are: 62060698786608744707...92256259918212890625 Find and show the number of decimal digits in the answer. Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead. Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value. Related tasks   Long multiplication   Exponentiation order   exponentiation operator   Exponentiation with infix operators in (or operating on) the base
#Ursa
Ursa
import "unbounded_int" decl unbounded_int x x.set ((x.valueof 5).pow ((x.valueof 4).pow ((x.valueof 3).pow 2)))   decl string first last xstr set xstr (string x)   # get the first twenty digits decl int i for (set i 0) (< i 20) (inc i) set first (+ first xstr<i>) end for   # get the last twenty digits for (set i (- (size xstr) 20)) (< i (size xstr)) (inc i) set last (+ last xstr<i>) end for   out "the first and last digits of 5^(4^(3^2)) are " first "..." console out last " (the result was " (size xstr) " digits long)" endl endl console   if (and (and (= first "62060698786608744707") (= last "92256259918212890625")) (= (size xstr) 183231)) out "(pass)" endl console else out "FAIL" endl console end if
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 {\displaystyle 5^{4^{3^{2}}}} Confirm that the first and last twenty digits of the answer are: 62060698786608744707...92256259918212890625 Find and show the number of decimal digits in the answer. Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead. Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value. Related tasks   Long multiplication   Exponentiation order   exponentiation operator   Exponentiation with infix operators in (or operating on) the base
#Ursala
Ursala
#import std #import nat #import bcd   #show+   main = <.@ixtPX take/$20; ^|T/~& '...'--@x,'length: '--@h+ %nP+ length@t>@h %vP power=> <5_,4_,3_,2_>
http://rosettacode.org/wiki/Zeckendorf_number_representation
Zeckendorf number representation
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100. 10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution. Task Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. Also see   OEIS A014417   for the the sequence of required results.   Brown's Criterion - Numberphile Related task   Fibonacci sequence
#VBA
VBA
Private Function zeckendorf(ByVal n As Integer) As Integer Dim r As Integer: r = 0 Dim c As Integer Dim fib As New Collection fib.Add 1 fib.Add 1 Do While fib(fib.Count) < n fib.Add fib(fib.Count - 1) + fib(fib.Count) Loop For i = fib.Count To 2 Step -1 c = n >= fib(i) r = r + r - c n = n + c * fib(i) Next i zeckendorf = r End Function   Public Sub main() Dim i As Integer For i = 0 To 20 Debug.Print Format(i, "@@"); ":"; Format(WorksheetFunction.Dec2Bin(zeckendorf(i)), "@@@@@@@") Next i End Sub
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.
#Eero
Eero
  #import <Foundation/Foundation.h>   int main() square := 1, increment = 3   for int door in 1 .. 100 printf("door #%d", door)   if door == square puts(" is open.") square += increment increment += 2 else puts(" is closed.")   return 0  
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)
#LabVIEW
LabVIEW
  // Create a new array with length 0 {def myArray1 {A.new}} -> []   // Create an array with 2 members (length is 2) {def myArray2 {A.new Item1 Item2}} -> [Item1,Item2]   // Edit a value in an array {def myArray3 {A.new 1 2 3}} {A.set! 1 hello {myArray3}} -> [1,hello,3]   // Add a value at the head of an array {def myArray4 {A.new 1 2 3}}-> myArray4 {A.addfirst! hello {myArray4}} -> [hello,1,2,3]   // Add a value at the tail of an array {def myArray5 {A.new 1 2 3}} {A.addlast! hello {myArray5}} -> [1,2,3,hello]   and so on...  
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
#Phix
Phix
enum Colour, Nationality, Drink, Smoke, Pet constant Colours = {"red","white","green","yellow","blue"}, Nationalities = {"English","Swede","Dane","Norwegian","German"}, Drinks = {"tea","coffee","milk","beer","water"}, Smokes = {"Pall Mall","Dunhill","Blend","Blue Master","Prince"}, Pets = {"dog","birds","cats","horse","zebra"}, Sets = {Colours,Nationalities,Drinks,Smokes,Pets} constant tagset5 = tagset(5) -- {1,2,3,4,5}, oft-permuted sequence perm = repeat(tagset5,5) -- perm[1] is Colour of each house, etc function house(integer i, string name) return find(find(name,Sets[i]),perm[i]) end function function left_of(integer h1, integer h2) return (h1-h2)==1 end function function next_to(integer h1, integer h2) return abs(h1-h2)==1 end function procedure print_house(integer i) printf(1,"%d:%s,%s,%s,%s,%s\n",{i, Colours[perm[Colour][i]], Nationalities[perm[Nationality][i]], Drinks[perm[Drink][i]], Smokes[perm[Smoke][i]], Pets[perm[Pet][i]]}) end procedure integer solutions = 0 sequence solperms = {} atom t0 = time() constant factorial5 = factorial(5) for C=1 to factorial5 do perm[Colour] = permute(C,tagset5) if left_of(house(Colour,"green"),house(Colour,"white")) then for N=1 to factorial5 do perm[Nationality] = permute(N,tagset5) 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 do perm[Drink] = permute(D,tagset5) if house(Nationality,"Dane")==house(Drink,"tea") and house(Drink,"coffee")==house(Colour,"green") and house(Drink,"milk")==3 then for S=1 to factorial5 do perm[Smoke] = permute(S,tagset5) if house(Colour,"yellow")==house(Smoke,"Dunhill") and house(Nationality,"German")==house(Smoke,"Prince") and house(Smoke,"Blue Master")==house(Drink,"beer") and next_to(house(Drink,"water"),house(Smoke,"Blend")) then for P=1 to factorial5 do perm[Pet] = permute(P,tagset5) if house(Nationality,"Swede")==house(Pet,"dog") and house(Smoke,"Pall Mall")==house(Pet,"birds") and next_to(house(Smoke,"Blend"),house(Pet,"cats")) and next_to(house(Pet,"horse"),house(Smoke,"Dunhill")) then for i=1 to 5 do print_house(i) end for solutions += 1 solperms = append(solperms,perm) end if end for end if end for end if end for end if end for end if end for printf(1,"%d solution%s found (%3.3fs).\n",{solutions,iff(solutions>1,"s",""),time()-t0}) for i=1 to length(solperms) do perm = solperms[i] printf(1,"The %s owns the Zebra\n",{Nationalities[house(Pet,"zebra")]}) end for
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="health"> <item upc="123456789" stock="12"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item upc="445322344" stock="18"> <name>Levitation Salve</name> <price>23.99</price> <description>Levitate yourself for up to 3 hours per application</description> </item> </section> <section name="food"> <item upc="485672034" stock="653"> <name>Blork and Freen Instameal</name> <price>4.95</price> <description>A tasty meal in a tablet; just add water</description> </item> <item upc="132957764" stock="44"> <name>Grob winglets</name> <price>3.56</price> <description>Tender winglets of Grob. Just add water</description> </item> </section> </inventory>
#VBScript
VBScript
  Set objXMLDoc = CreateObject("msxml2.domdocument")   objXMLDoc.load("In.xml")   Set item_nodes = objXMLDoc.selectNodes("//item") i = 1 For Each item In item_nodes If i = 1 Then WScript.StdOut.Write item.xml WScript.StdOut.WriteBlankLines(2) Exit For End If Next   Set price_nodes = objXMLDoc.selectNodes("//price") list_price = "" For Each price In price_nodes list_price = list_price & price.text & ", " Next WScript.StdOut.Write list_price WScript.StdOut.WriteBlankLines(2)   Set name_nodes = objXMLDoc.selectNodes("//name") list_name = "" For Each name In name_nodes list_name = list_name & name.text & ", " Next WScript.StdOut.Write list_name WScript.StdOut.WriteBlankLines(2)  
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="health"> <item upc="123456789" stock="12"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item upc="445322344" stock="18"> <name>Levitation Salve</name> <price>23.99</price> <description>Levitate yourself for up to 3 hours per application</description> </item> </section> <section name="food"> <item upc="485672034" stock="653"> <name>Blork and Freen Instameal</name> <price>4.95</price> <description>A tasty meal in a tablet; just add water</description> </item> <item upc="132957764" stock="44"> <name>Grob winglets</name> <price>3.56</price> <description>Tender winglets of Grob. Just add water</description> </item> </section> </inventory>
#Visual_Basic_.NET
Visual Basic .NET
Dim first_item = xml.XPathSelectElement("//item") Console.WriteLine(first_item)   For Each price In xml.XPathSelectElements("//price") Console.WriteLine(price.Value) Next   Dim names = (From item In xml.XPathSelectElements("//name") Select item.Value).ToArray
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.
#Plain_English
Plain English
To run: Start up. Clear the screen to the gray color. Draw the Taijitu symbol 4 inches wide at the screen's center. Put the screen's center into a spot. Move the spot 4 inches right. Draw the Taijitu symbol 2 inches wide at the spot. Refresh the screen. Wait for the escape key. Shut down.   To draw the Taijitu symbol some twips wide at a spot: Imagine a box the twips high by the twips wide. Imagine an ellipse given the box. Center the ellipse on the spot. Mask outside the ellipse. Imagine a left half box with the screen's left and the screen's top and the spot's x coord and the screen's bottom. Fill the left half with the white color. Imagine a right half box with the spot's x coord and the screen's top and the screen's right and the screen's bottom. Fill the right half with the black color. Imagine a swirl ellipse given the box. Scale the swirl given 1/2. Put the spot into an upper spot. Move the upper spot up the twips divided by 4. Put the spot into a lower spot. Move the lower spot down the twips divided by 4. Fill the swirl on the upper spot with the white color. Fill the swirl on the lower spot with the black color. Put the swirl into a dot. Scale the dot given 1/4. Fill the dot on the lower spot with the white color. Fill the dot on the upper spot with the black color. Unmask everything. Use the fat pen. Draw the ellipse.
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.
#PL.2FI
PL/I
yinyang: procedure options(main); yinyang: procedure(r); circle: procedure(x, y, c, r) returns(bit); declare (x, y, c, r) fixed; return( r*r >= (x/2) * (x/2) + (y-c) * (y-c) ); end circle;   pixel: procedure(x, y, r) returns(char); declare (x, y, r) fixed; if circle(x, y, -r/2, r/6) then return('#'); if circle(x, y, r/2, r/6) then return('.'); if circle(x, y, -r/2, r/2) then return('.'); if circle(x, y, r/2, r/2) then return('#'); if circle(x, y, 0, r) then do; if x<0 then return('.'); else return('#'); end; return(' '); end pixel;   declare (x, y, r) fixed; do y=-r to r; do x=-2*r to 2*r; put edit(pixel(x, y, r)) (A(1)); end; put skip; end; end yinyang;   call yinyang(4); put skip; call yinyang(8); end yinyang;
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
#Groovy
Groovy
def Y = { le -> ({ f -> f(f) })({ f -> le { x -> f(f)(x) } }) }   def factorial = Y { fac -> { n -> n <= 2 ? n : n * fac(n - 1) } }   assert 2432902008176640000 == factorial(20G)   def fib = Y { fibStar -> { n -> n <= 1 ? n : fibStar(n - 1) + fibStar(n - 2) } }   assert fib(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
#JavaScript
JavaScript
function ZigZagMatrix(n) { this.height = n; this.width = n;   this.mtx = []; for (var i = 0; i < n; i++) this.mtx[i] = [];   var i=1, j=1; for (var e = 0; e < n*n; e++) { this.mtx[i-1][j-1] = e; if ((i + j) % 2 == 0) { // Even stripes if (j < n) j ++; else i += 2; if (i > 1) i --; } else { // Odd stripes if (i < n) i ++; else j += 2; if (j > 1) j --; } } } ZigZagMatrix.prototype = Matrix.prototype;   var z = new ZigZagMatrix(5); print(z); print();   z = new ZigZagMatrix(4); print(z);
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 {\displaystyle 5^{4^{3^{2}}}} Confirm that the first and last twenty digits of the answer are: 62060698786608744707...92256259918212890625 Find and show the number of decimal digits in the answer. Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead. Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value. Related tasks   Long multiplication   Exponentiation order   exponentiation operator   Exponentiation with infix operators in (or operating on) the base
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Console Imports BI = System.Numerics.BigInteger   Module Module1   Dim Implems() As String = {"Built-In", "Recursive", "Iterative"}, powers() As Integer = {5, 4, 3, 2}   Function intPowR(val As BI, exp As BI) As BI If exp = 0 Then Return 1 Dim ne As BI, vs As BI = val * val If exp.IsEven Then ne = exp >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) ne = (exp - 1) >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) * val End Function   Function intPowI(val As BI, exp As BI) As BI intPowI = 1 : While (exp > 0) : If Not exp.IsEven Then intPowI *= val val *= val : exp >>= 1 : End While End Function   Sub DoOne(title As String, p() As Integer) Dim st As DateTime = DateTime.Now, res As BI, resStr As String Select Case (Array.IndexOf(Implems, title)) Case 0 : res = BI.Pow(p(0), CInt(BI.Pow(p(1), CInt(BI.Pow(p(2), p(3)))))) Case 1 : res = intPowR(p(0), intPowR(p(1), intPowR(p(2), p(3)))) Case Else : res = intPowI(p(0), intPowI(p(1), intPowI(p(2), p(3)))) End Select : resStr = res.ToString() Dim et As TimeSpan = DateTime.Now - st Debug.Assert(resStr.Length = 183231) Debug.Assert(resStr.StartsWith("62060698786608744707")) Debug.Assert(resStr.EndsWith("92256259918212890625")) WriteLine("n = {0}", String.Join("^", powers)) WriteLine("n = {0}...{1}", resStr.Substring(0, 20), resStr.Substring(resStr.Length - 20, 20)) WriteLine("n digits = {0}", resStr.Length) WriteLine("{0} elasped: {1} milliseconds." & vblf, title, et.TotalMilliseconds) End Sub   Sub Main() For Each itm As String in Implems : DoOne(itm, powers) : Next If Debugger.IsAttached Then Console.ReadKey() End Sub   End Module
http://rosettacode.org/wiki/Zeckendorf_number_representation
Zeckendorf number representation
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100. 10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution. Task Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. Also see   OEIS A014417   for the the sequence of required results.   Brown's Criterion - Numberphile Related task   Fibonacci sequence
#VBScript
VBScript
  Function Zeckendorf(n) num = n Set fibonacci = CreateObject("System.Collections.Arraylist") fibonacci.Add 1 : fibonacci.Add 2 i = 1 Do While fibonacci(i) < num fibonacci.Add fibonacci(i) + fibonacci(i-1) i = i + 1 Loop tmp = "" For j = fibonacci.Count-1 To 0 Step -1 If fibonacci(j) <= num And (tmp = "" Or Left(tmp,1) <> "1") Then tmp = tmp & "1" num = num - fibonacci(j) Else tmp = tmp & "0" End If Next Zeckendorf = CLng(tmp) End Function   'testing the function For k = 0 To 20 WScript.StdOut.WriteLine k & ": " & Zeckendorf(k) Next  
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.
#Egel
Egel
  import "prelude.eg"   using System using List   data open, closed   def toggle = [ open N -> closed N | closed N -> open N ]   def doors = [ N -> map [ N -> closed N ] (fromto 1 N) ]   def toggleK = [ K nil -> nil | K (cons (D N) DD) -> let DOOR = if (N%K) == 0 then toggle (D N) else D N in cons DOOR (toggleK K DD) ]   def toggleEvery = [ nil DOORS -> DOORS | (cons K KK) DOORS -> toggleEvery KK (toggleK K DOORS) ]   def run = [ N -> toggleEvery (fromto 1 N) (doors N) ]   def main = run 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)
#Lambdatalk
Lambdatalk
  // Create a new array with length 0 {def myArray1 {A.new}} -> []   // Create an array with 2 members (length is 2) {def myArray2 {A.new Item1 Item2}} -> [Item1,Item2]   // Edit a value in an array {def myArray3 {A.new 1 2 3}} {A.set! 1 hello {myArray3}} -> [1,hello,3]   // Add a value at the head of an array {def myArray4 {A.new 1 2 3}}-> myArray4 {A.addfirst! hello {myArray4}} -> [hello,1,2,3]   // Add a value at the tail of an array {def myArray5 {A.new 1 2 3}} {A.addlast! hello {myArray5}} -> [1,2,3,hello]   and so on...  
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
#Picat
Picat
import cp.   main => Nat = [English, Swede, Dane, German, Norwegian], Color = [Red, Green, White, Yellow, Blue], Smoke = [PallMall, Dunhill, Blend, SBlue, Prince], Pet = [Dog, Bird, Cat, Horse, Zebra], Drink = [Tea, Coffee, Milk, Beer, Water],   Nat  :: 1..5, Color  :: 1..5, Smoke  :: 1..5, Pet  :: 1..5, Drink  :: 1..5,   all_different(Nat), all_different(Color), all_different(Smoke), all_different(Pet), all_different(Drink),   English = Red, Swede = Dog, Dane = Tea, Green #= White-1, Coffee = Green, Bird = PallMall, Yellow = Dunhill, Milk = 3, Norwegian = 1, abs(Blend-Cat) #= 1, abs(Dunhill-Horse) #= 1, SBlue = Beer, German = Prince, abs(Norwegian-Blue) #= 1, abs(Blend-Water) #= 1,   solve(Nat ++ Color ++ Smoke ++ Pet ++ Drink),   L = [English=english, Swede=swede, Dane=dane, German=german, Norwegian=norwegian].sort(), member(Zebra=ZebraOwner, L), writef("The %w owns the zebra\n", ZebraOwner), writeln(L).  
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="health"> <item upc="123456789" stock="12"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item upc="445322344" stock="18"> <name>Levitation Salve</name> <price>23.99</price> <description>Levitate yourself for up to 3 hours per application</description> </item> </section> <section name="food"> <item upc="485672034" stock="653"> <name>Blork and Freen Instameal</name> <price>4.95</price> <description>A tasty meal in a tablet; just add water</description> </item> <item upc="132957764" stock="44"> <name>Grob winglets</name> <price>3.56</price> <description>Tender winglets of Grob. Just add water</description> </item> </section> </inventory>
#Wren
Wren
import "/pattern" for Pattern   var doc = """ <inventory title="OmniCorp Store #45x10^3"> <section name="health"> <item upc="123456789" stock="12"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item upc="445322344" stock="18"> <name>Levitation Salve</name> <price>23.99</price> <description>Levitate yourself for up to 3 hours per application</description> </item> </section> <section name="food"> <item upc="485672034" stock="653"> <name>Blork and Freen Instameal</name> <price>4.95</price> <description>A tasty meal in a tablet; just add water</description> </item> <item upc="132957764" stock="44"> <name>Grob winglets</name> <price>3.56</price> <description>Tender winglets of Grob. Just add water</description> </item> </section> </inventory> """   var p1 = Pattern.new("<item ") var match1 = p1.find(doc) var p2 = Pattern.new("<//item>") var match2 = p2.find(doc) System.print("The first 'item' element is:") System.print(" " + doc[match1.index..match2.index + 6])   var p3 = Pattern.new("<price>[+1^<]<//price>") var matches = p3.findAll(doc) System.print("\nThe 'prices' are:") for (m in matches) System.print(m.captures[0].text)   var p4 = Pattern.new("<name>[+1^<]<//name>") var matches2 = p4.findAll(doc) var names = matches2.map { |m| m.captures[0].text }.toList System.print("\nThe 'names' are:") System.print(names.join("\n"))
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.
#PostScript
PostScript
%!PS-Adobe-3.0 %%BoundingBox: 0 0 400 400   /fs 10 def /ed { exch def } def /dist { 3 -1 roll sub dup mul 3 1 roll sub dup mul add sqrt } def /circ { /r exch def [r neg 1 r { /y exch def [ r 2 mul neg 1 r 2 mul { /x ed x 2 div y 0 0 dist r .05 add gt {( )}{ x 2 div y 0 r 2 div dist dup r 5 div le { pop (.) } { r 2 div le { (@) }{ x 2 div y 0 r 2 div neg dist dup r 5 div le { pop (@)} { r 2 div le {(.)}{ x 0 le {(.)}{(@)}ifelse } ifelse } ifelse } ifelse } ifelse } ifelse } for] } for] } def   /dis { moveto gsave { grestore 0 fs 1.15 mul neg rmoveto gsave {show} forall } forall grestore } def   /Courier findfont fs scalefont setfont   11 circ 10 390 dis 6 circ 220 180 dis showpage %%EOF
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
#Haskell
Haskell
newtype Mu a = Roll { unroll :: Mu a -> a }   fix :: (a -> a) -> a fix = g <*> (Roll . g) where g = (. (>>= id) unroll)   - this version is not in tail call position... -- fac :: Integer -> Integer -- fac = -- fix $ \f n -> if n <= 0 then 1 else n * f (n - 1)   -- this version builds a progression from tail call position and is more efficient... fac :: Integer -> Integer fac = (fix $ \f n i -> if i <= 0 then n else f (i * n) (i - 1)) 1   -- make fibs a function, else memory leak as -- head of the list can never be released as per: -- https://wiki.haskell.org/Memory_leak, type 1.1 -- overly complex version... {-- fibs :: () -> [Integer] fibs() = fix $ (0 :) . (1 :) . (fix (\f (x:xs) (y:ys) -> case x + y of n -> n `seq` n : f xs ys) <*> tail) --}   -- easier to read, simpler (faster) version... fibs :: () -> [Integer] fibs() = 0 : 1 : fix fibs_ 0 1 where fibs_ fnc f s = case f + s of n -> n `seq` n : fnc s n   main :: IO () main = mapM_ print [ map fac [1 .. 20] , take 20 $ fibs() ]
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
#Joy
Joy
  (* From the library. *) DEFINE reverse == [] swap shunt; shunt == [swons] step.   (* Split according to the parameter given. *) DEFINE take-drop == [dup] swap dup [[] cons [take swap] concat concat] dip [] cons concat [drop] concat.   (* Take the first of a list of lists. *) DEFINE take-first == [] cons 3 [dup] times [dup] swap concat [take [first] map swap dup] concat swap concat [drop swap] concat swap concat [take [rest] step []] concat swap concat [[cons] times swap concat 1 drop] concat.   DEFINE zigzag ==   (* Use take-drop to generate a list of lists. *) 4 [dup] times 1 swap from-to-list swap pred 1 swap from-to-list reverse concat swap dup * pred 0 swap from-to-list swap [take-drop i] step [pop list] [cons] while   (* The odd numbers must be modified with reverse. *) [dup size 2 div popd [1 =] [pop reverse] [pop] ifte] map   (* Take the first of the first of n lists. *) swap dup take-first [i] cons times pop   (* Merge the n separate lists. *) [] [pop list] [cons] while   (* And print them. *) swap dup * pred 'd 1 1 format size succ [] cons 'd swons [1 format putchars] concat [step '\n putch] cons step.   11 zigzag.
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 {\displaystyle 5^{4^{3^{2}}}} Confirm that the first and last twenty digits of the answer are: 62060698786608744707...92256259918212890625 Find and show the number of decimal digits in the answer. Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead. Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value. Related tasks   Long multiplication   Exponentiation order   exponentiation operator   Exponentiation with infix operators in (or operating on) the base
#Vlang
Vlang
import math.big import math   fn main() {   mut x := u32(math.pow(3,2)) x = u32(math.pow(4,x)) mut y := big.integer_from_int(5) y = y.pow(x) str := y.str() println("5^(4^(3^2)) has $str.len digits: ${str[..20]} ... ${str[str.len-20..]}") }
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 {\displaystyle 5^{4^{3^{2}}}} Confirm that the first and last twenty digits of the answer are: 62060698786608744707...92256259918212890625 Find and show the number of decimal digits in the answer. Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead. Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value. Related tasks   Long multiplication   Exponentiation order   exponentiation operator   Exponentiation with infix operators in (or operating on) the base
#Wren
Wren
import "/fmt" for Fmt import "/big" for BigInt   var p = BigInt.three.pow(BigInt.two) p = BigInt.four.pow(p) p = BigInt.five.pow(p) var s = p.toString Fmt.print("5 ^ 4 ^ 3 ^ 2 has $,d digits.\n", s.count) System.print("The first twenty are  : %(s[0..19])") System.print("and the last twenty are : %(s[-20..-1])")
http://rosettacode.org/wiki/Zeckendorf_number_representation
Zeckendorf number representation
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100. 10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution. Task Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. Also see   OEIS A014417   for the the sequence of required results.   Brown's Criterion - Numberphile Related task   Fibonacci sequence
#Vlang
Vlang
fn main() { for i := 0; i <= 20; i++ { println("${i:2} ${zeckendorf(i):7b}") } }   fn zeckendorf(n int) int { // initial arguments of fib0 = 1 and fib1 = 1 will produce // the Fibonacci sequence {1, 2, 3,..} on the stack as successive // values of fib1. _, set := zr(1, 1, n, 0) return set }   fn zr(fib0 int, fib1 int, n int, bit u32) (int, int) { mut set := 0 mut remaining := 0 if fib1 > n { return n, 0 } // recurse. // construct sequence on the way in, construct ZR on the way out. remaining, set = zr(fib1, fib0+fib1, n, bit+1) if fib1 <= remaining { set |= 1 << bit remaining -= fib1 } return remaining, set }
http://rosettacode.org/wiki/Zeckendorf_number_representation
Zeckendorf number representation
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100. 10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution. Task Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. Also see   OEIS A014417   for the the sequence of required results.   Brown's Criterion - Numberphile Related task   Fibonacci sequence
#Wren
Wren
import "/fmt" for Fmt   var LIMIT = 46 // to stay within range of signed 32 bit integer   var fibonacci = Fn.new { |n| if (n < 2 || n > LIMIT) Fiber.abort("n must be between 2 and %(LIMIT)") var fibs = List.filled(n, 1) for (i in 2...n) fibs[i] = fibs[i - 1] + fibs[i - 2] return fibs }   var fibs = fibonacci.call(LIMIT)   var zeckendorf = Fn.new { |n| if (n < 0) Fiber.abort("n must be non-negative") if (n < 2) return n.toString var lastFibIndex = 1 for (i in 2..LIMIT) { if (fibs[i] > n) { lastFibIndex = i - 1 break } } n = n - fibs[lastFibIndex] lastFibIndex = lastFibIndex - 1 var zr = "1" for (i in lastFibIndex..1) { if (fibs[i] <= n) { zr = zr + "1" n = n - fibs[i] } else { zr = zr + "0" } } return zr }   System.print(" n z") for (i in 0..20) Fmt.print("$2d : $s", i, zeckendorf.call(i))
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.
#EGL
EGL
  program OneHundredDoors   function main()   doors boolean[] = new boolean[100]; n int = 100;   for (i int from 1 to n) for (j int from i to n by i) doors[j] = !doors[j]; end end   for (i int from 1 to n) if (doors[i]) SysLib.writeStdout( "Door " + i + " is open" ); end end   end   end  
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#lang5
lang5
[] 1 append ['foo 'bar] append 2 reshape 0 remove 2 swap 2 compress collapse .
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
#PicoLisp
PicoLisp
(be match (@House @Person @Drink @Pet @Cigarettes) (permute (red blue green yellow white) @House) (left-of @House white @House green)   (permute (Norwegian English Swede German Dane) @Person) (has @Person English @House red) (equal @Person (Norwegian . @)) (next-to @Person Norwegian @House blue)   (permute (tea coffee milk beer water) @Drink) (has @Drink tea @Person Dane) (has @Drink coffee @House green) (equal @Drink (@ @ milk . @))   (permute (dog birds cats horse zebra) @Pet) (has @Pet dog @Person Swede)   (permute (Pall-Mall Dunhill Blend Blue-Master Prince) @Cigarettes) (has @Cigarettes Pall-Mall @Pet birds) (has @Cigarettes Dunhill @House yellow) (next-to @Cigarettes Blend @Pet cats) (next-to @Cigarettes Dunhill @Pet horse) (has @Cigarettes Blue-Master @Drink beer) (has @Cigarettes Prince @Person German)   (next-to @Drink water @Cigarettes Blend) )   (be has ((@A . @X) @A (@B . @Y) @B)) (be has ((@ . @X) @A (@ . @Y) @B) (has @X @A @Y @B) )   (be right-of ((@A . @X) @A (@ @B . @Y) @B)) (be right-of ((@ . @X) @A (@ . @Y) @B) (right-of @X @A @Y @B) )   (be left-of ((@ @A . @X) @A (@B . @Y) @B)) (be left-of ((@ . @X) @A (@ . @Y) @B) (left-of @X @A @Y @B) )   (be next-to (@X @A @Y @B) (right-of @X @A @Y @B)) (be next-to (@X @A @Y @B) (left-of @X @A @Y @B))
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="health"> <item upc="123456789" stock="12"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item upc="445322344" stock="18"> <name>Levitation Salve</name> <price>23.99</price> <description>Levitate yourself for up to 3 hours per application</description> </item> </section> <section name="food"> <item upc="485672034" stock="653"> <name>Blork and Freen Instameal</name> <price>4.95</price> <description>A tasty meal in a tablet; just add water</description> </item> <item upc="132957764" stock="44"> <name>Grob winglets</name> <price>3.56</price> <description>Tender winglets of Grob. Just add water</description> </item> </section> </inventory>
#XProc
XProc
<p:pipeline xmlns:p="http://www.w3.org/ns/xproc" name="one-two-three" version="1.0"> <p:identity> <p:input port="source"> <p:inline> <root> <first/> <prices/> <names/> </root> </p:inline> </p:input> </p:identity> <p:insert match="/root/first" position="first-child"> <p:input port="insertion" select="(//item)[1]"> <p:pipe port="source" step="one-two-three"/> </p:input> </p:insert> <p:insert match="/root/prices" position="first-child"> <p:input port="insertion" select="//price"> <p:pipe port="source" step="one-two-three"/> </p:input> </p:insert> <p:insert match="/root/names" position="first-child"> <p:input port="insertion" select="//name"> <p:pipe port="source" step="one-two-three"/> </p:input> </p:insert> </p:pipeline>
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="health"> <item upc="123456789" stock="12"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item upc="445322344" stock="18"> <name>Levitation Salve</name> <price>23.99</price> <description>Levitate yourself for up to 3 hours per application</description> </item> </section> <section name="food"> <item upc="485672034" stock="653"> <name>Blork and Freen Instameal</name> <price>4.95</price> <description>A tasty meal in a tablet; just add water</description> </item> <item upc="132957764" stock="44"> <name>Grob winglets</name> <price>3.56</price> <description>Tender winglets of Grob. Just add water</description> </item> </section> </inventory>
#XQuery
XQuery
(: 1. Retrieve the first "item" element Notice the braces around //item. This evaluates first all item elements and then retrieving the first one. Whithout the braces you get the first item for every section. :) let $firstItem := (//item)[1]   (: 2. Perform an action on each "price" element (print it out) :) let $price := //price/data(.)   (: 3. Get an array of all the "name" elements  :) let $names := //name   return <result> <firstItem>{$firstItem}</firstItem> <prices>{$price}</prices> <names>{$names}</names> </result>
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.
#POV-Ray
POV-Ray
  // ====== General Scene setup ====== #version 3.7; global_settings { assumed_gamma 2.2 }   camera{ location <0,2.7,4> look_at <0,.1,0> right x*1.6 aperture .2 focal_point <1,0,0> blur_samples 200 variance 1/10000 } light_source{<2,4,8>, 1 spotlight point_at 0 radius 10} sky_sphere {pigment {granite scale <1,.1,1> color_map {[0 rgb 1][1 rgb <0,.4,.6>]}}} #default {finish {diffuse .9 reflection {.1 metallic} ambient .3} normal {granite scale .2}} plane { y, -1 pigment {hexagon color rgb .7 color rgb .75 color rgb .65} normal {hexagon scale 5}}   // ====== Declare one side of the symbol as a sum and difference of discs ======   #declare yang = difference { merge { difference { cylinder {0 <0,.1,0> 1} // flat disk box {-1 <1,1,0>} // cut in half cylinder {<.5,-.1,0> <.5,.2,0> .5} // remove half-cicle on one side } cylinder {<-.5,0,0> <-.5,.1,0> .5} // add on the other side cylinder {<.5,0,0> <.5,.1,0> .15} // also add a little dot } cylinder {<-.5,-.1,0> <-.5,.2,0> .15} // and carve out a hole pigment{color rgb 0.1} }   // ====== The other side is white and 180-degree turned ======   #declare yin = object { yang rotate <0,180,0> pigment{color rgb 1} }   // ====== Here we put the two together: ======   #macro yinyang( ysize ) union { object {yin} object {yang} scale ysize } #end   // ====== Here we put one into a scene: ======   object { yinyang(1) translate -y*1.08 }   // ====== And a bunch more just for fun: ======   #declare scl=1.1; #while (scl > 0.01)   object { yinyang(scl) rotate <0,180,0> translate <-scl*4,scl*2-1,0> rotate <0,scl*360,0> translate <-.5,0,0>}   object { yinyang(scl) translate <-scl*4,scl*2-1,0> rotate <0,scl*360+180,0> translate <.5,0,0>}   #declare scl = scl*0.85; #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.
#Prolog
Prolog
ying_yang(N) :- R is N * 100, sformat(Title, 'Yin Yang ~w', [N]), new(W, window(Title)), new(Wh, colour(@default, 255*255, 255*255, 255*255)), new(Bl, colour(@default, 0, 0, 0)), CX is R + 50, CY is R + 50, R1 is R / 2, R2 is R / 8, CY1 is R1 + 50, CY2 is 3 * R1 + 50,   new(E, semi_disk(point(CX, CY), R, w, Bl)), new(F, semi_disk(point(CX, CY), R, e, Wh)), new(D1, disk(point(CX, CY1), R, Bl)), new(D2, disk(point(CX, CY2), R, Wh)), new(D3, disk(point(CX, CY1), R2, Wh)), new(D4, disk(point(CX, CY2), R2, Bl)),   send_list(W, display, [E, F, D1, D2, D3, D4]),   WD is 2 * R + 100, send(W, size, size(WD, WD )), send(W, open).   :- pce_begin_class(semi_disk, path, "Semi disk with color ").   initialise(P, C, R, O, Col) :-> send(P, send_super, initialise), get(C, x, CX), get(C, y, CY), choose(O, Deb, End), forall(between(Deb, End, I), ( X is R * cos(I * pi/180) + CX, Y is R * sin(I * pi/180) + CY, send(P, append, point(X,Y)))), send(P, closed, @on), send(P, fill_pattern, Col).   :- pce_end_class.   choose(s, 0, 180). choose(n, 180, 360). choose(w, 90, 270). choose(e, -90, 90).   :- pce_begin_class(disk, ellipse, "disk with color ").   initialise(P, C, R, Col) :-> send(P, send_super, initialise, R, R), send(P, center, C), send(P, pen, 0), send(P, fill_pattern, Col).   :- pce_end_class.
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
#J
J
Y=. '('':''<@;(1;~":0)<@;<@((":0)&;))'(2 : 0 '') (1 : (m,'u'))(1 : (m,'''u u`:6('',(5!:5<''u''),'')`:6 y'''))(1 :'u u`:6') )  
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
#jq
jq
# Create an m x n matrix def matrix(m; n; init): if m == 0 then [] elif m == 1 then [range(0;n)] | map(init) elif m > 0 then matrix(1;n;init) as $row | [range(0;m)] | map( $row ) else error("matrix\(m);_;_) invalid") end ;   # Print a matrix neatly, each cell occupying n spaces def neatly(n): def right: tostring | ( " " * (n-length) + .); . as $in | length as $length | reduce range (0;$length) as $i (""; . + reduce range(0;$length) as $j (""; "\(.) \($in[$i][$j] | right )" ) + "\n" ) ;  
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 {\displaystyle 5^{4^{3^{2}}}} Confirm that the first and last twenty digits of the answer are: 62060698786608744707...92256259918212890625 Find and show the number of decimal digits in the answer. Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead. Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value. Related tasks   Long multiplication   Exponentiation order   exponentiation operator   Exponentiation with infix operators in (or operating on) the base
#Zig
Zig
const std = @import("std"); const bigint = std.math.big.int.Managed;   pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = &gpa.allocator; defer _ = gpa.deinit();   var a = try bigint.initSet(allocator, 5); try a.pow(a.toConst(), try std.math.powi(u32, 4, try std.math.powi(u32, 3, 2))); defer a.deinit();   var as = try a.toString(allocator, 10, false); defer allocator.free(as);   std.debug.print("{s}...{s}\n", .{ as[0..20], as[as.len - 20 ..] }); std.debug.print("{} digits\n", .{as.len}); }
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 {\displaystyle 5^{4^{3^{2}}}} Confirm that the first and last twenty digits of the answer are: 62060698786608744707...92256259918212890625 Find and show the number of decimal digits in the answer. Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead. Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value. Related tasks   Long multiplication   Exponentiation order   exponentiation operator   Exponentiation with infix operators in (or operating on) the base
#zkl
zkl
var BN=Import("zklBigNum"); n:=BN(5).pow(BN(4).pow(BN(3).pow(2))); s:=n.toString(); "%,d".fmt(s.len()).println(); println(s[0,20],"...",s[-20,*]);
http://rosettacode.org/wiki/Zeckendorf_number_representation
Zeckendorf number representation
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100. 10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution. Task Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. Also see   OEIS A014417   for the the sequence of required results.   Brown's Criterion - Numberphile Related task   Fibonacci sequence
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations   proc Zeckendorf(N); \Display Zeckendorf number (N <= 20) int N; int Fib, LZ, I; [Fib:= [1, 2, 3, 5, 8, 13]; \Fibonacci sequence LZ:= true; \suppress leading zeros for I:= 5 downto 1 do [if N >= Fib(I) then [N:= N-Fib(I); ChOut(0, ^1); LZ:= false] else ChOut(0, if LZ then ^ else ^0); ]; ChOut(0, N+^0); \output final digit, which can be 0 ];   int N; [for N:= 0 to 20 do [if N<10 then ChOut(0,^ ); IntOut(0, N); Text(0, ": "); Zeckendorf(N); CrLf(0); ]; ]
http://rosettacode.org/wiki/Zeckendorf_number_representation
Zeckendorf number representation
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100. 10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution. Task Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. Also see   OEIS A014417   for the the sequence of required results.   Brown's Criterion - Numberphile Related task   Fibonacci sequence
#Yabasic
Yabasic
sub Zeckendorf(n) local i, n$, c   do n$ = bin$(i) if not instr(n$,"11") then print c,":\t",n$ if c = n break c = c + 1 end if i = i + 1 loop end sub   Zeckendorf(20)  
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.
#Eiffel
Eiffel
note description: "100 Doors problem" date: "08-JUL-2015" revision: "1.1"   class APPLICATION   create make   feature {NONE} -- Initialization   make -- Main application routine. do initialize_closed_doors toggle_doors output_door_states end   feature -- Access   doors: ARRAYED_LIST [DOOR] -- A set of doors (self-initialized to capacity of `max_door_count'). attribute create Result.make (max_door_count) end   feature -- Basic Operations   initialize_closed_doors -- Initialize all `doors'. do across min_door_count |..| max_door_count as ic_address_list loop doors.extend (create {DOOR}.make_closed (ic_address_list.item)) end ensure has_all_closed_doors: across doors as ic_doors_list all not ic_doors_list.item.is_open end end   toggle_doors -- Toggle all `doors'. do across min_door_count |..| max_door_count as ic_addresses_list loop across doors as ic_doors_list loop if is_door_to_toggle (ic_doors_list.item.address, ic_addresses_list.item) then ic_doors_list.item.toggle_door end end end end   output_door_states -- Output the state of all `doors'. do doors.do_all (agent door_state_out) end   feature -- Status Report   is_door_to_toggle (a_door_address, a_index_address: like {DOOR}.address): BOOLEAN -- Is the door at `a_door_address' needing to be toggled, when compared to `a_index_address'? do Result := a_door_address \\ a_index_address = 0 ensure only_modulus_zero: Result = (a_door_address \\ a_index_address = 0) end   feature -- Outputs   door_state_out (a_door: DOOR) -- Output the state of `a_door'. do print ("Door " + a_door.address.out + " is ") if a_door.is_open then print ("open.") else print ("closed.") end io.new_line end   feature {DOOR} -- Constants   min_door_count: INTEGER = 1 -- Minimum number of doors.   max_door_count: INTEGER = 100 -- Maximum number of doors.   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)
#langur
langur
var .a1 = [1, 2, 3, "abc"] val .a2 = series 4..10 val .a3 = .a1 ~ .a2   writeln "initial values ..." writeln ".a1: ", .a1 writeln ".a2: ", .a2 writeln ".a3: ", .a3 writeln()   .a1[4] = .a2[4] writeln "after setting .a1[4] = .a2[4] ..." writeln ".a1: ", .a1 writeln ".a2: ", .a2 writeln ".a3: ", .a3 writeln()   writeln ".a2[1]: ", .a2[1] writeln()   writeln "using index alternate ..." writeln ".a2[5; 0]: ", .a2[5; 0] writeln ".a2[10; 0]: ", .a2[10; 0] writeln()
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
#Prolog
Prolog
select([A|As],S):- select(A,S,S1),select(As,S1). select([],_).   next_to(A,B,C):- left_of(A,B,C) ; left_of(B,A,C). left_of(A,B,C):- append(_,[A,B|_],C).   zebra(Owns, HS):- % color,nation,pet,drink,smokes HS = [ h(_,norwegian,_,_,_), _, h(_,_,_,milk,_), _, _], select( [ h(red,englishman,_,_,_), h(_,swede,dog,_,_), h(_,dane,_,tea,_), h(_,german,_,_,prince) ], HS), select( [ h(_,_,birds,_,pallmall), h(yellow,_,_,_,dunhill), h(_,_,_,beer,bluemaster) ], HS), left_of( h(green,_,_,coffee,_), h(white,_,_,_,_), HS), next_to( h(_,_,_,_,dunhill), h(_,_,horse,_,_), HS), next_to( h(_,_,_,_,blend), h(_,_,cats, _,_), HS), next_to( h(_,_,_,_,blend), h(_,_,_,water,_), HS), next_to( h(_,norwegian,_,_,_), h(blue,_,_,_,_), HS), member( h(_,Owns,zebra,_,_), HS).   :- ?- time(( zebra(Who, HS), maplist(writeln,HS), nl, write(Who), nl, nl, fail ; write('No more solutions.') )).
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="health"> <item upc="123456789" stock="12"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item upc="445322344" stock="18"> <name>Levitation Salve</name> <price>23.99</price> <description>Levitate yourself for up to 3 hours per application</description> </item> </section> <section name="food"> <item upc="485672034" stock="653"> <name>Blork and Freen Instameal</name> <price>4.95</price> <description>A tasty meal in a tablet; just add water</description> </item> <item upc="132957764" stock="44"> <name>Grob winglets</name> <price>3.56</price> <description>Tender winglets of Grob. Just add water</description> </item> </section> </inventory>
#XSLT
XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" /> <xsl:template match="/">   <!-- 1. first item element --> <xsl:text> The first item element is</xsl:text> <xsl:value-of select="//item[1]" />   <!-- 2. Print each price element --> <xsl:text> The prices are: </xsl:text> <xsl:for-each select="//price"> <xsl:text> </xsl:text> <xsl:copy-of select="." /> </xsl:for-each>   <!-- 3. Collect all the name elements --> <xsl:text> The names are: </xsl:text> <xsl:copy-of select="//name" /> </xsl:template> </xsl:stylesheet>
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.
#Python
Python
import math def yinyang(n=3): radii = [i * n for i in (1, 3, 6)] ranges = [list(range(-r, r+1)) for r in radii] squares = [[ (x,y) for x in rnge for y in rnge] for rnge in ranges] circles = [[ (x,y) for x,y in sqrpoints if math.hypot(x,y) <= radius ] for sqrpoints, radius in zip(squares, radii)] m = {(x,y):' ' for x,y in squares[-1]} for x,y in circles[-1]: m[x,y] = '*' for x,y in circles[-1]: if x>0: m[(x,y)] = '·' for x,y in circles[-2]: m[(x,y+3*n)] = '*' m[(x,y-3*n)] = '·' for x,y in circles[-3]: m[(x,y+3*n)] = '·' m[(x,y-3*n)] = '*' return '\n'.join(''.join(m[(x,y)] for x in reversed(ranges[-1])) for y in ranges[-1])
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#Java_2
Java
import java.util.function.Function;   public interface YCombinator { interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { } public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) { RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x)); return r.apply(r); }   public static void main(String... arguments) { Function<Integer,Integer> fib = Y(f -> n -> (n <= 2) ? 1  : (f.apply(n - 1) + f.apply(n - 2)) ); Function<Integer,Integer> fac = Y(f -> n -> (n <= 1) ? 1  : (n * f.apply(n - 1)) );   System.out.println("fib(10) = " + fib.apply(10)); System.out.println("fac(10) = " + fac.apply(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
#Julia
Julia
function zigzag_matrix(n::Int) matrix = zeros(Int, n, n) x, y = 1, 1 for i = 0:(n*n-1) matrix[y,x] = i if (x + y) % 2 == 0 # Even stripes if x < n x += 1 y -= (y > 1) else y += 1 end else # Odd stripes if y < n x -= (x > 1) y += 1 else x += 1 end end end return matrix end
http://rosettacode.org/wiki/Zeckendorf_number_representation
Zeckendorf number representation
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100. 10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution. Task Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. Also see   OEIS A014417   for the the sequence of required results.   Brown's Criterion - Numberphile Related task   Fibonacci sequence
#zkl
zkl
// return powers (0|1) of fib sequence (1,2,3,5,8...) that sum to n fcn zeckendorf(n){ //-->String of 1s & 0s, no consecutive 1's if(n<=0) return("0"); fibs:=fcn(ab){ ab.append(ab.sum()).pop(0) }.fp(L(1,2)); (0).pump(*,List,fibs,'wrap(fib){ if(fib>n)Void.Stop else fib }) .reverse() .pump(String,fcn(fib,rn){ if(fib>rn.value)"0" else { rn.set(rn.value-fib); "1" } }.fp1(Ref(n))) }
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.
#Ela
Ela
open generic   type Door = Open | Closed deriving Show   gate [] _ = [] gate (x::xs) (y::ys) | x == y = Open :: gate xs ys | else = Closed :: gate xs ys   run n = gate [1..n] [& k*k \\ k <- [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)
#Lasso
Lasso
// Create a new empty array local(array1) = array   // Create an array with 2 members (#myarray->size is 2) local(array1) = array('ItemA','ItemB')   // Assign a value to member [2] #array1->get(2) = 5   // Retrieve a value from an array #array1->get(2) + #array1->size // 8   // Merge arrays local( array1 = array('a','b','c'), array2 = array('a','b','c') ) #array1->merge(#array2) // a, b, c, a, b, c   // Sort an array #array1->sort // a, a, b, b, c, c   // Remove value by index #array1->remove(2) // a, b, b, c, c   // Remove matching items #array1->removeall('b') // a, c, c   // Insert item #array1->insert('z') // a, c, c, z   // Insert item at specific position #array1->insert('0',1) // 0, a, c, c, z
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
#Python
Python
  from logpy import * from logpy.core import lall import time   def lefto(q, p, list): # give me q such that q is left of p in list # zip(list, list[1:]) gives a list of 2-tuples of neighboring combinations # which can then be pattern-matched against the query return membero((q,p), zip(list, list[1:]))   def nexto(q, p, list): # give me q such that q is next to p in list # match lefto(q, p) OR lefto(p, q) # requirement of vector args instead of tuples doesn't seem to be documented return conde([lefto(q, p, list)], [lefto(p, q, list)])   houses = var()   zebraRules = lall( # there are 5 houses (eq, (var(), var(), var(), var(), var()), houses), # the Englishman's house is red (membero, ('Englishman', var(), var(), var(), 'red'), houses), # the Swede has a dog (membero, ('Swede', var(), var(), 'dog', var()), houses), # the Dane drinks tea (membero, ('Dane', var(), 'tea', var(), var()), houses), # the Green house is left of the White house (lefto, (var(), var(), var(), var(), 'green'), (var(), var(), var(), var(), 'white'), houses), # coffee is the drink of the green house (membero, (var(), var(), 'coffee', var(), 'green'), houses), # the Pall Mall smoker has birds (membero, (var(), 'Pall Mall', var(), 'birds', var()), houses), # the yellow house smokes Dunhills (membero, (var(), 'Dunhill', var(), var(), 'yellow'), houses), # the middle house drinks milk (eq, (var(), var(), (var(), var(), 'milk', var(), var()), var(), var()), houses), # the Norwegian is the first house (eq, (('Norwegian', var(), var(), var(), var()), var(), var(), var(), var()), houses), # the Blend smoker is in the house next to the house with cats (nexto, (var(), 'Blend', var(), var(), var()), (var(), var(), var(), 'cats', var()), houses), # the Dunhill smoker is next to the house where they have a horse (nexto, (var(), 'Dunhill', var(), var(), var()), (var(), var(), var(), 'horse', var()), houses), # the Blue Master smoker drinks beer (membero, (var(), 'Blue Master', 'beer', var(), var()), houses), # the German smokes Prince (membero, ('German', 'Prince', var(), var(), var()), houses), # the Norwegian is next to the blue house (nexto, ('Norwegian', var(), var(), var(), var()), (var(), var(), var(), var(), 'blue'), houses), # the house next to the Blend smoker drinks water (nexto, (var(), 'Blend', var(), var(), var()), (var(), var(), 'water', var(), var()), houses), # one of the houses has a zebra--but whose? (membero, (var(), var(), var(), 'zebra', var()), houses) )   t0 = time.time() solutions = run(0, houses, zebraRules) t1 = time.time() dur = t1-t0   count = len(solutions) zebraOwner = [house for house in solutions[0] if 'zebra' in house][0][0]   print "%i solutions in %.2f seconds" % (count, dur) print "The %s is the owner of the zebra" % zebraOwner print "Here are all the houses:" for line in solutions[0]: print str(line)  
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.
#Quackery
Quackery
[ $ "turtleduck.qky" loadfile ] now!   [ -1 4 turn 2dup -v fly 1 4 turn 4 wide ' [ 0 0 0 ] colour ' [ 0 0 0 ] fill [ 2dup 2 1 v/ 1 2 arc 2dup -2 1 v/ 1 2 arc 2dup -v 1 2 arc ] 2dup -v 1 2 arc 1 4 turn 2dup 2 1 v/ fly ' [ 0 0 0 ] colour 1 wide ' [ 255 255 255 ] fill [ 2dup 7 1 v/ circle ] 2dup fly ' [ 255 255 255 ] colour ' [ 0 0 0 ] fill [ 2dup 7 1 v/ circle ] -2 1 v/ fly -1 4 turn ] is yinyang ( n/d --> )   turtle -110 1 fly 100 1 yinyang 420 1 fly 300 1 yinyang
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.
#R
R
plot.yin.yang <- function(x=5, y=5, r=3, s=10, add=F){ suppressMessages(require("plotrix")) if(!add) plot(1:10, type="n", xlim=c(0,s), ylim=c(0,s), xlab="", ylab="", xaxt="n", yaxt="n", bty="n", asp=1) draw.circle(x, y, r, border="white", col= "black") draw.ellipse(x, y, r, r, col="white", angle=0, segment=c(90,270), arc.only=F) draw.ellipse(x, y - r * 0.5, r * 0.5, r * 0.5, col="black", border="black", angle=0, segment=c(90,270), arc.only=F) draw.circle(x, y - r * 0.5, r * 0.125, border="white", col= "white") draw.circle(x, y + r * 0.5, r * 0.5, col="white", border="white") draw.circle(x, y + r * 0.5, r * 0.125, border="black", lty=1, col= "black") draw.circle(x, y, r, border="black") } png("yin_yang.png") plot.yin.yang() plot.yin.yang(1,7,1, add=T) dev.off()
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
#JavaScript
JavaScript
function Y(f) { var g = f((function(h) { return function() { var g = f(h(h)); return g.apply(this, arguments); } })(function(h) { return function() { var g = f(h(h)); return g.apply(this, arguments); } })); return g; }   var fac = Y(function(f) { return function (n) { return n > 1 ? n * f(n - 1) : 1; }; });   var fib = Y(function(f) { return function(n) { return n > 1 ? f(n - 1) + f(n - 2) : n; }; });
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 0 1 5 6 14 2 4 7 13 15 3 8 12 16 21 9 11 17 20 22 10 18 19 23 24 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Klingphix
Klingphix
include ..\Utilitys.tlhy     %Size 5 !Size 0 ( $Size dup ) dim   %i 1 !i %j 1 !j     $Size 2 power [ 1 - ( $i $j ) set $i $j + 1 band 0 == ( [$j $Size < ( [$j 1 + !j] [$i 2 + !i] ) if $i 1 > [ $i 1 - !i] if ] [$i $Size < ( [$i 1 + !i] [$j 2 + !j] ) if $j 1 > [ $j 1 - !j] if ] ) if ] for   $Size [  %row !row $Size [  %col !col ( $row $col ) get tostr 32 32 chain chain 1 3 slice print drop ] for nl ] for     nl "End " input
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.
#Elena
Elena
import system'routines; import extensions;   public program() { var Doors := Array.allocate(100).populate:(n=>false); for(int i := 0, i < 100, i := i + 1) { for(int j := i, j < 100, j := j + i + 1) { Doors[j] := Doors[j].Inverted } };   for(int i := 0, i < 100, i := i + 1) { console.printLine("Door #",i + 1," :",Doors[i].iif("Open","Closed")) };   console.readChar() }
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)
#Latitude
Latitude
;; Construct an array. foo := [1, 2, 3].   ;; Arrays can also be constructed explicitly. bar := Array clone. bar pushBack (1). bar pushBack (2). bar pushBack (3).   ;; Accessing values. println: foo nth (2). ;; 3   ;; Mutating values. foo nth (1) = 99. println: foo. ;; [1, 99, 3]   ;; Appending to either the front or the back of the array. foo pushBack ("back"). foo pushFront ("front"). println: foo. ;; ["front", 1, 99, 3, "back"]   ;; Popping from the front or back. println: foo popBack. ;; "back" println: foo popBack. ;; 3 println: foo popFront. ;; "front" println: foo. ;; [1, 99]
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
#R
R
    library(combinat)   col <- factor(c("Red","Green","White","Yellow","Blue")) own <- factor(c("English","Swedish","Danish","German","Norwegian")) pet <- factor(c("Dog","Birds","Cats","Horse","Zebra")) drink <- factor(c("Coffee","Tea","Milk","Beer","Water")) smoke <- factor(c("PallMall", "Blend", "Dunhill", "BlueMaster", "Prince"))   col_p <- permn(levels(col)) own_p <- permn(levels(own)) pet_p <- permn(levels(pet)) drink_p <- permn(levels(drink)) smoke_p <- permn(levels(smoke))   imright <- function(h1,h2){ return(h1-h2==1) }   nextto <- function(h1,h2){ return(abs(h1-h2)==1) }   house_with <- function(f,val){ return(which(levels(f)==val)) }   for (i in seq(length(col_p))){ col <- factor(col, levels=col_p[[i]])   if (imright(house_with(col,"Green"),house_with(col,"White"))) { for (j in seq(length(own_p))){ own <- factor(own, levels=own_p[[j]])   if(house_with(own,"English") == house_with(col,"Red")){ if(house_with(own,"Norwegian") == 1){ if(nextto(house_with(own,"Norwegian"),house_with(col,"Blue"))){ for(k in seq(length(drink_p))){ drink <- factor(drink, levels=drink_p[[k]])   if(house_with(drink,"Coffee") == house_with(col,"Green")){ if(house_with(own,"Danish") == house_with(drink,"Tea")){ if(house_with(drink,"Milk") == 3){ for(l in seq(length(smoke_p))){ smoke <- factor(smoke, levels=smoke_p[[l]])   if(house_with(smoke,"Dunhill") == house_with(col,"Yellow")){ if(house_with(smoke,"BlueMaster") == house_with(drink,"Beer")){ if(house_with(own,"German") == house_with(smoke,"Prince")){ if(nextto(house_with(smoke,"Blend"),house_with(drink,"Water"))){ for(m in seq(length(pet_p))){ pet <- factor(pet, levels=pet_p[[m]])   if(house_with(own,"Swedish") == house_with(pet,"Dog")){ if(house_with(smoke,"PallMall") == house_with(pet,"Birds")){ if(nextto(house_with(smoke,"Blend"),house_with(pet,"Cats"))){ if(nextto(house_with(smoke,"Dunhill"),house_with(pet,"Horse"))){ res <- sapply(list(own,col,pet,smoke,drink),levels) colnames(res) <- c("Nationality","Colour","Pet","Drink","Smoke") print(res) } } } } } } } } } } } } } } } } } } }   }
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.
#Racket
Racket
  #lang racket (require slideshow/pict)   (define (yin-yang d) (define base (hc-append (inset/clip (circle d) 0 0 (- (/ d 2)) 0) (inset/clip (disk d) (- (/ d 2)) 0 0 0))) (define with-top (ct-superimpose base (cc-superimpose (colorize (disk (/ d 2)) "white") (disk (/ d 8))))) (define with-bottom (cb-superimpose with-top (cc-superimpose (disk (/ d 2)) (colorize (disk (/ d 8)) "white")))) (cc-superimpose with-bottom (circle d)))   (yin-yang 200)  
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.
#Raku
Raku
sub circle ($rad, $cx, $cy, $fill = 'white', $stroke = 'black' ){ say "<circle cx='$cx' cy='$cy' r='$rad' fill='$fill' stroke='$stroke' stroke-width='1'/>"; }   sub yin_yang ($rad, $cx, $cy, :$fill = 'white', :$stroke = 'black', :$angle = 90) { my ($c, $w) = (1, 0); say "<g transform='rotate($angle, $cx, $cy)'>" if $angle; 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); say "</g>" if $angle; }   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 height="400" width="400" xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink">';   yin_yang(100, 130, 130); yin_yang(50, 300, 300);   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
#Joy
Joy
DEFINE y == [dup cons] swap concat dup cons i;   fac == [ [pop null] [pop succ] [[dup pred] dip i *] ifte ] 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
#Kotlin
Kotlin
// version 1.1.3   typealias Vector = IntArray typealias Matrix = Array<Vector>   fun zigzagMatrix(n: Int): Matrix { val result = Matrix(n) { Vector(n) } var down = false var count = 0 for (col in 0 until n) { if (down) for (row in 0..col) result[row][col - row] = count++ else for (row in col downTo 0) result[row][col - row] = count++ down = !down } for (row in 1 until n) { if (down) for (col in n - 1 downTo row) result[row + n - 1 - col][col] = count++ else for (col in row until n) result[row + n - 1 - col][col] = count++ down = !down } return result } fun printMatrix(m: Matrix) { for (i in 0 until m.size) { for (j in 0 until m.size) print("%2d ".format(m[i][j])) println() } println() }   fun main(args: Array<String>) { printMatrix(zigzagMatrix(5)) printMatrix(zigzagMatrix(10)) }