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="heal...
#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 xm...
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="heal...
#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>Invisi...
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 ...
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...
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 stat...
#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, 5...
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, gi...
#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 di...
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 ...
#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 ...
#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, ...
#REXX
REXX
  /* REXX *************************************************************** * 11.10.2012 Walter Pachl **********************************************************************/ fib='13 8 5 3 2 1' Do i=6 To 1 By -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...
#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...
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,...
#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, ...
#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, ...
#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, ...
#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 ...
#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 ...
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="heal...
#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 ...
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), ...
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 stat...
#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...
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, gi...
#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...
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 ...
#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 ...
#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, ...
#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] + f...
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, ...
#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...
#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,...
#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, ...
#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, ...
#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, ...
#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 ...
#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 ...
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="heal...
#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="heal...
#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"...
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 with...
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 stat...
#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). %...
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, gi...
#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,...
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 ...
#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 ...
#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...922562599182128...
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, ...
#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 ...
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...
#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,...
#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 ...
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, ...
#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, ...
#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 ...
#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. ...
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="heal...
#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 t...
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 circl...
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 stat...
#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 (un...
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, gi...
#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...
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 ...
#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 ...
#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, ...
#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 ...
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...
#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,...
#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, ...
#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, ...
#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 ...
#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 nation...
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="heal...
#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="heal...
#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...
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'"...
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 stat...
#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, gi...
#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 ...
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 ...
#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)....
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 ...
#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; -- s...
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, ...
#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...
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...
#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,...
#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"];   ...
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, ...
#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, ...
#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, ...
#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 ...
#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_pe...
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="heal...
#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 # a...
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="heal...
#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...
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 stat...
#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, gi...
#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 ...
#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 7844689042054462083955328593...
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 ...
#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, ...
#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; ...
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...
#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.setSele...
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,...
#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), up...
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, ...
#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, ...
#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 ...
#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:...
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="heal...
#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="44532234...
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="heal...
#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="44532...
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 (...
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 stat...
#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 instan...
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, gi...
#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 :: (...
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 ...
#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(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 ...
#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, ...
#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...
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...
#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,...
#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 ...
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, ...
#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, ...
#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 ...
#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 he...
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="heal...
#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) pri...
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="heal...
#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. ...
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;   ...
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 stat...
#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 ...