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/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>
#Nim
Nim
import sequtils, strutils   const LibXml = "libxml2.so"   type   XmlDocPtr = pointer   XmlXPathContextPtr = pointer   XmlElementKind = enum xmlElementNode = 1 xmlAttributeNode = 2 xmlTextNode = 3 xmlCdataSectionNode = 4 xmlEntityRefNode = 5 xmlEntityNode = 6 xmlPiNode = 7 xmlCommentNode = 8 xmlDocumentNode = 9 xmlDocumentTypeNode = 10 xmlDocumentFragNode = 11 xmlNotationNode = 12 xmlHtmlDocumentNode = 13 xmlDtdNode = 14 xmlElementDecl = 15 xmlAttributeDecl = 16 xmlEntityDecl = 17 xmlNamespaceDecl = 18 xmlXincludeStart = 19 xmlXincludeEnd = 20   XmlNsKind = XmlElementKind   XmlNsPtr = ptr XmlNs XmlNs = object next: XmlNsPtr kind: XmlNsKind href: cstring prefix: cstring private: pointer context: XmlDocPtr   XmlAttrPtr = pointer   XmlNodePtr = ptr XmlNode XmlNode = object private: pointer kind: XmlElementKind name: cstring children: XmlNodePtr last: XmlNodePtr parent: XmlNodePtr next: XmlNodePtr prev: XmlNodePtr doc: XmlDocPtr ns: XmlNsPtr content: cstring properties: XmlAttrPtr nsDef: XmlNsPtr psvi: pointer line: cushort extra: cushort   XmlNodeSetPtr = ptr XmlNodeSet XmlNodeSet = object nodeNr: cint nodeMax: cint nodeTab: ptr UncheckedArray[XmlNodePtr]   XmlPathObjectKind = enum xpathUndefined xpathNodeset xpathBoolean xpathNumber xpathString xpathPoint xpathRange xpathLocationset xpathUsers xpathXsltTree   XmlXPathObjectPtr = ptr XmlXPathObject XmlXPathObject = object kind: XmlPathObjectKind nodeSetVal: XmlNodeSetPtr boolVal: cint floatVal: cdouble stringVal: cstring user: pointer index: cint user2: pointer index2: cint   XmlSaveCtxtPtr = pointer   XmlBufferPtr = pointer     # Declaration of needed "libxml2" procedures. proc xmlParseFile(docName: cstring): XmlDocPtr {.cdecl, dynlib: LibXml, importc: "xmlParseFile".}   proc xmlXPathNewContext(doc: XmlDocPtr): XmlXPathContextPtr {.cdecl, dynlib: LibXml, importc: "xmlXPathNewContext".}   proc xmlXPathEvalExpression(str: cstring; ctxt: XmlXPathContextPtr): XmlXPathObjectPtr {.cdecl, dynlib: LibXml, importc: "xmlXPathEvalExpression".}   proc xmlXPathFreeContext(ctxt: XmlXPathContextPtr) {.cdecl, dynlib: LibXml, importc: "xmlXPathFreeContext".}   proc xmlXPathFreeObject(obj: XmlXPathObjectPtr) {.cdecl, dynlib: LibXml, importc: "xmlXPathFreeObject".}   proc xmlSaveToBuffer(vuffer: XmlBufferPtr; encoding: cstring; options: cint): XmlSaveCtxtPtr {.cdecl, dynlib: LibXml, importc: "xmlSaveToBuffer".}   proc xmlBufferCreate(): XmlBufferPtr {.cdecl, dynlib: LibXml, importc: "xmlBufferCreate".}   proc xmlBufferFree(buf: XmlBufferPtr) {.cdecl, dynlib: LibXml, importc: "xmlBufferCreate".}   proc xmlBufferContent(buf: XmlBufferPtr): cstring {.cdecl, dynlib: LibXml, importc: "xmlBufferContent".}   proc xmlSaveTree(ctxt: XmlSaveCtxtPtr; cur: XmlNodePtr): clong {.cdecl, dynlib: LibXml, importc: "xmlSaveTree".}   proc xmlSaveClose(ctxt: XmlSaveCtxtPtr) {.cdecl, dynlib: LibXml, importc: "xmlSaveClose".}     proc `$`(node: XmlNodePtr): string = ## Return the representation of a node. let buffer = xmlBufferCreate() let saveContext = xmlSaveToBuffer(buffer, nil, 0) discard saveContext.xmlSaveTree(node) saveContext.xmlSaveClose() result = $buffer.xmlBufferContent() xmlBufferFree(buffer)     iterator nodes(xpath: string; context: XmlXPathContextPtr): XmlNodePtr = ## Yield the nodes which fit the XPath request. let xpathObj = xmlXPathEvalExpression(xpath, context) if xpathObj.isNil: quit "Failed to evaluate XPath: " & xpath, QuitFailure assert xpathObj.kind == xpathNodeset let nodeSet = xpathObj.nodeSetVal if not nodeSet.isNil: for i in 0..<nodeSet.nodeNr: yield nodeSet.nodeTab[i] xmlXPathFreeObject(xpathObj)     # Load and parse XML file. let doc = xmlParseFile("xpath_test.xml") if doc.isNil: quit "Unable to load and parse document", QuitFailure   # Create an XPath context. let context = xmlXPathNewContext(doc) if context.isNil: quit "Failed to create XPath context", QuitFailure   var xpath = "//section[1]/item[1]" echo "Request $#:".format(xpath) for node in nodes(xpath, context): echo node echo()   xpath = "//price/text()" echo "Request $#:".format(xpath) for node in nodes(xpath, context): echo node.content echo()   xpath = "//name" echo "Request $#:".format(xpath) let names = toSeq(nodes(xpath, context)).mapIt(it.children.content) echo names   xmlXPathFreeContext(context)
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>
#Objeck
Objeck
  use XML;   bundle Default { class Test { function : Main(args : String[]) ~ Nil { in := String->New(); in->Append("<inventory title=\"OmniCorp Store #45x10^3\">"); in->Append("<section name=\"health\">"); in->Append("<item upc=\"123456789\" stock=\"12\">"); in->Append("<name>Invisibility Cream</name>"); in->Append("<price>14.50</price>"); in->Append("<description>Makes you invisible</description>"); in->Append("</item>"); in->Append("<item upc=\"445322344\" stock=\"18\">"); in->Append("<name>Levitation Salve</name>"); in->Append("<price>23.99</price>"); in->Append("<description>Levitate yourself for up to 3 hours per application</description>"); in->Append("</item>"); in->Append("</section>"); in->Append("<section name=\"food\">"); in->Append("<item upc=\"485672034\" stock=\"653\">"); in->Append("<name>Blork and Freen Instameal</name>"); in->Append("<price>4.95</price>"); in->Append("<description>A tasty meal in a tablet; just add water</description>"); in->Append("</item>"); in->Append("<item upc=\"132957764\" stock=\"44\">"); in->Append("<name>Grob winglets</name>"); in->Append("<price>3.56</price>"); in->Append("<description>Tender winglets of Grob. Just add water</description>"); in->Append("</item>"); in->Append("</section>"); in->Append("</inventory>");   parser := XmlParser->New(in); if(parser->Parse()) { # get first item results := parser->FindElements("//inventory/section[1]/item[1]"); if(results <> Nil) { IO.Console->Instance()->Print("items: ")->PrintLine(results->Size()); }; # get all prices results := parser->FindElements("//inventory/section/item/price"); if(results <> Nil) { each(i : results) { element := results->Get(i)->As(XMLElement); element->GetContent()->PrintLine(); }; }; # get names results := parser->FindElements("//inventory/section/item/name"); if(results <> Nil) { IO.Console->Instance()->Print("names: ")->PrintLine(results->Size()); }; }; } } }  
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.
#Logo
Logo
to taijitu :r  ; Draw a classic Taoist taijitu of the given radius centered on the current  ; turtle position. The "eyes" are placed along the turtle's heading, the  ; filled one in front, the open one behind.    ; don't bother doing anything if the pen is not down if not pendown? [stop]    ; useful derivative values localmake "r2 (ashift :r -1) localmake "r4 (ashift :r2 -1) localmake "r8 (ashift :r4 -1)    ; remember where we started localmake "start pos    ; draw outer circle pendown arc 360 :r    ; draw upper half of S penup forward :r2 pendown arc 180 :r2    ; and filled inner eye arc 360 :r8 fill    ; draw lower half of S penup back :r pendown arc -180 :r2    ; other inner eye arc 360 :r8    ; fill this half of the symbol penup forward :r4 fill    ; put the turtle back where it started setpos :start pendown end   ; demo code to produce image at right clearscreen pendown hideturtle taijitu 100 penup forward 150 left 90 forward 150 pendown taijitu 75
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.
#Lua
Lua
function circle(x, y, c, r) return (r * r) >= (x * x) / 4 + ((y - c) * (y - c)) end   function pixel(x, y, r) if circle(x, y, -r / 2, r / 6) then return '#' end if circle(x, y, r / 2, r / 6) then return '.' end if circle(x, y, -r / 2, r / 2) then return '.' end if circle(x, y, r / 2, r / 2) then return '#' end if circle(x, y, 0, r) then if x < 0 then return '.' else return '#' end end return ' ' end   function yinYang(r) for y=-r,r do for x=-2*r,2*r do io.write(pixel(x, y, r)) end print() end end   yinYang(18)
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
#Elixir
Elixir
  iex(1)> yc = fn f -> (fn x -> x.(x) end).(fn y -> f.(fn arg -> y.(y).(arg) end) end) end #Function<6.90072148/1 in :erl_eval.expr/5> iex(2)> fac = fn f -> fn n -> if n < 2 do 1 else n * f.(n-1) end end end #Function<6.90072148/1 in :erl_eval.expr/5> iex(3)> for i <- 0..9, do: yc.(fac).(i) [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] iex(4)> fib = fn f -> fn n -> if n == 0 do 0 else (if n == 1 do 1 else f.(n-1) + f.(n-2) end) end end end #Function<6.90072148/1 in :erl_eval.expr/5> iex(5)> for i <- 0..9, do: yc.(fib).(i) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]  
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 0 1 5 6 14 2 4 7 13 15 3 8 12 16 21 9 11 17 20 22 10 18 19 23 24 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Forth
Forth
0 value diag   : south diag abs + cell+ ;   ' cell+ value zig ' south value zag   : init ( n -- ) 1- cells negate to diag ['] cell+ to zig ['] south to zag ;   : swap-diag zig zag to zig to zag ;   : put ( n addr -- n+1 addr ) 2dup ! swap 1+ swap ;   : turn ( addr -- addr+E/S ) zig execute swap-diag diag negate to diag ;   : zigzag ( matrix n -- ) { n } n init 0 swap n 1 ?do put turn i 0 do put diag + loop loop swap-diag n 1 ?do put turn n i 1+ ?do put diag + loop loop  ! ;   : .matrix ( n matrix -- ) over 0 do cr over 0 do dup @ 3 .r cell+ loop loop 2drop ;   : test ( n -- ) here over zigzag here .matrix ; 5 test 0 1 5 6 14 2 4 7 13 15 3 8 12 16 21 9 11 17 20 22 10 18 19 23 24 ok
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
#Python
Python
>>> y = str( 5**4**3**2 ) >>> print ("5**4**3**2 = %s...%s and has %i digits" % (y[:20], y[-20:], len(y))) 5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits
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
#Quackery
Quackery
> quackery Welcome to Quackery. Enter "leave" to leave the shell. /O> 5 4 3 2 ** ** ** ... number$ dup 20 split swap echo$ ... say "..." -20 split echo$ drop cr ... size echo say " digits" cr ... 62060698786608744707...92256259918212890625 183231 digits Stack empty. /O>
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
#REXX
REXX
  /* REXX *************************************************************** * 11.10.2012 Walter Pachl **********************************************************************/ fib='13 8 5 3 2 1' Do i=6 To 1 By -1 /* Prepare Fibonacci Numbers */ Parse Var fib f.i fib /* f.1 ... f.7 */ End Do n=0 To 20 /* for all numbers in the task */ m=n /* copy of number */ r='' /* result for n */ Do i=6 To 1 By -1 /* loop through numbers */ If m>=f.i Then Do /* f.i must be used */ r=r||1 /* 1 into result */ m=m-f.i /* subtract */ End Else /* f.i is larger than the rest */ r=r||0 /* 0 into result */ End r=strip(r,'L','0') /* strip leading zeros */ If r='' Then r='0' /* take care of 0 */ Say right(n,2)': 'right(r,6) /* show result */ End
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.
#DUP
DUP
100[$][0^:1-]# {initialize doors} % [s;[$101<][$$;~\:s;+]#%]d: {function d, switch door state function} 1s:[s;101<][d;!s;1+s:]# {increment step width from 1 to 100, execute function d each time} 1[$101<][$$.' ,;['o,'p,'e,'n,10,]['c,'l,'o,'s,'e,'d,10,]?1+]# {loop through doors, print door number and state}
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#i
i
main //Fixed-length arrays. f $= array.integer[1]() f[0] $= 2 print(f[0])   //Dynamic arrays. d $= list.integer() d[+] $= 2 print(d[1]) }
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
#smart_BASIC
smart BASIC
PRINT 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
#SNOBOL4
SNOBOL4
OUTPUT = (0 ** 0) END
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
#SQL
SQL
  SQL> SELECT POWER(0,0) FROM dual;  
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
#Julia
Julia
  # Julia 1.0 using Combinatorics function make(str, test ) filter(test, collect( permutations(split(str))) ) end   men = make("danish english german norwegian swedish", x -> "norwegian" == x[1])   drinks = make("beer coffee milk tea water", x -> "milk" == x[3])   #Julia 1.0 compatible colors = make("blue green red white yellow", x -> 1 == findfirst(c -> c == "white", x) - findfirst(c -> c == "green",x))   pets = make("birds cats dog horse zebra")   smokes = make("blend blue-master dunhill pall-mall prince")   function eq(x, xs, y, ys) findfirst(xs, x) == findfirst(ys, y) end   function adj(x, xs, y, ys) 1 == abs(findfirst(xs, x) - findfirst(ys, y)) end   function print_houses(n, pet, nationality, colors, drink, smokes) println("$n, $pet, $nationality $colors $drink $smokes") end   for m = men, c = colors if eq("red",c, "english",m) && adj("norwegian",m, "blue",c) for d = drinks if eq("danish",m, "tea",d) && eq("coffee",d,"green",c) for s = smokes if eq("yellow",c,"dunhill",s) && eq("blue-master",s,"beer",d) && eq("german",m,"prince",s) for p = pets if eq("birds",p,"pall-mall",s) && eq("swedish",m,"dog",p) && adj("blend",s,"cats",p) && adj("horse",p,"dunhill",s) println("Zebra is owned by ", m[findfirst(c -> c == "zebra", p)]) println("Houses:") for house_num in 1:5 print_houses(house_num,p[house_num],m[house_num],c[house_num],d[house_num],s[house_num]) end end end end end end end end end    
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>
#Oz
Oz
declare [XMLParser] = {Module.link ['x-oz://system/xml/Parser.ozf']}   proc {Main Data} Parser = {New XMLParser.parser init} [Doc] = {Parser parseVS(Data $)}   FirstItem = {XPath Doc [inventory section item]}.1   Prices = {XPath Doc [inventory section item price Text]}   Names = {XPath Doc [inventory section item name]} in {ForAll Prices System.showInfo} end   %% %% Emulation of some XPath functionality: %%   fun {XPath Doc Path} P|Pr = Path in Doc.name = P %% assert {FoldL Pr XPathStep [Doc]} end   fun {XPathStep Elements P} if {IsProcedure P} then {Map Elements P} else {FilteredChildren Elements P} end end   %% A flat list of all Type-children of all Elements. fun {FilteredChildren Elements Type} {Flatten {Map Elements fun {$ E} {Filter E.children fun {$ X} case X of element(name:!Type ...) then true else false end end} end}} end   %% PCDATA of an element as a ByteString fun {Text Element} Texts = for Child in Element.children collect:C do case Child of text(data:BS ...) then {C BS} end end in {FoldR Texts ByteString.append {ByteString.make nil}} end   Data = "<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>" in {Main Data}
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.
#Maple
Maple
  with(plottools): with(plots): yingyang := r -> display( circle([0, 0], r), disk([0, 1/2*r], 1/10*r, colour = black), disk([0, -1/2*r], 1/10*r, colour = white), disk([0, -1/2*r], 1/2*r, colour = black), inequal({1/4*r^2 <= x^2 + (y - 1/2*r)^2, 1/4*r^2 <= x^2 + (y + 1/2*r)^2, x^2 + y^2 <= r^2}, x = 0 .. r, y = -r .. r, grid = [100, 100], colour = black), scaling = constrained, axes = none );  
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
#Elm
Elm
module Main exposing ( main )   import Html exposing ( Html, text )   -- As with most of the strict (non-deferred or non-lazy) languages, -- this is the Z-combinator with the additional value parameter...   -- wrap type conversion to avoid recursive type definition... type Mu a b = Roll (Mu a b -> a -> b)   unroll : Mu a b -> (Mu a b -> a -> b) -- unwrap it... unroll (Roll x) = x   -- note lack of beta reduction using values... fixz : ((a -> b) -> (a -> b)) -> (a -> b) fixz f = let g r = f (\ v -> unroll r r v) in g (Roll g)   facz : Int -> Int -- facz = fixz <| \ f n -> if n < 2 then 1 else n * f (n - 1) -- inefficient recursion facz = fixz (\ f n i -> if i < 2 then n else f (i * n) (i - 1)) 1 -- efficient tailcall   fibz : Int -> Int -- fibz = fixz <| \ f n -> if n < 2 then n else f (n - 1) + f (n - 2) -- inefficient recursion fibz = fixz (\ fn f s i -> if i < 2 then f else fn s (f + s) (i - 1)) 1 1 -- efficient tailcall   -- by injecting laziness, we can get the true Y-combinator... -- as this includes laziness, there is no need for the type wrapper! fixy : ((() -> a) -> a) -> a fixy f = f <| \ () -> fixy f -- direct function recursion -- the above is not value recursion but function recursion! -- fixv f = let x = f x in x -- not allowed by task or by Elm! -- we can make Elm allow it by injecting laziness... -- fixv f = let x = f () x in x -- but now value recursion not function recursion   facy : Int -> Int -- facy = fixy <| \ f n -> if n < 2 then 1 else n * f () (n - 1) -- inefficient recursion facy = fixy (\ f n i -> if i < 2 then n else f () (i * n) (i - 1)) 1 -- efficient tailcall   fiby : Int -> Int -- fiby = fixy <| \ f n -> if n < 2 then n else f () (n - 1) + f (n - 2) -- inefficient recursion fiby = fixy (\ fn f s i -> if i < 2 then f else fn () s (f + s) (i - 1)) 1 1 -- efficient tailcall   -- something that can be done with a true Y-Combinator that -- can't be done with the Z combinator... -- given an infinite Co-Inductive Stream (CIS) defined as... type CIS a = CIS a (() -> CIS a) -- infinite lazy stream!   mapCIS : (a -> b) -> CIS a -> CIS b -- uses function to map mapCIS cf cis = let mp (CIS head restf) = CIS (cf head) <| \ () -> mp (restf()) in mp cis   -- now we can define a Fibonacci stream as follows... fibs : () -> CIS Int fibs() = -- two recursive fix's, second already lazy... let fibsgen = fixy (\ fn (CIS (f, s) restf) -> CIS (s, f + s) (\ () -> fn () (restf()))) in fixy (\ cisthnk -> fibsgen (CIS (0, 1) cisthnk)) |> mapCIS (\ (v, _) -> v)   nCISs2String : Int -> CIS a -> String -- convert n CIS's to String nCISs2String n cis = let loop i (CIS head restf) rslt = if i <= 0 then rslt ++ " )" else loop (i - 1) (restf()) (rslt ++ " " ++ Debug.toString head) in loop n cis "("   -- unfortunately, if we need CIS memoization so as -- to make a true lazy list, Elm doesn't support it!!!   main : Html Never main = String.fromInt (facz 10) ++ " " ++ String.fromInt (fibz 10) ++ " " ++ String.fromInt (facy 10) ++ " " ++ String.fromInt (fiby 10) ++ " " ++ nCISs2String 20 (fibs()) |> text
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
#Fortran
Fortran
PROGRAM ZIGZAG   IMPLICIT NONE INTEGER, PARAMETER :: size = 5 INTEGER :: zzarray(size,size), x(size*size), y(size*size), i, j   ! index arrays x = (/ ((j, i = 1, size), j = 1, size) /) y = (/ ((i, i = 1, size), j = 1, size) /)   ! Sort indices DO i = 2, size*size j = i - 1 DO WHILE (j>=1 .AND. (x(j)+y(j)) > (x(i)+y(i))) j = j - 1 END DO x(j+1:i) = cshift(x(j+1:i),-1) y(j+1:i) = cshift(y(j+1:i),-1) END DO   ! Create zig zag array DO i = 1, size*size IF (MOD(x(i)+y(i), 2) == 0) THEN zzarray(x(i),y(i)) = i - 1 ELSE zzarray(y(i),x(i)) = i - 1 END IF END DO   ! Print zig zag array DO j = 1, size DO i = 1, size WRITE(*, "(I5)", ADVANCE="NO") zzarray(i,j) END DO WRITE(*,*) END DO   END PROGRAM ZIGZAG
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
#R
R
library(gmp) large <- pow.bigz(5, pow.bigz(4, pow.bigz(3, 2))) largestr <- as.character(large) cat("first 20 digits:", substr(largestr, 1, 20), "\n", "last 20 digits:", substr(largestr, nchar(largestr) - 19, nchar(largestr)), "\n", "number of digits: ", nchar(largestr), "\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
#Racket
Racket
#lang racket   (define answer (number->string (foldr expt 1 '(5 4 3 2)))) (define len (string-length answer))   (printf "Got ~a digits~n" len) (printf "~a ... ~a~n" (substring answer 0 20) (substring answer (- len 20) len))  
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
#Ring
Ring
  # Project : Zeckendorf number representation   see "0 0" + nl for n = 1 to 20 see "" + n + " " + zeckendorf(n) + nl next   func zeckendorf(n) fib = list(45) fib[1] = 1 fib[2] = 1 i = 2 o = "" while fib[i] <= n i = i + 1 fib[i] = fib[i-1] + fib[i-2] end while i != 2 i = i - 1 if n >= fib[i] o = o + "1" n = n - fib[i] else o = o + "0" ok end return o  
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
#Ruby
Ruby
def zeckendorf return to_enum(__method__) unless block_given? x = 0 loop do bin = x.to_s(2) yield bin unless bin.include?("11") x += 1 end end   zeckendorf.take(21).each_with_index{|x,i| puts "%3d: %8s"% [i, x]}
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.
#DWScript
DWScript
var doors : array [1..100] of Boolean; var i, j : Integer;   for i := 1 to 100 do for j := i to 100 do if (j mod i) = 0 then doors[j] := not doors[j];F   for i := 1 to 100 do if doors[i] then PrintLn('Door '+IntToStr(i)+' 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)
#Io
Io
foo := list("foo", "bar", "baz") foo at(1) println // bar foo append("Foobarbaz") foo println foo atPut(2, "barbaz") // baz becomes barbaz
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
#Standard_ML
Standard ML
- Math.pow (0.0, 0.0); val it = 1.0 : real
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
#Stata
Stata
. display 0^0 1
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
#Swift
Swift
import Darwin print(pow(0.0,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
#Kotlin
Kotlin
// version 1.1.3   fun nextPerm(perm: IntArray): Boolean { val size = perm.size var k = -1 for (i in size - 2 downTo 0) { if (perm[i] < perm[i + 1]) { k = i break } } if (k == -1) return false // last permutation for (l in size - 1 downTo k) { if (perm[k] < perm[l]) { val temp = perm[k] perm[k] = perm[l] perm[l] = temp var m = k + 1 var n = size - 1 while (m < n) { val temp2 = perm[m] perm[m++] = perm[n] perm[n--] = temp2 } break } } return true }   fun check(a1: Int, a2: Int, v1: Int, v2: Int): Boolean { for (i in 0..4) if (p[a1][i] == v1) return p[a2][i] == v2 return false }   fun checkLeft(a1: Int, a2: Int, v1: Int, v2: Int): Boolean { for (i in 0..3) if (p[a1][i] == v1) return p[a2][i + 1] == v2 return false }   fun checkRight(a1: Int, a2: Int, v1: Int, v2: Int): Boolean { for (i in 1..4) if (p[a1][i] == v1) return p[a2][i - 1] == v2 return false }   fun checkAdjacent(a1: Int, a2: Int, v1: Int, v2: Int): Boolean { return checkLeft(a1, a2, v1, v2) || checkRight(a1, a2, v1, v2) }   val colors = listOf("Red", "Green", "White", "Yellow", "Blue") val nations = listOf("English", "Swede", "Danish", "Norwegian", "German") val animals = listOf("Dog", "Birds", "Cats", "Horse", "Zebra") val drinks = listOf("Tea", "Coffee", "Milk", "Beer", "Water") val smokes = listOf("Pall Mall", "Dunhill", "Blend", "Blue Master", "Prince")   val p = Array(120) { IntArray(5) { -1 } } // stores all permutations of numbers 0..4   fun fillHouses(): Int { var solutions = 0 for (c in 0..119) { if (!checkLeft(c, c, 1, 2)) continue // C5 : Green left of white for (n in 0..119) { if (p[n][0] != 3) continue // C10: Norwegian in First if (!check(n, c, 0, 0)) continue // C2 : English in Red if (!checkAdjacent(n, c, 3, 4)) continue // C15: Norwegian next to Blue for (a in 0..119) { if (!check(a, n, 0, 1)) continue // C3 : Swede has Dog for (d in 0..119) { if (p[d][2] != 2) continue // C9 : Middle drinks Milk if (!check(d, n, 0, 2)) continue // C4 : Dane drinks Tea if (!check(d, c, 1, 1)) continue // C6 : Green drinks Coffee for (s in 0..119) { if (!check(s, a, 0, 1)) continue // C7 : Pall Mall has Birds if (!check(s, c, 1, 3)) continue // C8 : Yellow smokes Dunhill if (!check(s, d, 3, 3)) continue // C13: Blue Master drinks Beer if (!check(s, n, 4, 4)) continue // C14: German smokes Prince if (!checkAdjacent(s, a, 2, 2)) continue // C11: Blend next to Cats if (!checkAdjacent(s, a, 1, 3)) continue // C12: Dunhill next to Horse if (!checkAdjacent(s, d, 2, 4)) continue // C16: Blend next to Water solutions++ printHouses(c, n, a, d, s) } } } } } return solutions }   fun printHouses(c: Int, n: Int, a: Int, d: Int, s: Int) { var owner: String = "" println("House Color Nation Animal Drink Smokes") println("===== ====== ========= ====== ====== ===========") for (i in 0..4) { val f = "%3d  %-6s  %-9s  %-6s  %-6s  %-11s\n" System.out.printf(f, i + 1, colors[p[c][i]], nations[p[n][i]], animals[p[a][i]], drinks[p[d][i]], smokes[p[s][i]]) if (animals[p[a][i]] == "Zebra") owner = nations[p[n][i]] } println("\nThe $owner owns the Zebra\n") }   fun main(args: Array<String>) { val perm = IntArray(5) { it } for (i in 0..119) { for (j in 0..4) p[i][j] = perm[j] nextPerm(perm) } val solutions = fillHouses() val plural = if (solutions == 1) "" else "s" println("$solutions solution$plural found") }
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>
#Perl
Perl
use XML::XPath qw();   my $x = XML::XPath->new('<inventory ... </inventory>');   [$x->findnodes('//item[1]')->get_nodelist]->[0]; print $x->findnodes_as_string('//price'); $x->findnodes('//name')->get_nodelist;
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>
#Phix
Phix
include builtins/xml.e constant xml_txt = """ <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> """, -- or, of course, xml_txt = get_text("input.xml") xml = xml_parse(xml_txt) sequence sections = xml_get_nodes(xml[XML_CONTENTS],"section"), item1 = {}, prices = {}, names = {} for s=1 to length(sections) do sequence items = xml_get_nodes(sections[s],"item") if item1={} then item1 = items[1] end if for i=1 to length(items) do prices = append(prices,xml_get_nodes(items[i],"price")[1][XML_CONTENTS]) names = append(names,xml_get_nodes(items[i],"name")[1][XML_CONTENTS]) end for end for puts(1,"===item[1]===\n") sequence tmp = xml_new_doc(item1) puts(1,xml_sprint(tmp)) puts(1,"===prices===\n") pp(prices) puts(1,"===names===\n") pp(names,{pp_Maxlen,90})
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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
YinYang[size_] := Graphics[{{Circle[{0, 0}, 2]}, {Disk[{0, 0}, 2, {90 Degree, -90 Degree}]}, {White, Disk[{0, 1}, 1]}, {Black, Disk[{0, -1}, 1]}, {Black, Disk[{0, 1}, 1/4]}, {White, Disk[{0, -1}, 1/4]}}, ImageSize -> 40 size]
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.
#Metapost
Metapost
vardef yinyang(expr u) = picture pic_; path p_; p_ := halfcircle scaled 2u rotated -90 -- halfcircle scaled u rotated 90 shifted (0, 1/2u) reflectedabout ((0,1), (0,-1)) -- halfcircle scaled u rotated -270 shifted (0, -1/2u) -- cycle;   pic_ := nullpicture; addto pic_ contour fullcircle scaled 2u withcolor black; addto pic_ contour p_ withcolor white; addto pic_ doublepath p_ withcolor black withpen pencircle scaled 0.5mm; addto pic_ contour fullcircle scaled 1/3u shifted (0, 1/2u) withcolor white; addto pic_ contour fullcircle scaled 1/3u shifted (0, -1/2u) withcolor black; pic_ enddef;   beginfig(1)  % let's create a Yin Yang symbol with a radius of 5cm draw yinyang(5cm) shifted (5cm, 5cm);  % and another one, radius 2.5cm, rotated 180 degrees and translated draw yinyang(2.5cm) rotated 180 shifted (11cm, 11cm); endfig;   end.
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#Erlang
Erlang
Y = fun(M) -> (fun(X) -> X(X) end)(fun (F) -> M(fun(A) -> (F(F))(A) end) end) end.   Fac = fun (F) -> fun (0) -> 1; (N) -> N * F(N-1) end end. Fib = fun(F) -> fun(0) -> 0; (1) -> 1; (N) -> F(N-1) + F(N-2) end end. (Y(Fac))(5). %% 120 (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
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Dim As Integer n   Do Input "Enter size of matrix "; n Loop Until n > 0   Dim zigzag(1 To n, 1 To n) As Integer '' all zero by default   ' enter the numbers 0 to (n^2 - 1) in the matrix's anti-diagonals zigzag(1, 1) = 0 If n > 1 Then Dim As Integer row = 0, col = 3 Dim As Boolean down = true, increment = true Dim As Integer i = 0, j = 2, k Do If down Then For k = 1 To j i += 1 row += 1 col -= 1 zigzag(row, col) = i Next down = false Else For k = 1 To j i += 1 row -= 1 col += 1 zigzag(row, col) = i Next down = true End If If increment Then j += 1 If j > n Then j = n - 1 increment = false End If Else j -= 1 If j = 0 Then Exit Do End If If down AndAlso increment Then col += 2 row -= 1 ElseIf Not Down AndAlso increment Then row += 2 col -= 1 ElseIf down AndAlso Not increment Then col += 1 Else '' Not down AndAlso NotIncrement row += 1 End If Loop End If   ' print zigzag matrix if n < 20 Print If n < 20 Then For i As Integer = 1 To n For j As Integer = 1 To n Print Using "####"; zigzag(i, j); Next j Print Next i Else Print "Matrix is too big to display on 80 column console" End If   Print Print "Press any key to quit" Sleep
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
#Raku
Raku
given ~[**] 5, 4, 3, 2 { say "5**4**3**2 = {.substr: 0,20}...{.substr: *-20} and has {.chars} digits"; }
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
#REXX
REXX
/*REXX program calculates and demonstrates arbitrary precision numbers (using powers). */ numeric digits 200000 /*two hundred thousand decimal digits. */   # = 5 ** (4 ** (3 ** 2) ) /*calculate multiple exponentiations. */   true=62060698786608744707...92256259918212890625 /*what answer is supposed to look like.*/ rexx= left(#, 20)'...'right(#, 20) /*the left and right 20 decimal digits.*/   say ' true:' true /*show what the "true" answer is. */ say ' REXX:' rexx /* " " " REXX " " */ say 'digits:' length(#) /* " " " length of answer is. */ say if true == rexx then say 'passed!' /*either it passed, ··· */ else say 'failed!' /* or it didn't. */ /*stick a fork in it, we're all done. */
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
#Scala
Scala
def zNum( n:BigInt ) : String = {   if( n == 0 ) return "0" // Short-circuit this and return zero if we were given zero     val v = n.abs   val fibs : Stream[BigInt] = { def series(i:BigInt,j:BigInt):Stream[BigInt] = i #:: series(j, i+j); series(1,0).tail.tail.tail }     def z( v:BigInt ) : List[BigInt] = if(v == 0) List() else {val m = fibs(fibs.indexWhere(_>v) - 1); m :: z(v-m)}   val zv = z(v)   // Walk the list of fibonacci numbers from the number that matches the most significant down to 1, // if the zeckendorf matchs then yield '1' otherwise '0' val s = (for( i <- (fibs.indexWhere(_==zv(0)) to 0 by -1) ) yield {   if( zv.contains(fibs(i))) "1" else "0"   }).mkString   if( n < 0 ) "-" + s // Using a negative-sign instead of twos-complement else s }     // A little test... (0 to 20) foreach( i => print( zNum(i) + "\n" ) )  
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.
#Dyalect
Dyalect
var doors = Array.Empty(100, false)   for p in 0..99 { for d in 0..99 { if (d + 1) % (p + 1) == 0 { doors[d] = !doors[d]; } } }   for d in doors.Indices() when doors[d] { print("Door \(d+1): 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)
#J
J
1 NB. a stand-alone scalar value is an array without any axis 1 NB. invoking any array produces that array as the result {. array=: 1 3, 6#0 NB. create, name, then get head item of the array: 1 3 0 0 0 0 0 0 1 0 { array NB. another way to get the head item 1 aword=: 'there' NB. a literal array 0 1 3 2 2 { aword NB. multiple items can be drawn in a single action three ]twoD=: 3 5 $ 'abcdefghijklmnopqrstuvwxyz' abcde fghij klmno 1 { twoD NB. item 1 from twoD - a list of three items fghij 1 {"1 twoD NB. item 1 from each rank-1 item of twoD (i.e. column 1) bgl (<2 2){ twoD NB. bracket indexing is not used in J m 'X' 1} aword NB. amend item 1 tXere aword=: 'X' 1 4} aword NB. in-place amend of items 1 and 4 tXerX 'X' (0 0;1 1;2 2)} twoD NB. amend specified items Xbcde fXhij klXno
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
#Symsyn
Symsyn
  (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
#Tcl
Tcl
% expr 0**0 1 % expr 0.0**0.0 1.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
#Logtalk
Logtalk
  /* Houses logical puzzle: who owns the zebra and who drinks water?   1) Five colored houses in a row, each with an owner, a pet, cigarettes, and a drink. 2) The English lives in the red house. 3) The Spanish has a dog. 4) They drink coffee in the green house. 5) The Ukrainian drinks tea. 6) The green house is next to the white house. 7) The Winston smoker has a serpent. 8) In the yellow house they smoke Kool. 9) In the middle house they drink milk. 10) The Norwegian lives in the first house from the left. 11) The Chesterfield smoker lives near the man with the fox. 12) In the house near the house with the horse they smoke Kool. 13) The Lucky Strike smoker drinks juice. 14) The Japanese smokes Kent. 15) The Norwegian lives near the blue house.   Who owns the zebra and who drinks water? */   :- object(houses).   :- public(houses/1). :- mode(houses(-list), one). :- info(houses/1, [ comment is 'Solution to the puzzle.', argnames is ['Solution'] ]).   :- public(print/1). :- mode(print(+list), one). :- info(print/1, [ comment is 'Pretty print solution to the puzzle.', argnames is ['Solution'] ]).   houses(Solution) :- template(Solution), % 1 member(h(english, _, _, _, red), Solution), % 2 member(h(spanish, dog, _, _, _), Solution), % 3 member(h(_, _, _, coffee, green), Solution), % 4 member(h(ukrainian, _, _, tea, _), Solution), % 5 next(h(_, _, _, _, green), h(_, _, _, _, white), Solution), % 6 member(h(_, snake, winston, _, _), Solution), % 7 member(h(_, _, kool, _, yellow), Solution), % 8 Solution = [_, _, h(_, _, _, milk, _), _, _], % 9 Solution = [h(norwegian, _, _, _, _)| _], % 10 next(h(_, fox, _, _, _), h(_, _, chesterfield, _, _), Solution), % 11 next(h(_, _, kool, _, _), h(_, horse, _, _, _), Solution), % 12 member(h(_, _, lucky, juice, _), Solution), % 13 member(h(japonese, _, kent, _, _), Solution), % 14 next(h(norwegian, _, _, _, _), h(_, _, _, _, blue), Solution), % 15 member(h(_, _, _, water, _), Solution), % one of them drinks water member(h(_, zebra, _, _, _), Solution). % one of them owns a zebra   print([]). print([House| Houses]) :- write(House), nl, print(Houses).   % h(Nationality, Pet, Cigarette, Drink, Color) template([h(_, _, _, _, _), h(_, _, _, _, _), h(_, _, _, _, _), h(_, _, _, _, _), h(_, _, _, _, _)]).   member(A, [A, _, _, _, _]). member(B, [_, B, _, _, _]). member(C, [_, _, C, _, _]). member(D, [_, _, _, D, _]). member(E, [_, _, _, _, E]).   next(A, B, [A, B, _, _, _]). next(B, C, [_, B, C, _, _]). next(C, D, [_, _, C, D, _]). next(D, E, [_, _, _, D, E]).   :- end_object.  
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>
#PHP
PHP
<?php //PHP5 only example due to changes in XML extensions between version 4 and 5 (Tested on PHP5.2.0) $doc = DOMDocument::loadXML('<inventory title="OmniCorp Store #45x10^3">...</inventory>'); //Load from file instead with $doc = DOMDocument::load('filename'); $xpath = new DOMXPath($doc); /* 1st Task: Retrieve the first "item" element */ $nodelist = $xpath->query('//item'); $result = $nodelist->item(0); /* 2nd task: Perform an action on each "price" element (print it out) */ $nodelist = $xpath->query('//price'); for($i = 0; $i < $nodelist->length; $i++) { //print each price element in the DOMNodeList instance, $nodelist, as text/xml followed by a newline print $doc->saveXML($nodelist->item($i))."\n"; } /* 3rd Task: Get an array of all the "name" elements */ $nodelist = $xpath->query('//name'); //our array to hold all the name elements, though in practice you'd probably not need to do this and simply use the DOMNodeList $result = array(); //a different way of iterating through the DOMNodeList foreach($nodelist as $node) { $result[] = $node; }
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.
#Modula-2
Modula-2
MODULE Taijitu; FROM InOut IMPORT Write, WriteLn;   PROCEDURE YinYang(r: INTEGER); VAR x, y: INTEGER;   PROCEDURE circle(x, y, c, r: INTEGER): BOOLEAN; BEGIN RETURN r*r >= (x DIV 2) * (x DIV 2) + (y-c) * (y-c); END circle;   PROCEDURE pixel(x, y, r: INTEGER): CHAR; BEGIN IF circle(x, y, -r DIV 2, r DIV 6) THEN RETURN '#'; ELSIF circle(x, y, r DIV 2, r DIV 6) THEN RETURN '.'; ELSIF circle(x, y, -r DIV 2, r DIV 2) THEN RETURN '.'; ELSIF circle(x, y, r DIV 2, r DIV 2) THEN RETURN '#'; ELSIF circle(x, y, 0, r) THEN IF x<0 THEN RETURN '.'; ELSE RETURN '#'; END; ELSE RETURN ' '; END; END pixel; BEGIN FOR y := -r TO r DO FOR x := -2*r TO 2*r DO Write(pixel(x,y,r)); END; WriteLn(); END; END YinYang;   BEGIN YinYang(4); WriteLn(); YinYang(8); END Taijitu.
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
#F.23
F#
type 'a mu = Roll of ('a mu -> 'a) // ' fixes ease syntax colouring confusion with   let unroll (Roll x) = x // val unroll : 'a mu -> ('a mu -> 'a)   // As with most of the strict (non-deferred or non-lazy) languages, // this is the Z-combinator with the additional 'a' parameter... let fix f = let g = fun x a -> f (unroll x x) a in g (Roll g) // val fix : (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b = <fun>   // Although true to the factorial definition, the // recursive call is not in tail call position, so can't be optimized // and will overflow the call stack for the recursive calls for large ranges... //let fac = fix (fun f n -> if n < 2 then 1I else bigint n * f (n - 1)) // val fac : (int -> BigInteger) = <fun>   // much better progressive calculation in tail call position... let fac = fix (fun f n i -> if i < 2 then n else f (bigint i * n) (i - 1)) <| 1I // val fac : (int -> BigInteger) = <fun>   // Although true to the definition of Fibonacci numbers, // this can't be tail call optimized and recursively repeats calculations // for a horrendously inefficient exponential performance fib function... // let fib = fix (fun fnc n -> if n < 2 then n else fnc (n - 1) + fnc (n - 2)) // val fib : (int -> BigInteger) = <fun>   // much better progressive calculation in tail call position... let fib = fix (fun fnc f s i -> if i < 2 then f else fnc s (f + s) (i - 1)) 1I 1I // val fib : (int -> BigInteger) = <fun>   [<EntryPoint>] let main argv = fac 10 |> printfn "%A" // prints 3628800 fib 10 |> printfn "%A" // prints 55 0 // return an integer exit code
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
#GAP
GAP
ZigZag := function(n) local a, i, j, k; a := NullMat(n, n); i := 1; j := 1; for k in [0 .. n*n - 1] do a[i][j] := k; if (i + j) mod 2 = 0 then if j < n then j := j + 1; else i := i + 2; fi; if i > 1 then i := i - 1; fi; else if i < n then i := i + 1; else j := j + 2; fi; if j > 1 then j := j - 1; fi; fi; od; return a; end;   PrintArray(ZigZag(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
#Ruby
Ruby
y = ( 5**4**3**2 ).to_s puts "5**4**3**2 = #{y[0..19]}...#{y[-20..-1]} and has #{y.length} digits"  
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
#Run_BASIC
Run BASIC
x$ = str$( 5^(4^(3^2))) print "Length:";len( x$) print left$( x$, 20); "......"; right$( x$, 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
#Scheme
Scheme
(import (rnrs))   (define (getFibList maxNum n1 n2 fibs) (if (> n2 maxNum) fibs (getFibList maxNum n2 (+ n1 n2) (cons n2 fibs))))   (define (getZeckendorf num) (if (<= num 0) "0" (let ((fibs (getFibList num 1 2 (list 1)))) (getZeckString "" num fibs))))   (define (getZeckString zeck num fibs) (let* ((curFib (car fibs)) (placeZeck (>= num curFib)) (outString (string-append zeck (if placeZeck "1" "0"))) (outNum (if placeZeck (- num curFib) num))) (if (null? (cdr fibs)) outString (getZeckString outString outNum (cdr fibs)))))   (let loop ((i 0)) (when (<= i 20) (for-each (lambda (item) (display item)) (list "Z(" i "):\t" (getZeckendorf i))) (newline) (loop (+ i 1))))  
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.
#Dylan
Dylan
define method doors() let doors = make(<array>, fill: #f, size: 100); for (x from 0 below 100) for (y from x below 100 by x + 1) doors[y] := ~doors[y] end end; for (x from 1 to 100) if (doors[x - 1]) format-out("door %d open\n", x) 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)
#Java
Java
int[] array = new int[10]; //optionally, replace "new int[10]" with a braced list of ints like "{1, 2, 3}" array[0] = 42; System.out.println(array[3]);
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
#TI-83_BASIC
TI-83_BASIC
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
#uBasic.2F4tH
uBasic/4tH
Print 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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
1 2 3 4 5 colors Blue Blue Blue Blue Blue colors Green Green Green Green Green colors Red Red Red Red Red colors White White White White White colors Yellow Yellow Yellow Yellow Yellow nationality Dane Dane Dane Dane Dane nationality English English English English English nationality German German German German German nationality Norwegian Norwegian Norwegian Norwegian Norwegian nationality Swede Swede Swede Swede Swede beverage Beer Beer Beer Beer Beer beverage Coffee Coffee Coffee Coffee Coffee beverage Milk Milk Milk Milk Milk beverage Tea Tea Tea Tea Tea beverage Water Water Water Water Water animal Birds Birds Birds Birds Birds animal Cats Cats Cats Cats Cats animal Dog Dog Dog Dog Dog animal Horse Horse Horse Horse Horse animal Zebra Zebra Zebra Zebra Zebra smoke Blend Blend Blend Blend Blend smoke Blue Master Blue Master Blue Master Blue Master Blue Master smoke Dunhill Dunhill Dunhill Dunhill Dunhill smoke Pall Mall Pall Mall Pall Mall Pall Mall Pall Mall smoke Prince Prince Prince Prince Prince
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>
#PicoLisp
PicoLisp
(load "@lib/xm.l")   (let Sections (body (in "file.xml" (xml))) (pretty (car (body (car Sections)))) (prinl) (for S Sections (for L (body S) (prinl (car (body L 'price))) ) ) (make (for S Sections (for L (body S) (link (car (body L '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>
#PowerShell
PowerShell
  $document = [xml]@' <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> '@   $query = "/inventory/section/item" $items = $document.SelectNodes($query)  
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.
#NetRexx
NetRexx
/* NetRexx */   options replace format comments java crossref savelog symbols binary   say "<?xml version='1.0' encoding='UTF-8' standalone='no'?>" say "<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN'" say " 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>" say "<svg xmlns='http://www.w3.org/2000/svg' version='1.1'" say " xmlns:xlink='http://www.w3.org/1999/xlink'" say " width='30' height='30'>" say " <defs><g id='y'>" say " <circle cx='0' cy='0' r='200' stroke='black'" say " fill='white' stroke-width='1'/>" say " <path d='M0 -200 A 200 200 0 0 0 0 200" say " 100 100 0 0 0 0 0 100 100 0 0 1 0 -200" say " z' fill='black'/>" say " <circle cx='0' cy='100' r='33' fill='white'/>" say " <circle cx='0' cy='-100' r='33' fill='black'/>" say " </g></defs>"   say draw_yinyang(20, 0.05) say draw_yinyang(8, 0.02)   say "</svg>"   return   method draw_yinyang(trans = int, scale = double) inheritable static returns String yy = String.format(" <use xlink:href='#y' transform='translate(%d,%d) scale(%g)'/>", - [Object Integer(trans), Integer(trans), Double(scale)]) return yy
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
#Factor
Factor
USING: fry kernel math ; IN: rosettacode.Y : Y ( quot -- quot ) '[ [ dup call call ] curry @ ] dup call ; inline   : almost-fac ( quot -- quot ) '[ dup zero? [ drop 1 ] [ dup 1 - @ * ] if ] ;   : almost-fib ( quot -- quot ) '[ dup 2 >= [ 1 2 [ - @ ] bi-curry@ bi + ] when ] ;
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
#Go
Go
package main   import ( "fmt" "strconv" )   func zz(n int) []int { r := make([]int, n*n) i := 0 n2 := n * 2 for d := 1; d <= n2; d++ { x := d - n if x < 0 { x = 0 } y := d - 1 if y > n-1 { y = n - 1 } j := n2 - d if j > d { j = d } for k := 0; k < j; k++ { if d&1 == 0 { r[(x+k)*n+y-k] = i } else { r[(y-k)*n+x+k] = i } i++ } }   return r }   func main() { const n = 5 w := len(strconv.Itoa(n*n - 1)) for i, e := range zz(n) { fmt.Printf("%*d ", w, e) if i%n == n-1 { fmt.Println("") } } }
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
#Rust
Rust
extern crate num; use num::bigint::BigUint; use num::FromPrimitive; use num::pow::pow;   fn main() { let big = BigUint::from_u8(5).unwrap(); let answer_as_string = format!("{}", pow(big,pow(4,pow(3,2))));   // The rest is output formatting. let first_twenty: String = answer_as_string.chars().take(20).collect(); let last_twenty_reversed: Vec<char> = answer_as_string.chars().rev().take(20).collect(); let last_twenty: String = last_twenty_reversed.into_iter().rev().collect(); println!("Number of digits: {}", answer_as_string.len()); println!("First and last digits: {:?}..{:?}", first_twenty, last_twenty); }
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
#Sather
Sather
class MAIN is main is r:INTI; p1 ::= "62060698786608744707"; p2 ::= "92256259918212890625";   -- computing 5^(4^(3^2)), it could be written -- also e.g. (5.inti)^((4.inti)^((3.inti)^(2.inti))) r  := (3.pow(2)).inti; r  := (4.inti).pow(r); r  := (5.inti).pow(r);   sr ::= r.str; -- string rappr. of the number if sr.head(p1.size) = p1 and sr.tail(p2.size) = p2 then #OUT + "result is ok..\n"; else #OUT + "oops\n"; end; #OUT + "# of digits: " + sr.size + "\n"; end; 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
#Sidef
Sidef
func fib(n) is cached { n < 2 ? 1  : (fib(n-1) + fib(n-2)) }   func zeckendorf(n) { n == 0 && return '0' var i = 1 ++i while (fib(i) <= n) gather { while (--i > 0) { var f = fib(i) f > n ? (take '0')  : (take '1'; n -= f) } }.join }   for n (0..20) { printf("%4d: %8s\n", n, zeckendorf(n)) }
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.
#D.C3.A9j.C3.A0_Vu
Déjà Vu
local :open-doors [ rep 101 false ]   for i range 1 100: local :j i while <= j 100: set-to open-doors j not open-doors! j set :j + j i   !print\ "Open doors: " for i range 1 100: if open-doors! i: !print\( to-str i " " )
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#JavaScript
JavaScript
// Create a new array with length 0 var myArray = new Array();   // Create a new array with length 5 var myArray1 = new Array(5);   // Create an array with 2 members (length is 2) var myArray2 = new Array("Item1","Item2");   // Create an array with 2 members using an array literal var myArray3 = ["Item1", "Item2"];   // Assign a value to member [2] (length is now 3) myArray3[2] = 5;   var x = myArray[2] + myArray.length; // 8   // You can also add a member to an array with the push function (length is now 4) myArray3.push('Test');   // Elisions are supported, but are buggy in some implementations var y = [0,1,,]; // length 3, or 4 in buggy implementations  
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
#Ursa
Ursa
> out (pow 0 0) endl console 1.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
#VBA
VBA
Public Sub zero() x = 0 y = 0 z = 0 ^ 0 Debug.Print "z ="; z End Sub
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
#VBScript
VBScript
WScript.Echo 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
#Mercury
Mercury
:- module zebra. :- interface.   :- import_module io.   :- pred main(io, io). :- mode main(di, uo) is cc_multi.  % or det for all-solutions   :- implementation.   :- import_module list. :- import_module solutions.   % perm   :- pred my_perm(list(T), list(T)). :- mode my_perm(in, out) is multi.   my_perm([], []). my_perm([X | Xs], Perm) :- my_perm(Xs, PermXs), my_insert(X, PermXs, Perm).   :- pred my_insert(T, list(T), list(T)). :- mode my_insert(in, in, out) is multi.   my_insert(X, [], [X]). my_insert(X, [Y | Ys], Zs) :- ( Zs = [X, Y | Ys]  ; my_insert(X, Ys, Zs0), Zs = [Y | Zs0] ).   % The puzzle   :- type person ---> english  ; spanish  ; ukrainian  ; norwegian  ; japanese.   :- pred left_of(list(T), T, T). :- mode left_of(in, in, in) is semidet.   left_of([A, B | _], A, B). left_of([_ | List], A, B) :- left_of(List, A, B).   :- pred next_to(list(T), T, T). :- mode next_to(in, in, in) is semidet.   next_to(List, A, B) :- ( left_of(List, A, B)  ; left_of(List, B, A) ).   :- pred puzzle({list(person), list(person), list(person), list(person), list(person)}). :- mode puzzle(out) is nondet.   puzzle({Houses, Colours, Pets, Drinks, Smokes}) :-  % 10. The Norwegian lives in the first house. First = norwegian, perm([english, spanish, ukrainian, japanese], [Second, Third, Fourth, Fifth]),    % 2. The Englishman lives in the red house. Red = english, perm([spanish, ukrainian, norwegian, japanese], [Green, Ivory, Yellow, Blue]),    % 10. The Norwegian lives in the first house.  % 15. The Norwegian lives next to the blue house. Second = Blue,    % 6. The green house is immediately to the right of the ivory house. left_of(Houses, Ivory, Green),    % 3. The Spaniard owns the dog. Dog = spanish, perm([english, ukrainian, norwegian, japanese], [Snails, Fox, Horse, Zebra]),    % 4. Coffee is drunk in the green house. Green = Coffee,    % 5. The Ukrainian drinks tea. Tea = ukrainian,    % 9. Milk is drunk in the middle house. Milk = Third,   perm([english, spanish, norwegian, japanese], [Coffee, Milk, Juice, Water]),    % 7. The Old Gold smoker owns snails. Snails = OldGold,    % 8. Kools are smoked in the yellow house. Kools = Yellow,    % 13. The Lucky Strike smoker drinks orange juice. LuckyStrike = Juice,    % 14. The Japanese smokes Parliaments. Parliament = japanese,   perm([english, spanish, ukrainian, norwegian], [OldGold, Kools, Chesterfield, LuckyStrike]),    % 11. The man who smokes Chesterfields lives in the house  % next to the man with the fox. next_to(Houses, Chesterfield, Fox),    % 12. Kools are smoked in the house next to the house  % where the horse is kept. next_to(Houses, Kools, Horse),   Houses = [First, Second, Third, Fourth, Fifth], Colours = [Red, Green, Ivory, Yellow, Blue], Pets = [Dog, Snails, Fox, Horse, Zebra], Drinks = [Coffee, Tea, Milk, Juice, Water], Smokes = [OldGold, Kools, Chesterfield, LuckyStrike, Parliament].   % Printing a solution   :- pred write_solution({list(person), list(person), list(person), list(person), list(person)}::in, io::di, io::uo) is det.   write_solution({Houses, Colours, Pets, Drinks, Smokes}, !IO) :- write_string("--------\n", !IO), write_assignments(["1st", "2nd", "3rd", "4th", "5th"], Houses, !IO), write_assignments(["red", "green", "ivory", "yellow", "blue"], Colours, !IO), write_assignments(["dog", "snails", "fox", "horse", "zebra"], Pets, !IO), write_assignments(["coffee", "tea", "milk", "juice", "water"], Drinks, !IO), write_assignments(["oldgold", "kools", "chesterfield", "luckystrike", "parliament"], Smokes, !IO).   :- pred write_assignments(list(string)::in, list(person)::in, io::di, io::uo) is det.   write_assignments(Labels, Persons, !IO) :- foldl_corresponding(write_assignment, Labels, Persons, !IO), nl(!IO).   :- pred write_assignment(string::in, person::in, io::di, io::uo) is det.   write_assignment(Label, Person, !IO) :- write_string(Label, !IO), write_string(" - ", !IO), write(Person, !IO), write_string("\n", !IO).   % main   main(!IO) :-  % Print all solutions. /* solutions(puzzle, Solutions), foldl(write_solution, Solutions, !IO). */    % Print solutions as they are found. /* unsorted_aggregate(puzzle, write_solution, !IO). */    % Print one solution. ( if puzzle(Solution) then write_solution(Solution, !IO) else write_string("No solution found.\n", !IO) ).  
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>
#Python
Python
# Python has basic xml parsing built in   from xml.dom import minidom   xmlfile = file("test3.xml") # load xml document from file xmldoc = minidom.parse(xmlfile).documentElement # parse from file stream or... xmldoc = minidom.parseString("<inventory title="OmniCorp Store #45x10^3">...</inventory>").documentElement # alternatively, parse a string   # 1st Task: Retrieve the first "item" element i = xmldoc.getElementsByTagName("item") # get a list of all "item" tags firstItemElement = i[0] # get the first element   # 2nd task: Perform an action on each "price" element (print it out) for j in xmldoc.getElementsByTagName("price"): # get a list of all "price" tags print j.childNodes[0].data # XML Element . TextNode . data of textnode   # 3rd Task: Get an array of all the "name" elements namesArray = xmldoc.getElementsByTagName("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>
#R
R
  library("XML") doc <- xmlInternalTreeParse("test3.xml")   # Retrieve the first "item" element getNodeSet(doc, "//item")[[1]]   # Perform an action on each "price" element sapply(getNodeSet(doc, "//price"), xmlValue)   # Get an array of all the "name" elements sapply(getNodeSet(doc, "//name"), xmlValue)    
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.
#Nim
Nim
import gintro/cairo   proc draw(ctx: Context; x, y, r: float) = ctx.arc(x, y, r + 1, 1.571, 7.854) ctx.setSource(0.0, 0.0, 0.0) ctx.fill() ctx.arcNegative(x, y - r / 2, r / 2, 1.571, 4.712) ctx.arc(x, y + r / 2, r / 2, 1.571, 4.712) ctx.arcNegative(x, y, r, 4.712, 1.571) ctx.setSource(1.0, 1.0, 1.0) ctx.fill() ctx.arc(x, y - r / 2, r / 5, 1.571, 7.854) ctx.setSource(0.0, 0.0, 0.0) ctx.fill() ctx.arc(x, y + r / 2, r / 5, 1.571, 7.854) ctx.setSource(1.0, 1.0, 1.0) ctx.fill()   let surface = imageSurfaceCreate(argb32, 200, 200) let context = newContext(surface) context.draw(120, 120, 75) context.draw(35, 35, 30) let status = surface.writeToPng("yin-yang.png") assert status == Status.success
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
#Falcon
Falcon
  Y = { f => {x=> {n => f(x(x))(n)}} ({x=> {n => f(x(x))(n)}}) } facStep = { f => {x => x < 1 ? 1 : x*f(x-1) }} fibStep = { f => {x => x == 0 ? 0 : (x == 1 ? 1 : f(x-1) + f(x-2))}}   YFac = Y(facStep) YFib = Y(fibStep)   > "Factorial 10: ", YFac(10) > "Fibonacci 10: ", YFib(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
#Groovy
Groovy
def zz = { n -> grid = new int[n][n] i = 0 for (d in 1..n*2) { (x, y) = [Math.max(0, d - n), Math.min(n - 1, d - 1)] Math.min(d, n*2 - d).times { grid[d%2?y-it:x+it][d%2?x+it:y-it] = i++; } } grid }
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
#Scala
Scala
scala> BigInt(5) modPow (BigInt(4) pow (BigInt(3) pow 2).toInt, BigInt(10) pow 20) res21: scala.math.BigInt = 92256259918212890625   scala> (BigInt(5) pow (BigInt(4) pow (BigInt(3) pow 2).toInt).toInt).toString res22: String = 6206069878660874470748320557284679309194219265199117173177383244 78446890420544620839553285931321349485035253770303663683982841794590287939217907 89641300156281305613064874236198955114921296922487632406742326659692228562195387 46210423235340883954495598715281862895110697243759768434501295076608139350684049 01191160699929926568099301259938271975526587719565309995276438998093283175080241 55833224724855977970015112594128926594587205662421861723789001208275184293399910 13912158886504596553858675842231519094813553261073608575593794241686443569888058 92732524316323249492420512640962691673104618378381545202638771401061171968052873 21414945463925055899307933774904078819911387324217976311238875802878310483037255 33789567769926391314746986316354035923183981697660495275234703657750678459919... scala> res22 take 20 res23: String = 62060698786608744707   scala> res22 length res24: Int = 183231   scala>
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
#Scheme
Scheme
(define x (expt 5 (expt 4 (expt 3 2)))) (define y (number->string x)) (define l (string-length y)) (display (string-append "5**4**3**2 = " (substring y 0 20) "..." (substring y (- l 20) l) " and has " (number->string l) " digits")) (newline)
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
#Simula
Simula
BEGIN INTEGER N, F0, F1, F2, D; N := 20; COMMENT CALCULATE D FROM ANY GIVEN N ; F1 := 1; F2 := 2; F0 := F1 + F2; D := 2; WHILE F0 < N DO BEGIN F1 := F2; F2 := F0; F0 := F1 + F2; D := D + 1; END; BEGIN COMMENT Sinclair ZX81 BASIC Solution ; TEXT Z1, S1; INTEGER I, J, Z; INTEGER ARRAY F(1:D);  ! 10 dim f(6) ; F(1) := 1;  ! 20 let f(1)=1 ; F(2) := 2;  ! 30 let f(2)=2 ; FOR I := 3 STEP 1 UNTIL D DO BEGIN  ! 40 for i=3 to 6 ; F(I) := F(I-2) + F(I-1);  ! 50 let f(i)=f(i-2)+f(i-1) ; END;  ! 60 next i ; FOR I := 0 STEP 1 UNTIL N DO BEGIN  ! 70 for i=0 to 20 ; Z1 :- "";  ! 80 let z$="" ; S1 :- " ";  ! 90 let s$=" " ; Z := I;  ! 100 let z=i ; FOR J := D STEP -1 UNTIL 1 DO BEGIN ! 110 for j=6 to 1 step -1 ; IF J=1 THEN S1 :- "0";  ! 120 if j=1 then let s$="0" ; IF NOT (Z<F(J)) THEN BEGIN  ! 130 if z<f(j) then goto 180 ; Z1 :- Z1 & "1";  ! 140 let z$=z$+"1" ; Z := Z-F(J);  ! 150 let z=z-f(j) ; S1 :- "0";  ! 160 let s$="0" ; END ELSE  ! 170 goto 190 ; Z1 :- Z1 & S1;  ! 180 let z$=z$+s$ ; END;  ! 190 next j ; OUTINT(I, 0); OUTCHAR(' ');  ! 200 print i ; !" "; !; IF I<10 THEN OUTCHAR(' ');  ! 210 if i<10 then print " "; !; OUTTEXT(Z1); OUTIMAGE;  ! 220 print z$ ; END;  ! 230 next i ; END; END
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.
#E
E
#!/usr/bin/env rune   var toggles := [] var gets := []   # Set up GUI (and data model) def frame := <swing:makeJFrame>("100 doors") frame.getContentPane().setLayout(<awt:makeGridLayout>(10, 10)) for i in 1..100 { def component := <import:javax.swing.makeJCheckBox>(E.toString(i)) toggles with= fn { component.setSelected(!component.isSelected()) } gets with= fn { component.isSelected() } frame.getContentPane().add(component) }   # Set up termination condition def done frame.addWindowListener(def _ { to windowClosing(event) { bind done := true } match _ {} })   # Open and close doors def loop(step, i) { toggles[i] <- () def next := i + step timer.whenPast(timer.now() + 10, fn { if (next >= 100) { if (step >= 100) { # Done. } else { loop <- (step + 1, step) } } else { loop <- (step, i + step) } }) } loop(1, 0)   frame.pack() frame.show() interp.waitAtTop(done)
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)
#jq
jq
# Create a new array with length 0 []   # Create a new array of 5 nulls [][4] = null # setting the element at offset 4 expands the array   # Create an array having the elements 1 and 2 in that order [1,2]   # Create an array of integers from 0 to 10 inclusive [ range(0; 11) ]   # If a is an array (of any length), update it so that a[2] is 5 a[2] = 5;   # Append arrays a and b a + b   # Append an element, e, to an array a a + [e]   ################################################## # In the following, a is assumed to be [0,1,2,3,4]   # It is not an error to use an out-of-range index: a[10] # => null   # Negative indices count backwards from after the last element: a[-1] # => 4   # jq supports simple slice operations but # only in the forward direction: a[:1] # => [0] a[1:] # => [1,2,3,4] a[2:4] # => [2,3] a[4:2] # null
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
#Verilog
Verilog
module main; initial begin $display("0 ^ 0 = ", 0**0); $finish ; end endmodule
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
#Visual_Basic_.NET
Visual Basic .NET
Module Program Sub Main() Console.Write(0^0) End Sub End Module
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
#MiniZinc
MiniZinc
  %Solve Zebra Puzzle. Nigel Galloway, August 27th., 2019 include "alldifferent.mzn"; enum N={English,Swedish,Danish,German,Norwegian}; enum I={Tea,Coffee,Milk,Beer,Water}; enum G={Dog,Birds,Cats,Horse,Zebra}; enum E={Red,Green,White,Blue,Yellow}; enum L={PallMall,Dunhill,BlueMaster,Prince,Blend}; array[1..5] of var N: Nz; constraint alldifferent(Nz); constraint Nz[1]=Norwegian;  %The Norwegian lives in the first house. array[1..5] of var I: Iz; constraint alldifferent(Iz); constraint Iz[3]=Milk;  %In the middle house they drink milk. array[1..5] of var G: Gz; constraint alldifferent(Gz); array[1..5] of var E: Ez; constraint alldifferent(Ez); array[1..5] of var L: Lz; constraint alldifferent(Lz); constraint exists(n in 1..5)(Nz[n]=English /\ Ez[n]=Red);  %The English man lives in the red house constraint exists(n in 1..5)(Nz[n]=Swedish /\ Gz[n]=Dog);  %The Swede has a dog. constraint exists(n in 1..5)(Nz[n]=Danish /\ Iz[n]=Tea);  %The Dane drinks tea. constraint exists(n in 1..4)(Ez[n]=Green /\ Ez[n+1]=White);  %The green house is immediately to the left of the white house. constraint exists(n in 1..5)(Ez[n]=Green /\ Iz[n]=Coffee);  %They drink coffee in the green house. constraint exists(n in 1..5)(Lz[n]=PallMall /\ Gz[n]=Birds);  %The man who smokes Pall Mall has birds constraint exists(n in 1..5)(Ez[n]=Yellow /\ Lz[n]=Dunhill);  %In the yellow house they smoke Dunhill. constraint exists(n in 1..4)((Lz[n]=Blend /\ Gz[n+1]=Cats) \/ (Lz[n+1]=Blend /\ Gz[n]=Cats));  %The man who smokes Blend lives in the house next to the house with cats. constraint exists(n in 1..4)((Gz[n]=Horse /\ Lz[n+1]=Dunhill) \/ (Gz[n+1]=Horse /\ Lz[n]=Dunhill));  %In a house next to the house where they have a horse, they smoke Dunhill. constraint exists(n in 1..5)(Lz[n]=BlueMaster /\ Iz[n]=Beer);  %The man who smokes Blue Master drinks beer. constraint exists(n in 1..5)(Nz[n]=German /\ Lz[n]=Prince);  %The German smokes Prince. constraint exists(n in 1..4)((Nz[n]=Norwegian /\ Ez[n+1]=Blue) \/ (Nz[n+1]=Norwegian /\ Ez[n]=Blue));%The Norwegian lives next to the blue house. constraint exists(n in 1..4)((Lz[n]=Blend /\ Iz[n+1]=Water) \/ (Lz[n+1]=Blend /\ Iz[n]=Water));  %They drink water in a house next to the house where they smoke Blend. var 1..5: n; constraint Gz[n]=Zebra; solve satisfy; output ["The "++show(Nz[n])++" owns the zebra"++"\n\n"++show(Nz)++"\n"++show(Iz)++"\n"++show(Gz)++"\n"++show(Ez)++"\n"++show(Lz)++"\n"];  
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>
#Racket
Racket
  #lang at-exp racket   (define input @~a{ <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>})   (require xml xml/path)   (define data (xml->xexpr ((eliminate-whitespace '(inventory section item)) (read-xml/element (open-input-string input)))))   ;; Retrieve the first "item" element (displayln (xexpr->string (se-path* '(item) data))) ;; => <name>Invisibility Cream</name>   ;; Perform an action on each "price" element (print it out) (printf "Prices: ~a\n" (string-join (se-path*/list '(item price) data) ", ")) ;; => Prices: 14.50, 23.99, 4.95, 3.56   ;; Get an array of all the "name" elements (se-path*/list '(item name) data) ;; => '("Invisibility Cream" "Levitation Salve" "Blork and Freen Instameal" "Grob winglets")  
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>
#Raku
Raku
use XML::XPath;   my $XML = XML::XPath.new(xml => q:to/END/); <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> END   put "First item:\n", $XML.find('//item[1]')[0];   put "\nPrice elements:"; .contents.put for $XML.find('//price').List;   put "\nName elements:\n", $XML.find('//name')».contents.join: ', ';
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.
#OCaml
OCaml
open Graphics   let draw_yinyang x y radius black white = let hr = radius / 2 in let sr = radius / 6 in set_color black; set_line_width 6; draw_circle x y radius; set_line_width 0; set_color black; fill_arc x y radius radius 270 450; set_color white; fill_arc x y radius radius 90 270; fill_arc x (y + hr) hr hr 270 450; set_color black; fill_arc x (y - hr) hr hr 90 270; fill_circle x (y + hr) sr; set_color white; fill_circle x (y - hr) sr   let () = open_graph ""; let width = size_x() and height = size_y() in set_color (rgb 200 200 200); fill_rect 0 0 width height; let w = width / 3 and h = height / 3 in let r = (min w h) / 3 in draw_yinyang w (h*2) (r*2) black white; draw_yinyang (w*2) h r blue magenta; ignore(read_key())
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
#Forth
Forth
\ Address of an xt. variable 'xt \ Make room for an xt. : xt, ( -- ) here 'xt ! 1 cells allot ; \ Store xt. : !xt ( xt -- ) 'xt @ ! ; \ Compile fetching the xt. : @xt, ( -- ) 'xt @ postpone literal postpone @ ; \ Compile the Y combinator. : y, ( xt1 -- xt2 ) >r :noname @xt, r> compile, postpone ; ; \ Make a new instance of the Y combinator. : y ( xt1 -- xt2 ) xt, y, dup !xt ;
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
#Haskell
Haskell
import Data.Array (Array, array, bounds, range, (!)) import Text.Printf (printf) import Data.List (sortBy)   compZig :: (Int, Int) -> (Int, Int) -> Ordering compZig (x, y) (x_, y_) = compare (x + y) (x_ + y_) <> go x y where go x y | even (x + y) = compare x x_ | otherwise = compare y y_   zigZag :: (Int, Int) -> Array (Int, Int) Int zigZag upper = array b $ zip (sortBy compZig (range b)) [0 ..] where b = ((0, 0), upper)
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
#Seed7
Seed7
$ include "seed7_05.s7i"; include "bigint.s7i";   const proc: main is func local var bigInteger: fiveToThePowerOf262144 is 5_ ** 4 ** 3 ** 2; var string: numberAsString is str(fiveToThePowerOf262144); begin writeln("5**4**3**2 = " <& numberAsString[..20] <& "..." <& numberAsString[length(numberAsString) - 19 ..]); writeln("decimal digits: " <& length(numberAsString)); end func;
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
#Sidef
Sidef
var x = 5**(4**(3**2)); var y = x.to_s; printf("5**4**3**2 = %s...%s and has %i digits\n", y.ft(0,19), y.ft(-20), y.len);
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
#Sinclair_ZX81_BASIC
Sinclair ZX81 BASIC
10 DIM F(6) 20 LET F(1)=1 30 LET F(2)=2 40 FOR I=3 TO 6 50 LET F(I)=F(I-2)+F(I-1) 60 NEXT I 70 FOR I=0 TO 20 80 LET Z$="" 90 LET S$=" " 100 LET Z=I 110 FOR J=6 TO 1 STEP -1 120 IF J=1 THEN LET S$="0" 130 IF Z<F(J) THEN GOTO 180 140 LET Z$=Z$+"1" 150 LET Z=Z-F(J) 160 LET S$="0" 170 GOTO 190 180 LET Z$=Z$+S$ 190 NEXT J 200 PRINT I;" "; 210 IF I<10 THEN PRINT " "; 220 PRINT Z$ 230 NEXT 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.
#EasyLang
EasyLang
len d[] 101 for p = 1 to 100 i = p while i <= 100 d[i] = 1 - d[i] i += p . . for i = 1 to 100 if d[i] = 1 print i . .
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Jsish
Jsish
/* Arrays in Jsi */ // Create a new array with length 0 var myArray = new Array(); ;myArray;   // In Jsi, typeof [] is "array". In ECMAScript, typeof [] is "object" ;typeof [];   // Create a new array with length 5 var myArray1 = new Array(5); ;myArray1;   // Create an array with 2 members (length is 2) var myArray2 = new Array("Item1","Item2"); ;myArray2; ;myArray2.length;   // Create an array with 2 members using an array literal var myArray3 = ["Item1", "Item2"]; ;myArray3;   // Assign a value to member [2] (length is now 3) myArray3[2] = 5; ;myArray3; ;myArray3.length;   var x = myArray3[2] + myArray3.length; // 8 ;x;   // You can also add a member to an array with the push function (length is now 4) myArray3.push('Test'); ;myArray3; ;myArray3.length;   // Empty array entries in a literal is a syntax error, elisions not allowed //var badSyntax = [1,2,,4];     /* =!EXPECTSTART!= myArray ==> [] typeof [] ==> array myArray1 ==> [ undefined, undefined, undefined, undefined, undefined ] myArray2 ==> [ "Item1", "Item2" ] myArray2.length ==> 2 myArray3 ==> [ "Item1", "Item2" ] myArray3 ==> [ "Item1", "Item2", 5 ] myArray3.length ==> 3 x ==> 8 myArray3 ==> [ "Item1", "Item2", 5, "Test" ] myArray3.length ==> 4 =!EXPECTEND!= */
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
#Vlang
Vlang
// Zero to the zero power, in V // Tectonics: v run zero-to-the-zero-power.v module main import math   // starts here // V does not include an exponentiation operator, but uses a math module pub fn main() { println(math.pow(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
#Wren
Wren
System.print(0.pow(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
#Nial
Nial
  remove is op x xs {filter (not (x =)) xs}   append_map is transformer func op seq { \ reduce (op x xs { (func x) link xs}) (seq append []) }   permutations is op seq { \ if empty seq then [[]] else \ (append_map \ (op head {each (op tail {head hitch tail}) \ (permutations (remove head seq))}) \ seq) \ endif}   f is find tokenize is op str{string_split ' ' str} mk is tr pred op str {filter pred permutations tokenize str} eq is op x xs y ys{f x xs = f y ys} adj is op x xs y ys{1 = abs(f x xs - f y ys)}   run is { \ men := mk (op xs {0 = f 'norwegian' xs}) \ 'danish english german norwegian swedish'; \ colors := mk (op xs {1 = ((f 'white' xs) - (f 'green' xs))}) \ 'blue green red white yellow'; \ drinks := mk (op xs {2 = f 'milk' xs}) 'beer coffee milk tea water'; \ pets := mk (op xs {l}) 'birds cats dog horse zebra'; \ smokes := mk (op xs {l}) 'blend blue-master dunhill pall-mall prince'; \ for m with men do \ for c with colors do \ if (eq 'english' m 'red' c) and \ (adj 'norwegian' m 'blue' c) then \ for d with drinks do \ if (eq 'danish' m 'tea' d) and \ (eq 'coffee' d 'green' c) then \ for s with smokes do \ if (eq 'yellow' c 'dunhill' s) and \ (eq 'blue-master' s 'beer' d) and \ (eq 'german' m 'prince' s) then \ for p with pets do \ if (eq 'birds' p 'pall-mall' s) and \ (eq 'swedish' m 'dog' p) and \ (adj 'blend' s 'cats' p) and \ (adj 'horse' p 'dunhill' s) then \ write (0 blend (p m c d s)) \ endif \ endfor \ endif \ endfor \ endif \ endfor \ endif \ endfor \ endfor }   abs(time - (run; time))  
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>
#Rascal
Rascal
import lang::xml::DOM; import Prelude;   public void get_first_item(loc a){ D = parseXMLDOM(readFile(a)); top-down-break visit(D){ case E:element(_,"item",_): return println(xmlPretty(E)); }; }   public void print_prices(loc a){ D = parseXMLDOM(readFile(a)); for(/element(_,"price",[charData(/str p)]) := D) println(p); }   public list[str] get_names(loc a){ D = parseXMLDOM(readFile(a)); L = []; for(/element(_,"name",[charData(/str n)]) := D) L += n; return 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>
#REXX
REXX
/*REXX program to parse various queries on an XML document (from a file). */ iFID='XPATH.XML' /*name of the input XML file (doc). */ $= /*string will contain the file's text. */ do j=1 while lines(iFID)\==0 /*read the entire file into a string. */ $=$ linein(iFID) /*append the line to the $ string. */ end /*j*/ /* [↓] show 1st ITEM in the document*/ parse var $ '<item ' item "</item>" say center('first item:',length(space(item)),'─') /*display a nice header.*/ say space(item) /* [↓] show all PRICES in the document*/ prices= /*nullify the list and add/append to it*/ $$=$ /*start with a fresh copy of document. */ do until $$='' /* [↓] keep parsing string until done.*/ parse var $$ '<price>' price '</price>' $$ prices=prices price /*add/append the price to the list. */ end /*until*/ say say center('prices:',length(space(prices)),'─') /*display a nice header.*/ say space(prices) /* [↓] show all NAMES in the document*/ names.= /*nullify the list and add/append to it*/ L=length(' names: ') /*maximum length of any one list name. */ $$=$ /*start with a fresh copy of document. */ do #=1 until $$='' /* [↓] keep parsing string until done.*/ parse var $$ '<name>' names.# '</name>' $$ L=max(L,length(names.#)) /*L: is used to find the widest name. */ end /*#*/   names.0=#-1; say /*adjust the number of names (DO loop).*/ say center('names:',L,'─') /*display a nicely formatted header. */ do k=1 for names.0 /*display all the names in the list. */ say names.k /*display a name from the NAMES list.*/ end /*k*/ /*stick a fork in it, we're all done. */
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.
#PARI.2FGP
PARI/GP
YinYang(r)={ for(y=-r,r, print(concat(apply( x-> if( x^2+y^2>r^2, " ", [y<0,y>0,x>0][logint((x^2+(abs(y)-r/2)^2)<<8\r^2+1,2)\3+1], "#", "." ), [-r..r] )))) }
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.
#Pascal
Pascal
//Written for TU Berlin //Compiled with fpc Program yingyang; Uses Math; const scale_x=2; scale_y=1; black='#'; white='.'; clear=' ';   function inCircle(centre_x:Integer;centre_y:Integer;radius:Integer;x:Integer;y:Integer):Boolean ; begin inCircle:=power(x-centre_x,2)+power(y-centre_y,2)<=power(radius,2); end;   function bigCircle(radius:Integer;x:Integer;y:Integer):Boolean ; begin bigCircle:=inCircle(0,0,radius,x,y); end;   function whiteSemiCircle(radius:Integer;x:Integer;y:Integer):Boolean ; begin whiteSemiCircle:=inCircle(0,radius div 2 ,radius div 2,x,y); end;     function smallBlackCircle(radius:Integer;x:Integer;y:Integer):Boolean ; begin smallBlackCircle:=inCircle(0,radius div 2 ,radius div 6,x,y); end;   function blackSemiCircle(radius:Integer;x:Integer;y:Integer):Boolean ; begin blackSemiCircle:=inCircle(0,-radius div 2 ,radius div 2,x,y); end;   function smallWhiteCircle(radius:Integer;x:Integer;y:Integer):Boolean ; begin smallWhiteCircle:=inCircle(0,-radius div 2 ,radius div 6,x,y); end;   var radius,sy,sx,x,y:Integer; begin writeln('Please type a radius:'); readln(radius); if radius<3 then begin writeln('A radius bigger than 3');halt end; sy:=round(radius*scale_y); while(sy>=-round(radius*scale_y)) do begin sx:=-round(radius*scale_x); while(sx<=round(radius*scale_x)) do begin x:=sx div scale_x; y:=sy div scale_y; if bigCircle(radius,x,y) then begin if (whiteSemiCircle(radius,x,y)) then if smallblackCircle(radius,x,y) then write(black) else write(white) else if blackSemiCircle(radius,x,y) then if smallWhiteCircle(radius,x,y) then write(white) else write(black) else if x>0 then write(white) else write(black); end else write(clear); sx:=sx+1 end; writeln; sy:=sy-1; end; end.      
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#FreeBASIC
FreeBASIC
Function Y(f As String) As String Y = f End Function   Function fib(n As Long) As Long Dim As Long n1 = 0, n2 = 1, k, sum For k = 1 To Abs(n) sum = n1 + n2 n1 = n2 n2 = sum Next k Return Iif(n < 0, (n1 * ((-1) ^ ((-n)+1))), n1) End Function   Function fac(n As Long) As Long Dim As Long r = 1, i For i = 2 To n r *= i Next i Return r End Function   Function execute(s As String, n As Integer) As Long Return Iif (s = "fac", fac(n), fib(n)) End Function   Sub test(nombre As String) Dim f As String: f = Y(nombre) Print !"\n"; f; ":"; For i As Integer = 1 To 10 Print execute(f, i); Next i End Sub   test("fac") test("fib") Sleep