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/Yellowstone_sequence
Yellowstone sequence
The Yellowstone sequence, also called the Yellowstone permutation, is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence. Example a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2). Task Find and show as output the first  30  Yellowstone numbers. Extra Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers. Related tasks   Greatest common divisor.   Plot coordinate pairs. See also   The OEIS entry:   A098550 The Yellowstone permutation.   Applegate et al, 2015: The Yellowstone Permutation [1].
#XPL0
XPL0
func GCD(N, D); \Return the greatest common divisor of N and D int N, D, R; \numerator, denominator, remainder [if D > N then [R:=D; D:=N; N:=R]; \swap D and N while D > 0 do [R:= rem(N/D); N:= D; D:= R; ]; return N; ];   int I, A(30+1), N, T; [for I:= 1 to 3 do A(I):= I; \givens N:= 4; repeat T:= 4; loop [if GCD(T, A(N-1)) = 1 and \relatively prime GCD(T, A(N-2)) # 1 then \not relatively prime [loop [for I:= 1 to N-1 do \test if in sequence if T = A(I) then quit; quit; ]; if I = N then \T is not in sequence so [A(N):= T; \ add it in N:= N+1; quit; ]; ]; T:= T+1; \next trial ]; until N > 30; for N:= 1 to 30 do [IntOut(0, A(N)); ChOut(0, ^ )]; \\for N:= 1 to 100 do Point(N, A(N)); \plot demonstration ]
http://rosettacode.org/wiki/Yellowstone_sequence
Yellowstone sequence
The Yellowstone sequence, also called the Yellowstone permutation, is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence. Example a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2). Task Find and show as output the first  30  Yellowstone numbers. Extra Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers. Related tasks   Greatest common divisor.   Plot coordinate pairs. See also   The OEIS entry:   A098550 The Yellowstone permutation.   Applegate et al, 2015: The Yellowstone Permutation [1].
#zkl
zkl
fcn yellowstoneW{ // --> iterator Walker.zero().tweak(fcn(a,b){ foreach i in ([1..]){ if(not b.holds(i) and i.gcd(a[-1])==1 and i.gcd(a[-2]) >1){ a.del(0).append(i); // only keep last two terms b[i]=True; return(i); } } }.fp(List(2,3), Dictionary(1,True, 2,True, 3,True))).push(1,2,3); }
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
#Ol
Ol
  (define x (expt 5 (expt 4 (expt 3 2)))) (print (div x (expt 10 (- (log 10 x) 20))) "..." (mod x (expt 10 20))) (print "totally digits: " (log 10 x))  
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
#ooRexx
ooRexx
  --REXX program to show arbitrary precision integers. numeric digits 200000 check = '62060698786608744707...92256259918212890625'   start = .datetime~new n = 5 ** (4 ** (3**2)) time = .datetime~new - start say 'elapsed time for the calculation:' time say sampl = left(n, 20)"..."right(n, 20)   say ' check:' check say 'Sample:' sampl say 'digits:' length(n) say   if check=sampl then say 'passed!' else say 'failed!'  
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
#Plain_TeX
Plain TeX
\def\genfibolist#1{% #creates the fibo list which sum>=#1 \let\fibolist\empty\def\targetsum{#1}\def\fibosum{0}% \genfibolistaux1,1\relax } \def\genfibolistaux#1,#2\relax{% \ifnum\fibosum<\targetsum\relax \edef\fibosum{\number\numexpr\fibosum+#2}% \edef\fibolist{#2,\fibolist}% \edef\tempfibo{\noexpand\genfibolistaux#2,\number\numexpr#1+#2\relax\relax}% \expandafter\tempfibo \fi } \def\zeckendorf#1{\expandafter\zeckendorfaux\fibolist,\relax#1\relax\relax0} \def\zeckendorfaux#1,#2\relax#3\relax#4\relax#5{% \ifx\relax#2\relax #4% \else \ifnum#3<#1 \edef\temp{#2\relax#3\relax#4\ifnum#5=1 0\fi\relax#5}% \else \edef\temp{#2\relax\number\numexpr#3-#1\relax\relax#41\relax1}% \fi \expandafter\expandafter\expandafter\zeckendorfaux\expandafter\temp \fi } \newcount\ii \def\listzeckendorf#1{% \genfibolist{#1}% \ii=0 \loop \ifnum\ii<#1 \advance\ii1 \number\ii: \zeckendorf\ii\endgraf \repeat } \listzeckendorf{20}% any integer accepted \bye
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
#PowerShell
PowerShell
  function Get-ZeckendorfNumber ( $N ) { # Calculate relevant portation of Fibonacci series $Fib = @( 1, 1 ) While ( $Fib[-1] -lt $N ) { $Fib += $Fib[-1] + $Fib[-2] }   # Start with 0 $ZeckendorfNumber = 0   # For each number in the relevant portion of Fibonacci series For ( $i = $Fib.Count - 1; $i -gt 0; $i-- ) { # If Fibonacci number is less than or equal to remainder of N If ( $Fib[$i] -le $N ) { # Double Z number and add 1 (equivalent to adding a '1' to the end of a binary number) $ZeckendorfNumber = $ZeckendorfNumber * 2 + 1 # Reduce N by Fibonacci number, skip next Fibonacci number $N -= $Fib[$i--] } # If were aren't finished yet, double Z number # (equivalent to adding a '0' to the end of a binary number) If ( $i ) { $ZeckendorfNumber *= 2 } } return $ZeckendorfNumber }  
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
D
import std.stdio; const N = 101; // #doors + 1 void main() { bool[N] doors = false; for(auto door=1; door<N; door++ ) { for(auto i=door; i<N; i+=door ) doors[i] = !doors[i]; if (doors[door]) write(door, " "); } }
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Halon
Halon
$array = [];   $array[] = 1; $array["key"] = 3;   $array[0] = 2;   echo $array[0]; echo $array["key"];
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part",   where the imaginary part is the number to be multiplied by i {\displaystyle i} . Task Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. Optional: Show complex conjugation. By definition, the   complex conjugate   of a + b i {\displaystyle a+bi} is a − b i {\displaystyle a-bi} Some languages have complex number libraries available.   If your language does, show the operations.   If your language does not, also show the definition of this type.
#Vlang
Vlang
import math.complex fn main() { a := complex.complex(1, 1) b := complex.complex(3.14159, 1.25) println("a: $a") println("b: $b") println("a + b: ${a+b}") println("a * b: ${a*b}") println("-a: ${a.addinv()}") println("1 / a: ${complex.complex(1,0)/a}") println("a̅: ${a.conjugate()}") }
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part",   where the imaginary part is the number to be multiplied by i {\displaystyle i} . Task Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. Optional: Show complex conjugation. By definition, the   complex conjugate   of a + b i {\displaystyle a+bi} is a − b i {\displaystyle a-bi} Some languages have complex number libraries available.   If your language does, show the operations.   If your language does not, also show the definition of this type.
#Wortel
Wortel
@class Complex { &[r i] @: { ^r || r 0 ^i || i 0 ^m +@sq^r @sq^i } add &o @new Complex[+ ^r o.r + ^i o.i] mul &o @new Complex[-* ^r o.r * ^i o.i +* ^r o.i * ^i o.r] neg &^ @new Complex[@-^r @-^i] inv &^ @new Complex[/ ^r ^m / @-^i ^m] toString &^?{ =^i 0 "{^r}" =^r 0 "{^i}i" >^i 0 "{^r} + {^i}i" "{^r} - {@-^i}i" } }   @vars { a @new Complex[5 3] b @new Complex[4 3N] } @each &x !console.log x [ "({a}) + ({b}) = {!a.add b}" "({a}) * ({b}) = {!a.mul b}" "-1 * ({b}) = {b.neg.}" "({a}) - ({b}) = {!a.add b.neg.}" "1 / ({b}) = {b.inv.}" "({!a.mul b}) / ({b}) = {`!.mul b.inv. !a.mul b}" ]
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
#Quackery
Quackery
/O> 0 0 ** ...   Stack: 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
#R
R
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
#Racket
Racket
#lang racket ;; as many zeros as I can think of... (define zeros (list 0  ; unspecified number type 0. ; hinted as float #e0 ; explicitly exact #i0 ; explicitly inexact 0+0i ; exact complex 0.+0.i ; float inexact )) (for*((z zeros) (p zeros)) (printf "(~a)^(~a) = ~s~%" z p (with-handlers [(exn:fail:contract:divide-by-zero? exn-message)] (expt z p))))
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
#FormulaOne
FormulaOne
  // First, let's give some type-variables some values: Nationality = Englishman | Swede | Dane | Norwegian | German Colour = Red | Green | Yellow | Blue | White Cigarette = PallMall | Dunhill | BlueMaster | Blend | Prince Domestic = Dog | Bird | Cat | Zebra | Horse Beverage = Tea | Coffee | Milk | Beer | Water HouseRow = First | Second | Third | Fourth | Fifth   { We use injections to make the array-elements unique. Example: 'Pet' is an array of unique elements of type 'Domestic', indexed by 'Nationality'. In the predicate 'Zebra', we use this injection 'Pet' to define the array-variable 'pet' as a parameter of the 'Zebra'-predicate. The symbol used is the '->>'. 'Nationality->>Domestic' can be read as 'Domestic(Nationality)' in "plain array-speak"; the difference being that the elements are by definition unique (cf. 'injective function').   So, in FormulaOne we use a formula like: 'pet(Swede) = Dog', which simply means that the 'Swede' (type 'Nationality') has a 'pet' (type 'Pet', of type 'Domestic', indexed by 'Nationality'), which appears to be a 'Dog' (type 'Domestic'). Or, one could say that the 'Swede' has been mapped to the 'Dog' (Oh, well...). }   Pet = Nationality->>Domestic Drink = Nationality->>Beverage HouseColour = Nationality->>Colour Smoke = Nationality->>Cigarette HouseOrder = HouseRow->>Nationality   pred Zebra(house_olour::HouseColour, pet::Pet, smoke::Smoke, drink::Drink, house_order::HouseOrder) iff   // For convenience sake, some temporary place_holder variables are used. // An underscore distinguishes them:   house_colour(green_house) = Green & house_colour(white_house) = White & house_colour(yellow_house) = Yellow & smoke(pallmall_smoker) = PallMall & smoke(blend_smoker) = Blend & smoke(dunhill_smoker) = Dunhill & smoke(bluemaster_smoker) = BlueMaster & pet(cat_keeper) = Cat & pet(neighbour_dunhill_smoker) = Horse &   { 2. The English man lives in the red house: } house_colour(Englishman) = Red &   { 3. The Swede has a dog: } pet(Swede) = Dog &   { 4. The Dane drinks tea: } drink(Dane) = Tea &   { 'smoke' and 'drink' are both nouns, like the other variables. One could read the formulas like: 'the colour of the Englishman's house is Red' -> 'the Swede's pet is a dog' -> 'the Dane's drink is tea'. }   { 5. The green house is immediately to the left of the white house. The local predicate 'LeftOf' (see below) determines the house order: } LeftOf(green_house, white_house, house_order) &   { 6. They drink coffee in the green house: } drink(green_house) = Coffee &   { 7. The man who smokes Pall Mall has birds: } pet(pallmall_smoker) = Bird &   { 8. In the yellow house they smoke Dunhill: } smoke(yellow_house) = Dunhill &   { 9. In the middle house (third in the row) they drink milk: } drink(house_order(Third)) = Milk &   {10. The Norwegian lives in the first house: } house_order(First) = Norwegian &   {11. The man who smokes Blend lives in the house next to the house with cats. Another local predicate 'Neighbour' makes them neighbours: } Neighbour(blend_smoker, cat_keeper, house_order) &   {12. In a house next to the house where they have a horse, they smoke Dunhill: } Neighbour(dunhill_smoker, neighbour_dunhill_smoker, house_order) &   {13. The man who smokes Blue Master drinks beer: } drink(bluemaster_smoker) = Beer &   {14. The German smokes Prince: } smoke(German) = Prince &   {15. The Norwegian lives next to the blue house Cf. 10. "The Norwegian lives in the first house", so the blue house is the second house: } house_colour(house_order(Second)) = Blue &   {16. They drink water in a house next to the house where they smoke Blend: } drink(neighbour_blend_smoker) = Water & Neighbour(blend_smoker, neighbour_blend_smoker, house_order)   { A simplified solution would number the houses 1, 2, 3, 4, 5 which makes it easier to order the houses. 'right in the center' would become 3; 'in the first house', 1 But we stick to the original puzzle and use some local predicates. }   local pred Neighbour(neighbour1::Nationality, neighbour2::Nationality, house_order::HouseOrder)iff neighbour1 <> neighbour2 & house_order(house1) = neighbour1 & house_order(house2) = neighbour2 & ( house1 = house2 + 1 | house1 = house2 - 1 )   local pred LeftOf(neighbour1::Nationality, neighbour2::Nationality, house_order::HouseOrder) iff neighbour1 <> neighbour2 & house_order(house1) = neighbour1 & house_order(house2) = neighbour2 & house1 = house2 - 1   { The 'all'-query in FormulaOne: all Zebra(house_colour, pet, smokes, drinks, house_order) gives, of course, only one solution, so it can be replaced by: one Zebra(house_colour, pet, smokes, drinks, house_order) }   // The compacted version:   Nationality = Englishman | Swede | Dane | Norwegian | German Colour = Red | Green | Yellow | Blue | White Cigarette = PallMall | Dunhill | BlueMaster | Blend | Prince Domestic = Dog | Bird | Cat | Zebra | Horse Beverage = Tea | Coffee | Milk | Beer | Water HouseRow = First | Second | Third | Fourth | Fifth   Pet = Nationality->>Domestic Drink = Nationality->>Beverage HouseColour = Nationality->>Colour Smoke = Nationality->>Cigarette HouseOrder = HouseRow->>Nationality   pred Zebra(house_colour::HouseColour, pet::Pet, smoke::Smoke, drink::Drink, house_order::HouseOrder) iff   house-colour(green_house) = Green & house-colour(white_house) = White & house-colour(yellow_house) = Yellow & smoke(pallmall_smoker) = PallMall & smoke(blend_smoker) = Blend & smoke(dunhill_smoker) = Dunhill & smoke(bluemaster_smoker) = BlueMaster & pet(cat_keeper) = Cat & pet(neighbour_dunhill_smoker) = Horse & house_colour(Englishman) = Red & pet(Swede) = Dog & drink(Dane) = Tea & LeftOf(green_house, white_house, house_order) & drink(green_house) = Coffee & pet(pallmall_smoker) = Bird & smoke(yellow_house) = Dunhill & drink(house_order(Third)) = Milk & house_order(First) = Norwegian & Neighbour(blend_smoker, cat_keeper, house_order) & Neighbour(dunhill_smoker, neighbour_dunhill_smoker, house_order) & drink(bluemaster_smoker) = Beer & smoke(German) = Prince & house_colour(house_order(Second)) = Blue & drink(neighbour_blend_smoker) = Water & Neighbour(blend_smoker, neighbour_blend_smoker, house_order)   local pred Neighbour(neighbour1::Nationality, neighbour2::Nationality, house_order::HouseOrder)iff neighbour1 <> neighbour2 & house_order(house1) = neighbour1 & house_order(house2) = neighbour2 & ( house1 = house2 + 1 | house1 = house2 - 1 )   local pred LeftOf(neighbour1::Nationality, neighbour2::Nationality, house_::HouseOrder) iff neighbour1 <> neighbour2 & house_order(house1) = neighbour1 & house_order(house2) = neighbour2 & house1 = house2 - 1  
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>
#HicEst
HicEst
CHARACTER xml*1000, output*1000 READ(ClipBoard) xml   EDIT(Text=xml, Right='<item', Right=5, GetPosition=a, Right='</item>', Left, GetPosition=z) WRITE(Text=output) xml( a : z), $CRLF   i = 1 1 EDIT(Text=xml, SetPosition=i, SePaRators='<>', Right='<price>', Word=1, Parse=price, GetPosition=i, ERror=99) IF(i > 0) THEN WRITE(Text=output, APPend) 'Price element = ', price, $CRLF GOTO 1 ! HicEst does not have a "WHILE" ENDIF   EDIT(Text=xml, SPR='<>', R='<name>', W=1, WordEnd=$CR, APpendTo=output, DO=999) WRITE(ClipBoard) TRIM(output)
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>
#Java
Java
import java.io.StringReader; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource;   public class XMLParser { final static String xmlStr = "<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 priwater</description>" + " </item>" + " </section>" + "</inventory>";   public static void main(String[] args) { try { Document doc = DocumentBuilderFactory.newInstance() .newDocumentBuilder() .parse(new InputSource(new StringReader(xmlStr))); XPath xpath = XPathFactory.newInstance().newXPath(); // 1 System.out.println(((Node) xpath.evaluate( "/inventory/section/item[1]", doc, XPathConstants.NODE)) .getAttributes().getNamedItem("upc")); // 2, 3 NodeList nodes = (NodeList) xpath.evaluate( "/inventory/section/item/price", doc, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) System.out.println(nodes.item(i).getTextContent()); } catch (Exception e) { System.out.println("Error ocurred while parsing XML."); } } }
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.
#J
J
yinyang=:3 :0 radii=. y*1 3 6 ranges=. i:each radii squares=. ,"0/~each ranges circles=. radii ([ >: +/"1&.:*:@])each squares cInds=. ({:radii) +each circles #&(,/)each squares   M=. ' *.' {~ circles (* 1 + 0 >: {:"1)&(_1&{::) squares offset=. 3*y,0 M=. '*' ((_2 {:: cInds) <@:+"1 offset)} M M=. '.' ((_2 {:: cInds) <@:-"1 offset)} M M=. '.' ((_3 {:: cInds) <@:+"1 offset)} M M=. '*' ((_3 {:: cInds) <@:-"1 offset)} M )
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
#D.C3.A9j.C3.A0_Vu
Déjà Vu
Y f: labda y: labda: call y @y f labda x: x @x call   labda f: labda n: if < 1 n: * n f -- n else: 1 set :fac Y   labda f: labda n: if < 1 n: + f - n 2 f -- n else: 1 set :fib Y   !. fac 6 !. fib 6
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 0 1 5 6 14 2 4 7 13 15 3 8 12 16 21 9 11 17 20 22 10 18 19 23 24 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Erlang
Erlang
  -module( zigzag ).   -export( [matrix/1, task/0] ).   matrix( N ) -> {{_X_Y, N}, Proplist} = lists:foldl( fun matrix_as_proplist/2, {{{0, 0}, N}, []}, lists:seq(0, (N * N) - 1) ), [columns( X, Proplist ) || X <- lists:seq(0, N - 1)].   task() -> matrix( 5 ).       columns( Column, Proplist ) -> lists:sort( [Value || {{_X, Y}, Value} <- Proplist, Y =:= Column] ).   matrix_as_proplist( N, {{X_Y, Max}, Acc} ) -> Next = next_indexes( X_Y, Max ), {{Next, Max}, [{X_Y, N} | Acc]}.   next_indexes( {X, Y}, Max ) when Y + 1 =:= Max, (X + Y) rem 2 =:= 0 -> {X + 1, Y - 1}; next_indexes( {X, Y}, Max ) when Y + 1 =:= Max, (X + Y) rem 2 =:= 1 -> {X + 1, Y}; next_indexes( {X, Y}, Max ) when X + 1 =:= Max, (X + Y) rem 2 =:= 0 -> {X, Y + 1}; next_indexes( {X, Y}, Max ) when X + 1 =:= Max, (X + Y) rem 2 =:= 1 -> {X - 1, Y + 1}; next_indexes( {X, 0}, _Max ) when X rem 2 =:= 0 -> {X + 1, 0}; next_indexes( {X, 0}, _Max ) when X rem 2 =:= 1 -> {X - 1, 1}; next_indexes( {0, Y}, _Max ) when Y rem 2 =:= 0 -> {1, Y - 1}; next_indexes( {0, Y}, _Max ) when Y rem 2 =:= 1 -> {0, Y + 1}; next_indexes( {X, Y}, _Max ) when (X + Y) rem 2 =:= 0 -> {X + 1, Y - 1}; next_indexes( {X, Y}, _Max ) when (X + Y) rem 2 =:= 1 -> {X - 1, Y + 1}.  
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
#Oz
Oz
declare Pow5432 = {Pow 5 {Pow 4 {Pow 3 2}}} S = {Int.toString Pow5432} Len = {Length S} in {System.showInfo {List.take S 20}#"..."# {List.drop S Len-20}#" ("#Len#" 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
#PARI.2FGP
PARI/GP
num_first_last_digits(a=5,b=4^3^2,n=20)={ my(L = b*log(a)/log(10), m=Mod(a,10^n)^b); [L\1+1, 10^frac(L)\10^(1-n), lift(m)] \\ where x\y = floor(x/y) but more efficient } print("Length, first and last 20 digits of 5^4^3^2: ", num_first_last_digits()) \\ uses default values a=5, b=4^3^2, n=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
#PureBasic
PureBasic
Procedure.s zeck(n.i) Dim f.i(1) : Define i.i=1, o$ f(0)=1 : f(1)=1 While f(i)<n i+1 : ReDim f(ArraySize(f())+1) : f(i)=f(i-1)+f(i-2) Wend For i=i To 1 Step -1 If n>=f(i) : o$+"1" : n-f(i) : Else : o$+"0" : EndIf Next If Len(o$)>1 : o$=LTrim(o$,"0") : EndIf ProcedureReturn o$ EndProcedure   Define n.i, t$ OpenConsole("Zeckendorf number representation") PrintN(~"\tNr.\tZeckendorf") For n=0 To 20 t$=zeck(n) If FindString(t$,"11") PrintN("Error: n= "+Str(n)+~"\tZeckendorf= "+t$) Break Else PrintN(~"\t"+RSet(Str(n),3," ")+~"\t"+RSet(t$,7," ")) EndIf Next Input()
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#Dafny
Dafny
  datatype Door = Closed | Open   method InitializeDoors(n:int) returns (doors:array<Door>) // Precondition: n must be a valid array size. requires n >= 0 // Postcondition: doors is an array, which is not an alias for any other // object, with a length of n, all of whose elements are Closed. The "fresh" // (non-alias) condition is needed to allow doors to be modified by the // remaining code. ensures doors != null && fresh(doors) && doors.Length == n ensures forall j :: 0 <= j < doors.Length ==> doors[j] == Closed; { doors := new Door[n]; var i := 0; // Invariant: i is always a valid index inside the loop, and all doors less // than i are Closed. These invariants are needed to ensure the second // postcondition. while i < doors.Length invariant i <= doors.Length invariant forall j :: 0 <= j < i ==> doors[j] == Closed; { doors[i] := Closed; i := i + 1; } }   method Main () { var doors := InitializeDoors(100);   var pass := 1; while pass <= doors.Length { var door := pass; while door < doors.Length { doors[door] := if doors[door] == Closed then Open else Closed; door := door + pass; } pass := pass + 1; } var i := 0; while i < doors.Length { print i, " is ", if doors[i] == Closed then "closed\n" else "open\n"; i := i + 1; } }  
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Harbour
Harbour
// Declare and initialize two-dimensional array local arr1 := { { "NITEM", "N", 10, 0 }, { "CONTENT", "C", 60, 0 } } // Create an empty array local arr2 := {} // Declare three-dimensional array local arr3[ 2, 100, 3 ] // Create an array local arr4 := Array( 50 )   // Array can be dynamically resized: arr4 := ASize( arr4, 80 )
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part",   where the imaginary part is the number to be multiplied by i {\displaystyle i} . Task Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. Optional: Show complex conjugation. By definition, the   complex conjugate   of a + b i {\displaystyle a+bi} is a − b i {\displaystyle a-bi} Some languages have complex number libraries available.   If your language does, show the operations.   If your language does not, also show the definition of this type.
#Wren
Wren
import "/complex" for Complex   var x = Complex.new(1, 3) var y = Complex.new(5, 2) System.print("x =  %(x)") System.print("y =  %(y)") System.print("x + y =  %(x + y)") System.print("x - y =  %(x - y)") System.print("x * y =  %(x * y)") System.print("x / y =  %(x / y)") System.print("-x =  %(-x)") System.print("1 / x =  %(x.inverse)") System.print("x* =  %(x.conj)")
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
#Raku
Raku
say ' type n n**n exp(n,n)'; say '-------- -------- -------- --------';   for 0, 0.0, FatRat.new(0), 0e0, 0+0i { printf "%8s  %8s  %8s  %8s\n", .^name, $_, $_**$_, exp($_,$_); }
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
#Red
Red
Red[] print 0 ** 0 print power 0 0 print math [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
#GAP
GAP
leftOf  :=function(setA, vA, setB, vB) local i; for i in [1..4] do if ( setA[i] = vA) and (setB[i+1] = vB) then return true ;fi; od; return false; end;   nextTo  :=function(setA, vA, setB, vB) local i; for i in [1..4] do if ( setA[i] = vA) and (setB[i+1] = vB) then return true ;fi; if ( setB[i] = vB) and (setA[i+1] = vA) then return true ;fi; od; return false; end;     requires := function(setA, vA, setB, vB) local i; for i in [1..5] do if ( setA[i] = vA) and (setB[i] = vB) then return true ;fi; od; return false; end;     pcolors :=PermutationsList(["white" ,"yellow" ,"blue" ,"red" ,"green"]); pcigars :=PermutationsList(["blends", "pall_mall", "prince", "bluemasters", "dunhill"]); pnats:=PermutationsList(["german", "swedish", "british", "norwegian", "danish"]); pdrinks :=PermutationsList(["beer", "water", "tea", "milk", "coffee"]); ppets  :=PermutationsList(["birds", "cats", "horses", "fish", "dogs"]);     for colors in pcolors do if not (leftOf(colors,"green",colors,"white")) then continue ;fi; for nats in pnats do if not (requires(nats,"british",colors,"red")) then continue ;fi; if not (nats[1]="norwegian") then continue ;fi; if not (nextTo(nats,"norwegian",colors,"blue")) then continue ;fi; for pets in ppets do if not (requires(nats,"swedish",pets,"dogs")) then continue ;fi; for drinks in pdrinks do if not (drinks[3]="milk") then continue ;fi; if not (requires(colors,"green",drinks,"coffee")) then continue ;fi; if not (requires(nats,"danish",drinks,"tea")) then continue ;fi; for cigars in pcigars do if not (nextTo(pets,"horses",cigars,"dunhill")) then continue ;fi; if not (requires(cigars,"pall_mall",pets,"birds")) then continue ;fi; if not (nextTo(cigars,"blends",drinks,"water")) then continue ;fi; if not (nextTo(cigars,"blends",pets,"cats")) then continue ;fi; if not (requires(nats,"german",cigars,"prince")) then continue ;fi; if not (requires(colors,"yellow",cigars,"dunhill")) then continue ;fi; if not (requires(cigars,"bluemasters",drinks,"beer")) then continue ;fi; Print(colors,"\n"); Print(nats,"\n"); Print(drinks,"\n"); Print(pets,"\n"); Print(cigars,"\n"); od;od;od;od;od;  
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>
#JavaScript
JavaScript
//create XMLDocument object from file var xhr = new XMLHttpRequest(); xhr.open('GET', 'file.xml', false); xhr.send(null); var doc = xhr.responseXML;   //get first <item> element var firstItem = doc.evaluate( '//item[1]', doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue; alert( firstItem.textContent );   //output contents of <price> elements var prices = doc.evaluate( '//price', doc, null, XPathResult.ANY_TYPE, null ); for( var price = prices.iterateNext(); price != null; price = prices.iterateNext() ) { alert( price.textContent ); }   //add <name> elements to array var names = doc.evaluate( '//name', doc, null, XPathResult.ANY_TYPE, null); var namesArray = []; for( var name = names.iterateNext(); name != null; name = names.iterateNext() ) { namesArray.push( name ); } alert( namesArray );
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.
#Java
Java
package org.rosettacode.yinandyang;   import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel;   public class YinYangGenerator { private final int size;   public YinYangGenerator(final int size) { this.size = size; }   /** * Draw a yin yang symbol on the given graphics context. */ public void drawYinYang(final Graphics graphics) { // Preserve the color for the caller final Color colorSave = graphics.getColor();   graphics.setColor(Color.WHITE); // Use fillOval to draw a filled in circle graphics.fillOval(0, 0, size-1, size-1);   graphics.setColor(Color.BLACK); // Use fillArc to draw part of a filled in circle graphics.fillArc(0, 0, size-1, size-1, 270, 180); graphics.fillOval(size/4, size/2, size/2, size/2);   graphics.setColor(Color.WHITE); graphics.fillOval(size/4, 0, size/2, size/2); graphics.fillOval(7*size/16, 11*size/16, size/8, size/8);   graphics.setColor(Color.BLACK); graphics.fillOval(7*size/16, 3*size/16, size/8, size/8); // Use drawOval to draw an empty circle for the outside border graphics.drawOval(0, 0, size-1, size-1);   // Restore the color for the caller graphics.setColor(colorSave); }   /** * Create an image containing a yin yang symbol. */ public Image createImage(final Color bg) { // A BufferedImage creates the image in memory final BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB); // Get the graphics object for the image; note in many // applications you actually use Graphics2D for the // additional API calls final Graphics graphics = image.getGraphics(); // Color in the background of the image graphics.setColor(bg); graphics.fillRect(0,0,size,size); drawYinYang(graphics); return image; }   public static void main(final String args[]) { final int size = Integer.parseInt(args[0]); final YinYangGenerator generator = new YinYangGenerator(size);   final JFrame frame = new JFrame("Yin Yang Generator"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); final Image yinYang = generator.createImage(frame.getBackground()); // Use JLabel to display an image frame.add(new JLabel(new ImageIcon(yinYang))); frame.pack(); frame.setVisible(true); } }
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#E
E
def y := fn f { fn x { x(x) }(fn y { f(fn a { y(y)(a) }) }) } def fac := fn f { fn n { if (n<2) {1} else { n*f(n-1) } }} def fib := fn f { fn n { if (n == 0) {0} else if (n == 1) {1} else { f(n-1) + f(n-2) } }}
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 0 1 5 6 14 2 4 7 13 15 3 8 12 16 21 9 11 17 20 22 10 18 19 23 24 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#ERRE
ERRE
PROGRAM ZIG_ZAG   !$DYNAMIC DIM ARRAY%[0,0]   BEGIN SIZE%=5  !$DIM ARRAY%[SIZE%-1,SIZE%-1]   I%=1 J%=1 FOR E%=0 TO SIZE%^2-1 DO ARRAY%[I%-1,J%-1]=E% IF ((I%+J%) AND 1)=0 THEN IF J%<SIZE% THEN J%+=1 ELSE I%+=2 END IF IF I%>1 THEN I%-=1 END IF ELSE IF I%<SIZE% THEN I%+=1 ELSE J%+=2 END IF IF J%>1 THEN J%-=1 END IF END IF END FOR   FOR ROW%=0 TO SIZE%-1 DO FOR COL%=0 TO SIZE%-1 DO WRITE("###";ARRAY%[ROW%,COL%];) END FOR PRINT END FOR END PROGRAM
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
#Pascal
Pascal
program GMP_Demo;   uses math, gmp;   var a: mpz_t; out: pchar; len: longint; i: longint;   begin mpz_init_set_ui(a, 5); mpz_pow_ui(a, a, 4 ** (3 ** 2)); len := mpz_sizeinbase(a, 10); writeln('GMP says size is: ', len); out := mpz_get_str(NIL, 10, a); writeln('Actual size is: ', length(out)); write('Digits: '); for i := 0 to 19 do write(out[i]); write ('...'); for i := len - 20 to len do write(out[i]); writeln; 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
#Python
Python
def fib(): memo = [1, 2] while True: memo.append(sum(memo)) yield memo.pop(0)   def sequence_down_from_n(n, seq_generator): seq = [] for s in seq_generator(): seq.append(s) if s >= n: break return seq[::-1]   def zeckendorf(n): if n == 0: return [0] seq = sequence_down_from_n(n, fib) digits, nleft = [], n for s in seq: if s <= nleft: digits.append(1) nleft -= s else: digits.append(0) assert nleft == 0, 'Check all of n is accounted for' assert sum(x*y for x,y in zip(digits, seq)) == n, 'Assert digits are correct' while digits[0] == 0: # Remove any zeroes padding L.H.S. digits.pop(0) return digits   n = 20 print('Fibonacci digit multipliers: %r' % sequence_down_from_n(n, fib)) for i in range(n + 1): print('%3i: %8s' % (i, ''.join(str(d) for d in zeckendorf(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.
#Dart
Dart
main() { for (var k = 1, x = new List(101); k <= 100; k++) { for (int i = k; i <= 100; i += k) x[i] = !x[i]; if (x[k]) print("$k 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)
#Haskell
Haskell
import Data.Array.IO   main = do arr <- newArray (1,10) 37 :: IO (IOArray Int Int) a <- readArray arr 1 writeArray arr 1 64 b <- readArray arr 1 print (a,b)
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part",   where the imaginary part is the number to be multiplied by i {\displaystyle i} . Task Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. Optional: Show complex conjugation. By definition, the   complex conjugate   of a + b i {\displaystyle a+bi} is a − b i {\displaystyle a-bi} Some languages have complex number libraries available.   If your language does, show the operations.   If your language does not, also show the definition of this type.
#XPL0
XPL0
include c:\cxpl\codes;   func real CAdd(A, B, C); \Return complex sum of two complex numbers real A, B, C; [C(0):= A(0) + B(0); C(1):= A(1) + B(1); return C; ];   func real CMul(A, B, C); \Return complex product of two complex numbers real A, B, C; [C(0):= A(0)*B(0) - A(1)*B(1); C(1):= A(1)*B(0) + A(0)*B(1); return C; ];   func real CNeg(A, C); \Return negative of a complex number real A, C; [C(0):= -A(0); C(1):= -A(1); return C; ];   func real CInv(A, C); \Return inversion (reciprical) of complex number real A, C; real D; [D:= sq(A(0)) + sq(A(1)); C(0):= A(0)/D; C(1):=-A(1)/D; return C; ];   func real Conj(A, C); \Return conjugate of a complex number real A, C; [C(0):= A(0); C(1):=-A(1); return C; ];   proc COut(D, A); \Output a complex number to specified device int D; real A; [RlOut(D, A(0)); Text(D, if A(1)>=0.0 then " +" else " -"); RlOut(D, abs(A(1))); ChOut(D, ^i); ];   real U, V, W(2); [Format(2,2); U:= [1.0, 1.0]; V:= [3.14, 1.2]; COut(0, CAdd(U,V,W)); CrLf(0); COut(0, CMul(U,V,W)); CrLf(0); COut(0, CNeg(U,W)); CrLf(0); COut(0, CInv(U,W)); CrLf(0); COut(0, Conj(U,W)); CrLf(0); ]
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part",   where the imaginary part is the number to be multiplied by i {\displaystyle i} . Task Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. Optional: Show complex conjugation. By definition, the   complex conjugate   of a + b i {\displaystyle a+bi} is a − b i {\displaystyle a-bi} Some languages have complex number libraries available.   If your language does, show the operations.   If your language does not, also show the definition of this type.
#Yabasic
Yabasic
rem ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ rem CADDI/CADDR addition of complex numbers Z1 + Z2 with Z1 = a1 + b1 *i Z2 = a2 + b2*i rem CADDI returns imaginary part and CADDR the real part rem ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ export sub caddi( a1 , b1 , a2 , b2) return (b1 + b2) end sub export sub caddr( a1 , b1 , a2 , b2) return (a1 + a2) end sub   rem ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ rem CDIVI/CDIVR division of complex numbers Z1 / Z2 with Z1 = r + s *i Z2 = t + u*i rem CDIVI returns imaginary part and CDIVR the real part rem ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ export sub cdivi(r,s,t,u) return ((s*t- u*r) / (t^2 + u^2)) end sub export sub cdivr( r , s , t , u) return ((r*t- s*u) / (t^2 + u^2)) end sub   rem ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ rem CMULI/CMULR multiplication of complex numbers Z1 * Z2, with Z1 = r + s *i Z2 = t + u*i rem CMULI returns imaginary part and CMULR the real part rem ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ export sub cmuli( r , s , t , u) return (r * u + s * t) end sub export sub cmulr( r , s , t , u) return (r * t - s * u) end sub   rem ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ rem CSUBI/CSUBR subtraction of complex numbers Z1 - Z2 with Z1 = a1 + b1 *i Z2 = a2 + b2*i rem CSUBI returns imaginary part and CSUBR the real part rem ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ export sub csubi( a1 , b1 , a2 , b2) return (b1 - b2) end sub export sub csubr( a1 , b1 , a2 , b2) return (a1 - a2) end sub   if (peek$("library") = "main") then print "Example: Z1 + Z2 with Z1 = 3 +2i , Z2 = 1-3i: Z1 + Z2 = 4 -1i" print caddr(3,2,1,-2), "/", caddi(3,2,1,-3) // 4/-1 end if
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
#Relation
Relation
  echo pow(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
#REXX
REXX
/*REXX program shows the results of raising zero to the zeroth power.*/ say '0 ** 0 (zero to the zeroth power) ───► ' 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
#Go
Go
package main   import ( "fmt" "log" "strings" )   // Define some types   type HouseSet [5]*House type House struct { n Nationality c Colour a Animal d Drink s Smoke } type Nationality int8 type Colour int8 type Animal int8 type Drink int8 type Smoke int8   // Define the possible values   const ( English Nationality = iota Swede Dane Norwegian German ) const ( Red Colour = iota Green White Yellow Blue ) const ( Dog Animal = iota Birds Cats Horse Zebra ) const ( Tea Drink = iota Coffee Milk Beer Water ) const ( PallMall Smoke = iota Dunhill Blend BlueMaster Prince )   // And how to print them   var nationalities = [...]string{"English", "Swede", "Dane", "Norwegian", "German"} var colours = [...]string{"red", "green", "white", "yellow", "blue"} var animals = [...]string{"dog", "birds", "cats", "horse", "zebra"} var drinks = [...]string{"tea", "coffee", "milk", "beer", "water"} var smokes = [...]string{"Pall Mall", "Dunhill", "Blend", "Blue Master", "Prince"}   func (n Nationality) String() string { return nationalities[n] } func (c Colour) String() string { return colours[c] } func (a Animal) String() string { return animals[a] } func (d Drink) String() string { return drinks[d] } func (s Smoke) String() string { return smokes[s] } func (h House) String() string { return fmt.Sprintf("%-9s  %-6s  %-5s  %-6s  %s", h.n, h.c, h.a, h.d, h.s) } func (hs HouseSet) String() string { lines := make([]string, 0, len(hs)) for i, h := range hs { s := fmt.Sprintf("%d  %s", i, h) lines = append(lines, s) } return strings.Join(lines, "\n") }   // Simple brute force solution   func simpleBruteForce() (int, HouseSet) { var v []House for n := range nationalities { for c := range colours { for a := range animals { for d := range drinks { for s := range smokes { h := House{ n: Nationality(n), c: Colour(c), a: Animal(a), d: Drink(d), s: Smoke(s), } if !h.Valid() { continue } v = append(v, h) } } } } } n := len(v) log.Println("Generated", n, "valid houses")   combos := 0 first := 0 valid := 0 var validSet HouseSet for a := 0; a < n; a++ { if v[a].n != Norwegian { // Condition 10: continue } for b := 0; b < n; b++ { if b == a { continue } if v[b].anyDups(&v[a]) { continue } for c := 0; c < n; c++ { if c == b || c == a { continue } if v[c].d != Milk { // Condition 9: continue } if v[c].anyDups(&v[b], &v[a]) { continue } for d := 0; d < n; d++ { if d == c || d == b || d == a { continue } if v[d].anyDups(&v[c], &v[b], &v[a]) { continue } for e := 0; e < n; e++ { if e == d || e == c || e == b || e == a { continue } if v[e].anyDups(&v[d], &v[c], &v[b], &v[a]) { continue } combos++ set := HouseSet{&v[a], &v[b], &v[c], &v[d], &v[e]} if set.Valid() { valid++ if valid == 1 { first = combos } validSet = set //return set } } } } } } log.Println("Tested", first, "different combinations of valid houses before finding solution") log.Println("Tested", combos, "different combinations of valid houses in total") return valid, validSet }   // anyDups returns true if h as any duplicate attributes with any of the specified houses func (h *House) anyDups(list ...*House) bool { for _, b := range list { if h.n == b.n || h.c == b.c || h.a == b.a || h.d == b.d || h.s == b.s { return true } } return false }   func (h *House) Valid() bool { // Condition 2: if h.n == English && h.c != Red || h.n != English && h.c == Red { return false } // Condition 3: if h.n == Swede && h.a != Dog || h.n != Swede && h.a == Dog { return false } // Condition 4: if h.n == Dane && h.d != Tea || h.n != Dane && h.d == Tea { return false } // Condition 6: if h.c == Green && h.d != Coffee || h.c != Green && h.d == Coffee { return false } // Condition 7: if h.a == Birds && h.s != PallMall || h.a != Birds && h.s == PallMall { return false } // Condition 8: if h.c == Yellow && h.s != Dunhill || h.c != Yellow && h.s == Dunhill { return false } // Condition 11: if h.a == Cats && h.s == Blend { return false } // Condition 12: if h.a == Horse && h.s == Dunhill { return false } // Condition 13: if h.d == Beer && h.s != BlueMaster || h.d != Beer && h.s == BlueMaster { return false } // Condition 14: if h.n == German && h.s != Prince || h.n != German && h.s == Prince { return false } // Condition 15: if h.n == Norwegian && h.c == Blue { return false } // Condition 16: if h.d == Water && h.s == Blend { return false } return true }   func (hs *HouseSet) Valid() bool { ni := make(map[Nationality]int, 5) ci := make(map[Colour]int, 5) ai := make(map[Animal]int, 5) di := make(map[Drink]int, 5) si := make(map[Smoke]int, 5) for i, h := range hs { ni[h.n] = i ci[h.c] = i ai[h.a] = i di[h.d] = i si[h.s] = i } // Condition 5: if ci[Green]+1 != ci[White] { return false } // Condition 11: if dist(ai[Cats], si[Blend]) != 1 { return false } // Condition 12: if dist(ai[Horse], si[Dunhill]) != 1 { return false } // Condition 15: if dist(ni[Norwegian], ci[Blue]) != 1 { return false } // Condition 16: if dist(di[Water], si[Blend]) != 1 { return false }   // Condition 9: (already tested elsewhere) if hs[2].d != Milk { return false } // Condition 10: (already tested elsewhere) if hs[0].n != Norwegian { return false } return true }   func dist(a, b int) int { if a > b { return a - b } return b - a }   func main() { log.SetFlags(0) n, sol := simpleBruteForce() fmt.Println(n, "solution found") fmt.Println(sol) }
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>
#Julia
Julia
using LibExpat   xdoc = raw"""<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> """   debracket(s) = replace(s, r".+\>(.+)\<.+" => s"\1")   etree = xp_parse(xdoc) firstshow = LibExpat.find(etree, "//item")[1] println("The first item's node XML entry is:\n", firstshow, "\n\n")   prices = LibExpat.find(etree, "//price") println("Prices:") for p in prices println("\t", debracket(string(p))) end println("\n")   namearray = LibExpat.find(etree, "//name") println("Array of names of items:\n\t", map(s -> debracket(string(s)), namearray))  
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>
#Kotlin
Kotlin
// version 1.1.3   import javax.xml.parsers.DocumentBuilderFactory import org.xml.sax.InputSource import java.io.StringReader import javax.xml.xpath.XPathFactory import javax.xml.xpath.XPathConstants import org.w3c.dom.Node import org.w3c.dom.NodeList   val 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> """   fun main(args: Array<String>) { val dbFactory = DocumentBuilderFactory.newInstance() val dBuilder = dbFactory.newDocumentBuilder() val xmlInput = InputSource(StringReader(xml)) val doc = dBuilder.parse(xmlInput) val xpFactory = XPathFactory.newInstance() val xPath = xpFactory.newXPath()   val qNode = xPath.evaluate("/inventory/section/item[1]", doc, XPathConstants.NODE) as Node val upc = qNode.attributes.getNamedItem("upc") val stock = qNode.attributes.getNamedItem("stock") println("For the first item : upc = ${upc.textContent} and stock = ${stock.textContent}")   val qNodes = xPath.evaluate("/inventory/section/item/price", doc, XPathConstants.NODESET) as NodeList print("\nThe prices of each item are : ") for (i in 0 until qNodes.length) print("${qNodes.item(i).textContent} ") println()   val qNodes2 = xPath.evaluate("/inventory/section/item/name", doc, XPathConstants.NODESET) as NodeList val names = Array<String>(qNodes2.length) { qNodes2.item(it).textContent } println("\nThe names of each item are as follows :") println(" ${names.joinToString("\n ")}") }
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#JavaScript
JavaScript
  function Arc(posX,posY,radius,startAngle,endAngle,color){//Angle in radians. this.posX=posX; this.posY=posY; this.radius=radius; this.startAngle=startAngle; this.endAngle=endAngle; this.color=color; } //0,0 is the top left of the screen var YingYang=[ new Arc(0.5,0.5,1,0.5*Math.PI,1.5*Math.PI,"white"),//Half white semi-circle new Arc(0.5,0.5,1,1.5*Math.PI,0.5*Math.PI,"black"),//Half black semi-circle new Arc(0.5,0.25,.5,0,2*Math.PI,"black"),//black circle new Arc(0.5,0.75,.5,0,2*Math.PI,"white"),//white circle new Arc(0.5,0.25,1/6,0,2*Math.PI,"white"),//small white circle new Arc(0.5,0.75,1/6,0,2*Math.PI,"black")//small black circle ] //Ying Yang is DONE! //Now we'll have to draw it. //We'll draw it in a matrix that way we can get results graphically or by text! function Array2D(width,height){ this.height=height; this.width=width; this.array2d=[]; for(var i=0;i<this.height;i++){ this.array2d.push(new Array(this.width)); } } Array2D.prototype.resize=function(width,height){//This is expensive //nheight and nwidth is the difference of the new and old height var nheight=height-this.height,nwidth=width-this.width; if(nwidth>0){ for(var i=0;i<this.height;i++){ if(i<height) Array.prototype.push.apply(this.array2d[i],new Array(nwidth)); } } else if(nwidth<0){ for(var i=0;i<this.height;i++){ if(i<height) this.array2d[i].splice(width,nwidth); } } if(nheight>0){ Array.prototype.push.apply(this.array2d,new Array(width)); } else if(nheight<0){ this.array2d.splice(height,nheight) } } Array2D.prototype.loop=function(callback){ for(var i=0;i<this.height;i++) for(var i2=0;i2<this.width;i++) callback.call(this,this.array2d[i][i2],i,i2);   } var mat=new Array2D(100,100);//this sounds fine; YingYang[0]; //In construction.  
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
#EchoLisp
EchoLisp
  ;; Ref : http://www.ece.uc.edu/~franco/C511/html/Scheme/ycomb.html   (define Y (lambda (X) ((lambda (procedure) (X (lambda (arg) ((procedure procedure) arg)))) (lambda (procedure) (X (lambda (arg) ((procedure procedure) arg)))))))   ; Fib (define Fib* (lambda (func-arg) (lambda (n) (if (< n 2) n (+ (func-arg (- n 1)) (func-arg (- n 2))))))) (define fib (Y Fib*)) (fib 6) → 8   ; Fact (define F* (lambda (func-arg) (lambda (n) (if (zero? n) 1 (* n (func-arg (- n 1))))))) (define fact (Y F*))   (fact 10) → 3628800  
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
#Euphoria
Euphoria
function zigzag(integer size) sequence s integer i, j, d, max s = repeat(repeat(0,size),size) i = 1 j = 1 d = -1 max = size*size for n = 1 to floor(max/2)+1 do s[i][j] = n s[size-i+1][size-j+1] = max-n+1 i += d j-= d if i < 1 then i += 1 d = -d elsif j < 1 then j += 1 d = -d end if end for return s end function   ? zigzag(5)
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
#Perl
Perl
use Math::BigInt; my $x = Math::BigInt->new('5') ** Math::BigInt->new('4') ** Math::BigInt->new('3') ** Math::BigInt->new('2'); my $y = "$x"; printf("5**4**3**2 = %s...%s and has %i digits\n", substr($y,0,20), substr($y,-20), length($y));
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
#Phix
Phix
with javascript_semantics include mpfr.e atom t0 = time() mpz res = mpz_init() mpz_ui_pow_ui(res,5,power(4,power(3,2))) string s = mpz_get_short_str(res), e = elapsed(time()-t0) printf(1,"5^4^3^2 = %s (%s)\n", {s,e})
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
#Quackery
Quackery
[ 2 base put echo base release ] is binecho ( n --> )   [ 0 swap ' [ 2 1 ] [ 2dup 0 peek < iff [ behead drop ] done dup 0 peek over 1 peek + swap join again ] witheach [ rot 1 << unrot 2dup < iff drop else [ - dip [ 1 | ] ] ] drop ] is n->z ( n --> z )   [ 0 temp put 1 1 rot [ dup while dup 1 & if [ over temp tally ] 1 >> dip [ tuck + ] again ] 2drop drop temp take ] is z->n ( z --> n )   21 times [ i^ dup echo say " -> " n->z dup binecho say " -> " z->n echo cr ]
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.
#Dc
Dc
  ## NB: This code uses the dc command "r" via register "r". ## You may comment out the unwanted version. [SxSyLxLy]sr # this should work with every "dc" [r]sr # GNU dc can exchange top 2 stack values by "r" ## Now use "lrx" instead of "r" ...   0k # we work without decimal places [q]sq # useful e.g. as loop termination   ## (x)(y)>R == if (y)>(x) eval R ## isle x y --> (x <= y) [ [1q]S. [ !<. 0 ]x s.L. ]sl ## l: isle   [ 100 llx ]sL ## L: isle100   ## for initcode condcode incrcode body ## [1] [2] [3] [4] [ [q]S. 4:. 3:. 2:. 1:. 1;.x [2;.x 0=. 4;.x 3;.x 0;.x]d0:.x Os.L.o ]sf ## f: for ##----------------------------------------------------------------------------   ## for( i=1 ; i<=100 ; ++i ) { ## door[i] = 0; ## } #[init ...]P []ps- [1si] [li lLx] [li1+si] [ li 0:d ]lfx   ## for( s=1 ; s<=100 ; ++s ) { ## for( i=s ; i<=100 ; i+=s ) { ## door[i] = 1 - door[i] ## } ## } [1ss] [ls lLx] [ls1+ss] [ #[step ]P lsn [ ...]ps- [lssi] [li lLx] [lils+si] [ 1 li;d - li:d ]lfx ]lfx   ## long output: ## for( i=1 ; i<=100 ; ++i ) { ## print "door #", i, " is ", (door[i] ? "open" : "closed")), NL ## } [ [1si] [li lLx] [li1+si] [ [door #]P li n [ is ]P [closed] [open] li;d 0=r lrx s- n [.]ps- ]lfx ]   ## terse output: ## for( i=1 ; i<=100 ; ++i ) { ## if( door[i] ) { ## print i ## } ## print NL ## } [ [1si] [li lLx] [li1+si] [ [] [ [ ]n lin ] li;d 0=r lrx s- x ]lfx []ps- ]   lrx # comment out for the long output version s- x #[stack rest...]P []ps- f  
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)
#hexiscript
hexiscript
let a arr 2 # fixed size let a[0] 123 # index starting at 0 let a[1] "test" # can hold different types   println a[1]
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part",   where the imaginary part is the number to be multiplied by i {\displaystyle i} . Task Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. Optional: Show complex conjugation. By definition, the   complex conjugate   of a + b i {\displaystyle a+bi} is a − b i {\displaystyle a-bi} Some languages have complex number libraries available.   If your language does, show the operations.   If your language does not, also show the definition of this type.
#zkl
zkl
var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) (GSL.Z(3,4) + GSL.Z(1,2)).println(); // (4.00+6.00i) (GSL.Z(3,4) - GSL.Z(1,2)).println(); // (2.00+2.00i) (GSL.Z(3,4) * GSL.Z(1,2)).println(); // (-5.00+10.00i) (GSL.Z(3,4) / GSL.Z(1,2)).println(); // (2.20-0.40i) (GSL.Z(1,0) / GSL.Z(1,1)).println(); // (0.50-0.50i) // inversion (-GSL.Z(3,4)).println(); // (-3.00-4.00i) GSL.Z(3,4).conjugate().println(); // (3.00-4.00i)
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part",   where the imaginary part is the number to be multiplied by i {\displaystyle i} . Task Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. Optional: Show complex conjugation. By definition, the   complex conjugate   of a + b i {\displaystyle a+bi} is a − b i {\displaystyle a-bi} Some languages have complex number libraries available.   If your language does, show the operations.   If your language does not, also show the definition of this type.
#zonnon
zonnon
  module Numbers; type {public,immutable} Complex = record re,im: real; end Complex;   operator {public} "+" (a,b: Complex): Complex; var r: Complex; begin r.re := a.re + b.re; r.im := a.im + b.im; return r end "+";   operator {public} "-" (a,b: Complex): Complex; var r: Complex; begin r.re := a.re - b.re; r.im := a.im - b.im; return r end "-";   operator {public} "*" (a,b: Complex): Complex; var r: Complex; begin r.re := a.re*b.re - a.im*b.im; r.im := a.re*b.im + a.im*b.re; return r end "*";   operator {public} "/" (a,b: Complex): Complex; var r: Complex; d: real; begin d := b.re * b.re + b.im * b.im; r.re := (a.re * b.re + a.im * b.im)/d; r.im := (a.im * b.re - a.re * b.im)/d; return r end "/";   operator {public} "-" (a: Complex): Complex; begin a.im := -1 * a.im; return a end "-";   operator {public} "~" (a: Complex): Complex; var d: real; c: Complex; begin d := a.re * a.re + a.im * a.im; c.re := a.re/d; c.im := (-1.0 * a.im)/d; return c end "~";   end Numbers.     module Main; import Numbers;   var a,b,c: Numbers.Complex;   procedure Writeln(c: Numbers.Complex); begin writeln("(",c.re:4:2,";",c.im:4:2,"i)"); end Writeln;   procedure NewComplex(x,y: real): Numbers.Complex; var r: Numbers.Complex; begin r.re := x;r.im := y; return r end NewComplex;   begin a := NewComplex(1.5,3.0); b := NewComplex(1.0,1.0); Writeln(a + b); Writeln(a - b); Writeln(a * b); Writeln(a / b); Writeln(-a); Writeln(~b); end Main.  
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
#Ring
Ring
  x = 0 y = 0 z = pow(x,y) see "z=" + z + nl # z=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
#Ruby
Ruby
require 'bigdecimal'   [0, 0.0, Complex(0), Rational(0), BigDecimal("0")].each do |n| printf "%10s: ** -> %s\n" % [n.class, n**n] 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
#Rust
Rust
fn main() { println!("{}",0u32.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
#Haskell
Haskell
module Main where   import Control.Applicative ((<$>), (<*>)) import Control.Monad (foldM, forM_) import Data.List ((\\))   -- types data House = House { color :: Color -- <trait> :: House -> <Trait> , man :: Man , pet :: Pet , drink :: Drink , smoke :: Smoke } deriving (Eq, Show)   data Color = Red | Green | Blue | Yellow | White deriving (Eq, Show, Enum, Bounded)   data Man = Eng | Swe | Dan | Nor | Ger deriving (Eq, Show, Enum, Bounded)   data Pet = Dog | Birds | Cats | Horse | Zebra deriving (Eq, Show, Enum, Bounded)   data Drink = Coffee | Tea | Milk | Beer | Water deriving (Eq, Show, Enum, Bounded)   data Smoke = PallMall | Dunhill | Blend | BlueMaster | Prince deriving (Eq, Show, Enum, Bounded)   type Solution = [House]   main :: IO () main = do forM_ solutions $ \sol -> mapM_ print sol >> putStrLn "----" putStrLn "No More Solutions"     solutions :: [Solution] solutions = filter finalCheck . map reverse $ foldM next [] [1..5] where -- NOTE: list of houses is generated in reversed order next :: Solution -> Int -> [Solution] next sol pos = [h:sol | h <- newHouses sol, consistent h pos]     newHouses :: Solution -> Solution newHouses sol = -- all combinations of traits not yet used House <$> new color <*> new man <*> new pet <*> new drink <*> new smoke where new trait = [minBound ..] \\ map trait sol -- :: [<Trait>]     consistent :: House -> Int -> Bool consistent house pos = and -- consistent with the rules: [ man `is` Eng <=> color `is` Red -- 2 , man `is` Swe <=> pet `is` Dog -- 3 , man `is` Dan <=> drink `is` Tea -- 4 , color `is` Green <=> drink `is` Coffee -- 6 , pet `is` Birds <=> smoke `is` PallMall -- 7 , color `is` Yellow <=> smoke `is` Dunhill -- 8 , const (pos == 3) <=> drink `is` Milk -- 9 , const (pos == 1) <=> man `is` Nor -- 10 , drink `is` Beer <=> smoke `is` BlueMaster -- 13 , man `is` Ger <=> smoke `is` Prince -- 14 ] where infix 4 <=> p <=> q = p house == q house -- both True or both False     is :: Eq a => (House -> a) -> a -> House -> Bool (trait `is` value) house = trait house == value     finalCheck :: [House] -> Bool finalCheck solution = and -- fulfills the rules: [ (color `is` Green) `leftOf` (color `is` White) -- 5 , (smoke `is` Blend ) `nextTo` (pet `is` Cats ) -- 11 , (smoke `is` Dunhill) `nextTo` (pet `is` Horse) -- 12 , (color `is` Blue ) `nextTo` (man `is` Nor ) -- 15 , (smoke `is` Blend ) `nextTo` (drink `is` Water) -- 16 ] where nextTo :: (House -> Bool) -> (House -> Bool) -> Bool nextTo p q = leftOf p q || leftOf q p leftOf p q | (_:h:_) <- dropWhile (not . p) solution = q h | otherwise = False
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>
#Ksh
Ksh
  #!/bin/ksh   # Perform XPath queries on a XML Document   # # Variables: # typeset -T Xml_t=( typeset -h 'UPC' upc typeset -i -h 'num in stock' stock=0 typeset -h 'name' name typeset -F2 -h 'price' price typeset -h 'description' description   function init_item { typeset key ; key="$1" typeset val ; val="${2%\<\/${key}*}"   case ${key} in upc) _.upc="${val//@(\D)/}" ;; stock) _.stock="${val//@(\D)/}" ;; name) _.name="${val%\<\/${key}*}" ;; price) _.price="${val}" ;; description) _.description=$(echo ${val}) ;; esac }   function prt_item { print "upc= ${_.upc}" print "stock= ${_.stock}" print "name= ${_.name}" print "price= ${_.price}" print "description= ${_.description}" } )   # # Functions: #     ###### # main # ###### integer i=0 typeset -a Item_t   buff=$(< xmldoc) # read xmldoc item=${buff%%'</item>'*} ; buff=${.sh.match}   while [[ -n ${item} ]]; do Xml_t Item_t[i] item=${item#*'<item'} ; item=$(echo ${item}) for word in ${item}; do if [[ ${word} == *=* ]]; then Item_t[i].init_item ${word%\=*} ${word#*\=} else if [[ ${word} == \<* ]]; then # Beginning key=${word%%\>*} ; key=${key#*\<} val=${word#*\>} fi   [[ ${word} != \<* && ${word} != *\> ]] && val+=" ${word} "   if [[ ${word} == *\> ]]; then # End val+=" ${word%\<${key}\>*}" Item_t[i].init_item "${key}" "${val}" fi fi done (( i++ )) item=${buff#*'</item>'} ; item=${item%%'</item>'*} ; buff=${.sh.match} done   print "First Item element:" Item_t[0].prt_item   typeset -a names printf "\nList of prices:\n" for ((i=0; i<${#Item_t[*]}-1; i++)); do print ${Item_t[i].price} names[i]=${Item_t[i].name} done   printf "\nArray of names:\n" for (( i=0; i<${#names[*]}; i++)); do print "names[$i] = ${names[i]}" done
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>
#Lasso
Lasso
// makes extracting attribute values easier define xml_attrmap(in::xml_namedNodeMap_attr) => { local(out = map) with attr in #in do #out->insert(#attr->name = #attr->value) return #out }   local( text = '<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> ', xml = xml(#text) )   local( items = #xml -> extract('//item'), firstitem = #items -> first, itemattr = xml_attrmap(#firstitem -> attributes), newprices = array )   '<strong>First item:</strong><br /> UPC: ' #itemattr -> find('upc') ' (stock: ' #itemattr -> find('stock') ')<br />' #firstitem -> extractone('name') -> nodevalue ' [' #firstitem -> extractone('price') -> nodevalue '] (' #firstitem -> extractone('description') -> nodevalue ')<br /><br />'   with item in #items let name = #item -> extractone('name') -> nodevalue let price = #item -> extractone('price') -> nodevalue do { #newprices -> insert(#name + ': ' + (decimal(#price) * 1.10) -> asstring(-precision = 2) + ' (' + #price + ')') } '<strong>Adjusted prices:</strong><br />' #newprices -> join('<br />') '<br /><br />' '<strong>Array with all names:</strong><br />' #xml -> extract('//name') -> asstaticarray
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.
#jq
jq
  def svg: "<svg width='100%' height='100%' version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'>" ;   def draw_yinyang(x; scale): "<use xlink:href='#y' transform='translate(\(x),\(x)) scale(\(scale))'/>";   def define_yinyang: "<defs> <g id='y'> <circle cx='0' cy='0' r='200' stroke='black' fill='white' stroke-width='1'/> <path d='M0 -200 A 200 200 0 0 0 0 200 100 100 0 0 0 0 0 100 100 0 0 1 0 -200 z' fill='black'/> <circle cx='0' cy='100' r='33' fill='white'/> <circle cx='0' cy='-100' r='33' fill='black'/> </g> </defs>" ;   def draw: svg, define_yinyang, draw_yinyang(20; .05), draw_yinyang(8 ; .02), "</svg>" ;   draw
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.
#Julia
Julia
function yinyang(n::Int=3) radii = (i * n for i in (1, 3, 6)) ranges = collect(collect(-r:r) for r in radii) squares = collect(collect((x, y) for x in rnge, y in rnge) for rnge in ranges) circles = collect(collect((x, y) for (x,y) in sqrpoints if hypot(x, y) ≤ radius) for (sqrpoints, radius) in zip(squares, radii)) m = Dict((x, y) => ' ' for (x, y) in squares[end]) for (x, y) in circles[end] m[(x, y)] = x > 0 ? '·' : '*' end for (x, y) in circles[end-1] m[(x, y + 3n)] = '*' m[(x, y - 3n)] = '·' end for (x, y) in circles[end-2] m[(x, y + 3n)] = '·' m[(x, y - 3n)] = '*' end return join((join(m[(x, y)] for x in reverse(ranges[end])) for y in ranges[end]), '\n') end   println(yinyang(4))  
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#Eero
Eero
#import <Foundation/Foundation.h>   typedef int (^Func)(int) typedef Func (^FuncFunc)(Func) typedef Func (^RecursiveFunc)(id) // hide recursive typing behind dynamic typing   Func fix(FuncFunc f) Func r(RecursiveFunc g) int s(int x) return g(g)(x) return f(s) return r(r)   int main(int argc, const char *argv[]) autoreleasepool   Func almost_fac(Func f) return (int n | return n <= 1 ? 1 : n * f(n - 1))   Func almost_fib(Func f) return (int n | return n <= 2 ? 1 : f(n - 1) + f(n - 2))   fib := fix(almost_fib) fac := fix(almost_fac)   Log('fib(10) = %d', fib(10)) Log('fac(10) = %d', fac(10))   return 0
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 0 1 5 6 14 2 4 7 13 15 3 8 12 16 21 9 11 17 20 22 10 18 19 23 24 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#F.23
F#
  //Produce a zig zag matrix - Nigel Galloway: April 7th., 2015 let zz l a = let N = Array2D.create l a 0 let rec gng (n, i, g, e) = N.[n,i] <- g match e with | _ when i=a-1 && n=l-1 -> N | 1 when n = l-1 -> gng (n, i+1, g+1, 2) | 2 when i = a-1 -> gng (n+1, i, g+1, 1) | 1 when i = 0 -> gng (n+1, 0, g+1, 2) | 2 when n = 0 -> gng (0, i+1, g+1, 1) | 1 -> gng (n+1, i-1, g+1, 1) | _ -> gng (n-1, i+1, g+1, 2) gng (0, 0, 0, 2)  
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
#PHP
PHP
<?php $y = bcpow('5', bcpow('4', bcpow('3', '2'))); printf("5**4**3**2 = %s...%s and has %d digits\n", substr($y,0,20), substr($y,-20), strlen($y)); ?>
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
#PicoLisp
PicoLisp
(let L (chop (** 5 (** 4 (** 3 2)))) (prinl (head 20 L) "..." (tail 20 L)) (length L) )
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
#R
R
zeckendorf <- function(number) {   # Get an upper limit on Fibonacci numbers needed to cover number indexOfFibonacciNumber <- function(n) { if (n < 1) { 2 } else { Phi <- (1 + sqrt(5)) / 2 invertClosedFormula <- log(n * sqrt(5)) / log(Phi) ceiling(invertClosedFormula) } }   upperLimit <- indexOfFibonacciNumber(number)   # Return the sequence as digits, sorted descending fibonacciSequenceDigits <- function(n) { fibGenerator <- function(f, ...) { c(f[2], sum(f)) } fibSeq <- Reduce(fibGenerator, 1:n, c(0,1), accumulate=TRUE)   fibNums <- unlist(lapply(fibSeq, head, n=1))   # drop last F0 and F1 and reverse sequence rev(fibNums[-2:-1]) }   digits <- fibonacciSequenceDigits(upperLimit)   isInNumber <- function(digit) { if (number >= digit) { number <<- number - digit 1 } else { 0 } }   zeckSeq <- Map(isInNumber, digits)   # drop leading 0 and convert to String gsub("^0+1", "1", paste(zeckSeq, collapse="")) }   print(unlist(lapply(0:20, zeckendorf)))
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.
#DCL
DCL
  $! doors.com $! Excecute by running @doors at prompt. $ square = 1 $ incr = 3 $ count2 = 0 $ d = 1 $ LOOP2: $ count2 = count2 + 1 $ IF (d .NE. square) $ THEN WRITE SYS$OUTPUT "door ''d' is closed" $ ELSE WRITE SYS$OUTPUT "door ''d' is open" $ square = incr + square $ incr = incr + 2 $ ENDIF $ d = d + 1 $ IF (count2 .LT. 100) THEN GOTO LOOP2  
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)
#HicEst
HicEst
REAL :: n = 3, Astat(n), Bdyn(1, 1)   Astat(2) = 2.22222222 WRITE(Messagebox, Name) Astat(2)   ALLOCATE(Bdyn, 2*n, 3*n) Bdyn(n-1, n) = -123 WRITE(Row=27) Bdyn(n-1, n)   ALIAS(Astat, n-1, last2ofAstat, 2) WRITE(ClipBoard) last2ofAstat ! 2.22222222 0
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part",   where the imaginary part is the number to be multiplied by i {\displaystyle i} . Task Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. Optional: Show complex conjugation. By definition, the   complex conjugate   of a + b i {\displaystyle a+bi} is a − b i {\displaystyle a-bi} Some languages have complex number libraries available.   If your language does, show the operations.   If your language does not, also show the definition of this type.
#ZX_Spectrum_Basic
ZX Spectrum Basic
5 LET complex=2: LET r=1: LET i=2 10 DIM a(complex): LET a(r)=1.0: LET a(i)=1.0 20 DIM b(complex): LET b(r)=PI: LET b(i)=1.2 30 DIM o(complex) 40 REM add 50 LET o(r)=a(r)+b(r) 60 LET o(i)=a(i)+b(i) 70 PRINT "Result of addition is:": GO SUB 1000 80 REM mult 90 LET o(r)=a(r)*b(r)-a(i)*b(i) 100 LET o(i)=a(i)*b(r)+a(r)*b(i) 110 PRINT "Result of multiplication is:": GO SUB 1000 120 REM neg 130 LET o(r)=-a(r) 140 LET o(i)=-a(i) 150 PRINT "Result of negation is:": GO SUB 1000 160 LET denom=a(r)^2+a(i)^2 170 LET o(r)=a(r)/denom 180 LET o(i)=-a(i)/denom 190 PRINT "Result of inversion is:": GO SUB 1000 200 STOP 1000 IF o(i)>=0 THEN PRINT o(r);" + ";o(i);"i": RETURN 1010 PRINT o(r);" - ";-o(i);"i": RETURN  
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
#S-lang
S-lang
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
#Scala
Scala
assert(math.pow(0, 0) == 1, "Scala blunder, should go back to school !")
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
#Scheme
Scheme
(display (expt 0 0)) (newline) (display (expt 0.0 0.0)) (newline) (display (expt 0+0i 0+0i)) (newline)
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
#J
J
ehs=: 5$a:   cr=: (('English';'red') 0 3} ehs);<('Dane';'tea') 0 2}ehs cr=: cr, (('German';'Prince') 0 4}ehs);<('Swede';'dog') 0 1 }ehs   cs=: <('PallMall';'birds') 4 1}ehs cs=: cs, (('yellow';'Dunhill') 3 4}ehs);<('BlueMaster';'beer') 4 2}ehs   lof=: (('coffee';'green')2 3}ehs);<(<'white')3}ehs   next=: <((<'Blend') 4 }ehs);<(<'water')2}ehs next=: next,<((<'Blend') 4 }ehs);<(<'cats')1}ehs next=: next,<((<'Dunhill') 4}ehs);<(<'horse')1}ehs
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>
#LiveCode
LiveCode
put revXMLCreateTree(fld "FieldXML",true,true,false) into xmltree   // task 1 put revXMLEvaluateXPath(xmltree,"//item[1]") into nodepath put revXMLText(xmltree,nodepath,true)   // task 2 put revXMLDataFromXPathQuery(xmltree,"//item/price",,comma)   // task 3 put revXMLDataFromXPathQuery(xmltree,"//name") into namenodes filter namenodes without empty split namenodes using cr put namenodes is an array
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>
#Lua
Lua
require 'lxp' 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>]] local first = true local names, prices = {}, {} p = lxp.new({StartElement = function (parser, name) local a, b, c = parser:pos() --line, offset, pos if name == 'item' and first then print(data:match('.-</item>', c - b + 1)) first = false end if name == 'name' then names[#names+1] = data:match('>(.-)<', c) end if name == 'price' then prices[#prices+1] = data:match('>(.-)<', c) end end})   p:parse(data) p:close()   print('Name: ', table.concat(names, ', ')) print('Price: ', table.concat(prices, ', '))
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.
#Kotlin
Kotlin
// version 1.1.2   import java.awt.Color import java.awt.Graphics import java.awt.Image import java.awt.image.BufferedImage import javax.swing.ImageIcon import javax.swing.JFrame import javax.swing.JPanel import javax.swing.JLabel   class YinYangGenerator { private fun drawYinYang(size: Int, g: Graphics) { with(g) { // Preserve the color for the caller val colorSave = color color = Color.WHITE   // Use fillOval to draw a filled in circle fillOval(0, 0, size - 1, size - 1) color = Color.BLACK   // Use fillArc to draw part of a filled in circle fillArc(0, 0, size - 1, size - 1, 270, 180) fillOval(size / 4, size / 2, size / 2, size / 2) color = Color.WHITE fillOval(size / 4, 0, size / 2, size / 2) fillOval(7 * size / 16, 11 * size / 16, size /8, size / 8) color = Color.BLACK fillOval(7 * size / 16, 3 * size / 16, size / 8, size / 8)   // Use drawOval to draw an empty circle for the outside border drawOval(0, 0, size - 1, size - 1)   // Restore the color for the caller color = colorSave } }   fun createImage(size: Int, bg: Color): Image { // A BufferedImage creates the image in memory val image = BufferedImage(size, size, BufferedImage.TYPE_INT_RGB)   // Get the graphics object for the image val g = image.graphics   // Color in the background of the image g.color = bg g.fillRect(0, 0, size, size) drawYinYang(size, g) return image } }   fun main(args: Array<String>) { val gen = YinYangGenerator() val size = 400 // say val p = JPanel() val yinYang = gen.createImage(size, p.background) p.add(JLabel(ImageIcon(yinYang)))   val size2 = size / 2 // say val yinYang2 = gen.createImage(size2, p.background) p.add(JLabel(ImageIcon(yinYang2)))   val f = JFrame("Big and Small Yin Yang") with (f) { defaultCloseOperation = JFrame.EXIT_ON_CLOSE add(p) pack() isVisible = true } }
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#Ela
Ela
fix = \f -> (\x -> & f (x x)) (\x -> & f (x x))   fac _ 0 = 1 fac f n = n * f (n - 1)   fib _ 0 = 0 fib _ 1 = 1 fib f n = f (n - 1) + f (n - 2)   (fix fac 12, fix fib 12)
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
#Factor
Factor
USING: columns fry kernel make math math.ranges prettyprint sequences sequences.cords sequences.extras ; IN: rosetta-code.zig-zag-matrix   : [1,b,1] ( n -- seq ) [1,b] dup but-last-slice <reversed> cord-append ;   : <reversed-evens> ( seq -- seq' ) [ even? [ <reversed> ] when ] map-index ;   : diagonals ( n -- seq ) [ sq <iota> ] [ [1,b,1] ] bi [ [ cut [ , ] dip ] each ] { } make nip <reversed-evens> ;   : zig-zag-matrix ( n -- seq ) [ diagonals ] [ dup ] bi '[ [ dup 0 <column> _ head , [ _ < [ rest-slice ] when ] map-index harvest ] until-empty ] { } make ;   : zig-zag-demo ( -- ) 5 zig-zag-matrix simple-table. ;   MAIN: zig-zag-demo
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
#Pike
Pike
> string res = (string)pow(5,pow(4,pow(3,2))); > res[..19] == "62060698786608744707"; Result: 1 > res[<19..] == "92256259918212890625"; Result: 1 > sizeof(result); Result: 183231
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
#PowerShell
PowerShell
# Perform calculation $BigNumber = [BigInt]::Pow( 5, [BigInt]::Pow( 4, [BigInt]::Pow( 3, 2 ) ) )   # Display first and last 20 digits $BigNumberString = [string]$BigNumber $BigNumberString.Substring( 0, 20 ) + "..." + $BigNumberString.Substring( $BigNumberString.Length - 20, 20 )   # Display number of digits $BigNumberString.Length
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
#Racket
Racket
  #lang racket (require math)   (define (fibs n) (reverse (for/list ([i (in-naturals 2)] #:break (> (fibonacci i) n)) (fibonacci i))))   (define (zechendorf n) (match/values (for/fold ([n n] [xs '()]) ([f (fibs n)]) (if (> f n) (values n (cons 0 xs)) (values (- n f) (cons 1 xs)))) [(_ xs) (reverse xs)]))   (for/list ([n 21]) (list n (zechendorf 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.
#Delphi
Delphi
proc nonrec main() void: byte DOORS = 100; [DOORS+1] bool door_open; unsigned DOORS i, j;   /* make sure all doors are closed */ for i from 1 upto DOORS do door_open[i] := false od;   /* pass through the doors */ for i from 1 upto DOORS do for j from i by i upto DOORS do door_open[j] := not door_open[j] od od;   /* show the open doors */ for i from 1 upto DOORS do if door_open[i] then writeln("Door ", i, " is open.") fi od corp
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)
#HolyC
HolyC
// Create an array of fixed size U8 array[10] = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;   // The first element of a HolyC array is indexed at 0. To set a value: array[0] = 123;   // Access an element Print("%d\n", array[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
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i"; include "complex.s7i";   const proc: main is func begin writeln("0 ** 0 = " <& 0 ** 0); writeln("0.0 ** 0 = " <& 0.0 ** 0); writeln("0.0 ** 0.0 = " <& 0.0 ** 0.0); writeln("0.0+0i ** 0 = " <& complex(0.0) ** 0); end func;  
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
#SenseTalk
SenseTalk
set a to 0 set b to 0   put a to the power of b // Prints: 1
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives in the red house.   The Swede has a dog.   The Dane drinks tea.   The green house is immediately to the left of the white house.   They drink coffee in the green house.   The man who smokes Pall Mall has birds.   In the yellow house they smoke Dunhill.   In the middle house they drink milk.   The Norwegian lives in the first house.   The man who smokes Blend lives in the house next to the house with cats.   In a house next to the house where they have a horse, they smoke Dunhill.   The man who smokes Blue Master drinks beer.   The German smokes Prince.   The Norwegian lives next to the blue house.   They drink water in a house next to the house where they smoke Blend. The question is, who owns the zebra? Additionally, list the solution for all the houses. Optionally, show the solution is unique. Related tasks   Dinesman's multiple-dwelling problem   Twelve statements
#Java
Java
package org.rosettacode.zebra;   import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Objects; import java.util.Set;   public class Zebra {   private static final int[] orders = {1, 2, 3, 4, 5}; private static final String[] nations = {"English", "Danish", "German", "Swedish", "Norwegian"}; private static final String[] animals = {"Zebra", "Horse", "Birds", "Dog", "Cats"}; private static final String[] drinks = {"Coffee", "Tea", "Beer", "Water", "Milk"}; private static final String[] cigarettes = {"Pall Mall", "Blend", "Blue Master", "Prince", "Dunhill"}; private static final String[] colors = {"Red", "Green", "White", "Blue", "Yellow"};   static class Solver { private final PossibleLines puzzleTable = new PossibleLines();   void solve() { PossibleLines constraints = new PossibleLines(); constraints.add(new PossibleLine(null, "English", "Red", null, null, null)); constraints.add(new PossibleLine(null, "Swedish", null, "Dog", null, null)); constraints.add(new PossibleLine(null, "Danish", null, null, "Tea", null)); constraints.add(new PossibleLine(null, null, "Green", null, "Coffee", null)); constraints.add(new PossibleLine(null, null, null, "Birds", null, "Pall Mall")); constraints.add(new PossibleLine(null, null, "Yellow", null, null, "Dunhill")); constraints.add(new PossibleLine(3, null, null, null, "Milk", null)); constraints.add(new PossibleLine(1, "Norwegian", null, null, null, null)); constraints.add(new PossibleLine(null, null, null, null, "Beer", "Blue Master")); constraints.add(new PossibleLine(null, "German", null, null, null, "Prince")); constraints.add(new PossibleLine(2, null, "Blue", null, null, null));   //Creating all possible combination of a puzzle line. //The maximum number of lines is 5^^6 (15625). //Each combination line is checked against a set of knowing facts, thus //only a small number of line result at the end. for (Integer orderId : Zebra.orders) { for (String nation : Zebra.nations) { for (String color : Zebra.colors) { for (String animal : Zebra.animals) { for (String drink : Zebra.drinks) { for (String cigarette : Zebra.cigarettes) { addPossibleNeighbors(constraints, orderId, nation, color, animal, drink, cigarette); } } } } } }   System.out.println("After general rule set validation, remains " + puzzleTable.size() + " lines.");   for (Iterator<PossibleLine> it = puzzleTable.iterator(); it.hasNext(); ) { boolean validLine = true;   PossibleLine possibleLine = it.next();   if (possibleLine.leftNeighbor != null) { PossibleLine neighbor = possibleLine.leftNeighbor; if (neighbor.order < 1 || neighbor.order > 5) { validLine = false; it.remove(); } } if (validLine && possibleLine.rightNeighbor != null) { PossibleLine neighbor = possibleLine.rightNeighbor; if (neighbor.order < 1 || neighbor.order > 5) { it.remove(); } } }   System.out.println("After removing out of bound neighbors, remains " + puzzleTable.size() + " lines.");   //Setting left and right neighbors for (PossibleLine puzzleLine : puzzleTable) { for (PossibleLine leftNeighbor : puzzleLine.neighbors) { PossibleLine rightNeighbor = leftNeighbor.copy();   //make it left neighbor leftNeighbor.order = puzzleLine.order - 1; if (puzzleTable.contains(leftNeighbor)) { if (puzzleLine.leftNeighbor != null) puzzleLine.leftNeighbor.merge(leftNeighbor); else puzzleLine.setLeftNeighbor(leftNeighbor); } rightNeighbor.order = puzzleLine.order + 1; if (puzzleTable.contains(rightNeighbor)) { if (puzzleLine.rightNeighbor != null) puzzleLine.rightNeighbor.merge(rightNeighbor); else puzzleLine.setRightNeighbor(rightNeighbor); } } }   int iteration = 1; int lastSize = 0;   //Recursively validate against neighbor rules while (puzzleTable.size() > 5 && lastSize != puzzleTable.size()) { lastSize = puzzleTable.size(); puzzleTable.clearLineCountFlags();   recursiveSearch(null, puzzleTable, -1);   constraints.clear(); // Assuming we'll get at leas one valid line each iteration, we create // a set of new rules with lines which have no more then one instance of same OrderId. for (int i = 1; i < 6; i++) { if (puzzleTable.getLineCountByOrderId(i) == 1) constraints.addAll(puzzleTable.getSimilarLines(new PossibleLine(i, null, null, null, null, null))); }   puzzleTable.removeIf(puzzleLine -> !constraints.accepts(puzzleLine));   System.out.println("After " + iteration + " recursive iteration, remains " + puzzleTable.size() + " lines"); iteration++; }   // Print the results System.out.println("-------------------------------------------"); if (puzzleTable.size() == 5) { for (PossibleLine puzzleLine : puzzleTable) { System.out.println(puzzleLine.getWholeLine()); } } else System.out.println("Sorry, solution not found!"); }   private void addPossibleNeighbors( PossibleLines constraints, Integer orderId, String nation, String color, String animal, String drink, String cigarette) { boolean validLine = true; PossibleLine pzlLine = new PossibleLine(orderId, nation, color, animal, drink, cigarette); // Checking against a set of knowing facts if (constraints.accepts(pzlLine)) { // Adding rules of neighbors if (cigarette.equals("Blend") && (animal.equals("Cats") || drink.equals("Water"))) validLine = false;   if (cigarette.equals("Dunhill") && animal.equals("Horse")) validLine = false;   if (validLine) { puzzleTable.add(pzlLine);   //set neighbors constraints if (color.equals("Green")) { pzlLine.setRightNeighbor( new PossibleLine(null, null, "White", null, null, null)); } if (color.equals("White")) { pzlLine.setLeftNeighbor( new PossibleLine(null, null, "Green", null, null, null)); } // if (animal.equals("Cats") && !cigarette.equals("Blend")) { pzlLine.neighbors.add(new PossibleLine(null, null, null, null, null, "Blend")); } if (cigarette.equals("Blend") && !animal.equals("Cats")) { pzlLine.neighbors.add(new PossibleLine(null, null, null, "Cats", null , null)); } // if (drink.equals("Water") && !animal.equals("Cats") && !cigarette.equals("Blend")) { pzlLine.neighbors.add(new PossibleLine(null, null, null, null, null, "Blend")); }   if (cigarette.equals("Blend") && !drink.equals("Water")) { pzlLine.neighbors.add(new PossibleLine(null, null, null, null, "Water" , null)); } // if (animal.equals("Horse") && !cigarette.equals("Dunhill")) { pzlLine.neighbors.add(new PossibleLine(null, null, null, null, null, "Dunhill")); } if (cigarette.equals("Dunhill") && !animal.equals("Horse")) { pzlLine.neighbors.add(new PossibleLine(null, null, null, "Horse", null, null)); } } } }   // Recursively checks the input set to ensure each line has right neighbor. // Neighbors can be of three type, left, right or undefined. // Direction: -1 left, 0 undefined, 1 right private boolean recursiveSearch(PossibleLine pzzlNodeLine, PossibleLines possibleLines, int direction) { boolean validLeaf = false; boolean hasNeighbor; PossibleLines puzzleSubSet;   for (Iterator<PossibleLine> it = possibleLines.iterator(); it.hasNext(); ) { PossibleLine pzzlLeafLine = it.next(); validLeaf = false;   hasNeighbor = pzzlLeafLine.hasNeighbor(direction);   if (hasNeighbor) { puzzleSubSet = puzzleTable.getSimilarLines(pzzlLeafLine.getNeighbor(direction)); if (puzzleSubSet != null) { if (pzzlNodeLine != null) validLeaf = puzzleSubSet.contains(pzzlNodeLine); else validLeaf = recursiveSearch(pzzlLeafLine, puzzleSubSet, -1 * direction); } }   if (!validLeaf && pzzlLeafLine.hasNeighbor(-1 * direction)) { hasNeighbor = true; puzzleSubSet = puzzleTable.getSimilarLines(pzzlLeafLine.getNeighbor(-1 * direction)); if (puzzleSubSet != null) { if (pzzlNodeLine != null) validLeaf = puzzleSubSet.contains(pzzlNodeLine); else validLeaf = recursiveSearch(pzzlLeafLine, puzzleSubSet, direction); } }   if (pzzlNodeLine != null && validLeaf) return true;   if (pzzlNodeLine == null && hasNeighbor && !validLeaf) { it.remove(); }   if (pzzlNodeLine == null) { if (hasNeighbor && validLeaf) { possibleLines.riseLineCountFlags(pzzlLeafLine.order); } if (!hasNeighbor) { possibleLines.riseLineCountFlags(pzzlLeafLine.order); } } } return validLeaf; } }   public static void main(String[] args) {   Solver solver = new Solver(); solver.solve(); }   static class PossibleLines extends LinkedHashSet<PossibleLine> {   private final int[] count = new int[5];   public PossibleLine get(int index) { return ((PossibleLine) toArray()[index]); }   public PossibleLines getSimilarLines(PossibleLine searchLine) { PossibleLines puzzleSubSet = new PossibleLines(); for (PossibleLine possibleLine : this) { if (possibleLine.getCommonFactsCount(searchLine) == searchLine.getFactsCount()) puzzleSubSet.add(possibleLine); } if (puzzleSubSet.isEmpty()) return null;   return puzzleSubSet; }   public boolean contains(PossibleLine searchLine) { for (PossibleLine puzzleLine : this) { if (puzzleLine.getCommonFactsCount(searchLine) == searchLine.getFactsCount()) return true; } return false; }   public boolean accepts(PossibleLine searchLine) { int passed = 0; int notpassed = 0;   for (PossibleLine puzzleSetLine : this) { int lineFactsCnt = puzzleSetLine.getFactsCount(); int comnFactsCnt = puzzleSetLine.getCommonFactsCount(searchLine);   if (lineFactsCnt != comnFactsCnt && lineFactsCnt != 0 && comnFactsCnt != 0) { notpassed++; }   if (lineFactsCnt == comnFactsCnt) passed++; } return passed >= 0 && notpassed == 0; }   public void riseLineCountFlags(int lineOrderId) { count[lineOrderId - 1]++; }   public void clearLineCountFlags() { Arrays.fill(count, 0); }   public int getLineCountByOrderId(int lineOrderId) { return count[lineOrderId - 1]; } }   static class PossibleLine {   Integer order; String nation; String color; String animal; String drink; String cigarette;   PossibleLine rightNeighbor; PossibleLine leftNeighbor; Set<PossibleLine> neighbors = new LinkedHashSet<>();   public PossibleLine(Integer order, String nation, String color, String animal, String drink, String cigarette) { this.animal = animal; this.cigarette = cigarette; this.color = color; this.drink = drink; this.nation = nation; this.order = order; }   @Override public boolean equals(Object obj) { return obj instanceof PossibleLine && getWholeLine().equals(((PossibleLine) obj).getWholeLine()); }   public int getFactsCount() { int facts = 0; facts += order != null ? 1 : 0; facts += nation != null ? 1 : 0; facts += color != null ? 1 : 0; facts += animal != null ? 1 : 0; facts += cigarette != null ? 1 : 0; facts += drink != null ? 1 : 0; return facts; }   private static int common(Object a, Object b) { return a != null && Objects.equals(a, b) ? 1 : 0; }   public int getCommonFactsCount(PossibleLine facts) { return common(order, facts.order) + common(nation, facts.nation) + common(color, facts.color) + common(animal, facts.animal) + common(cigarette, facts.cigarette) + common(drink, facts.drink); }   public void setLeftNeighbor(PossibleLine leftNeighbor) { this.leftNeighbor = leftNeighbor; this.leftNeighbor.order = order - 1; }   public void setRightNeighbor(PossibleLine rightNeighbor) { this.rightNeighbor = rightNeighbor; this.rightNeighbor.order = order + 1; }   public boolean hasNeighbor(int direction) { return getNeighbor(direction) != null; }   public PossibleLine getNeighbor(int direction) { if (direction < 0) return leftNeighbor; else return rightNeighbor; }   public String getWholeLine() { return order + " - " + nation + " - " + color + " - " + animal + " - " + drink + " - " + cigarette; }   @Override public int hashCode() { return Objects.hash(order, nation, color, animal, drink, cigarette); }   public void merge(PossibleLine mergedLine) { if (order == null) order = mergedLine.order; if (nation == null) nation = mergedLine.nation; if (color == null) color = mergedLine.color; if (animal == null) animal = mergedLine.animal; if (drink == null) drink = mergedLine.drink; if (cigarette == null) cigarette = mergedLine.cigarette; }   public PossibleLine copy() { PossibleLine clone = new PossibleLine(order, nation, color, animal, drink, cigarette); clone.leftNeighbor = leftNeighbor; clone.rightNeighbor = rightNeighbor; clone.neighbors = neighbors; // shallow copy return clone; } } }
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>
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
example = Import["test.txt", "XML"]; Cases[example, XMLElement["item", _ , _] , Infinity] // First Cases[example, XMLElement["price", _, List[n_]] -> n, Infinity] // Column Cases[example, XMLElement["name", _, List[n_]] -> n, Infinity] // Column
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>
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java symbols binary   import javax.xml.parsers. import javax.xml.xpath. import org.w3c.dom. import org.w3c.dom.Node import org.xml.sax.   xmlStr = '' - || '<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 priwater</description>' - || ' </item>' - || ' </section>' - || '</inventory>'   expr1 = '/inventory/section/item[1]' expr2 = '/inventory/section/item/price' expr3 = '/inventory/section/item/name' attr1 = 'upc'   do doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(InputSource(StringReader(xmlStr))) xpath = XPathFactory.newInstance().newXPath()   -- Extract attribute from 1st item element say expr1 say " "(Node xpath.evaluate(expr1, doc, XPathConstants.NODE)).getAttributes().getNamedItem(attr1) say   -- Extract and display all price elments nodes = NodeList xpath.evaluate(expr2, doc, XPathConstants.NODESET) say expr2 loop i_ = 0 to nodes.getLength() - 1 say Rexx(nodes.item(i_).getTextContent()).format(10, 2) end i_ say   -- Extract elements and store in an ArrayList nameList = java.util.List nameList = ArrayList() nodes = NodeList xpath.evaluate(expr3, doc, XPathConstants.NODESET) loop i_ = 0 to nodes.getLength() - 1 nameList.add(nodes.item(i_).getTextContent()) end i_   -- display contents of ArrayList say expr3 loop n_ = 0 to nameList.size() - 1 say " "nameList.get(n_) end n_ say   catch ex = Exception ex.printStackTrace() end   return  
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#Lambdatalk
Lambdatalk
  {{SVG 580 580} {YY 145 145 300} {YY 270 195 50} {YY 270 345 50} }   {def YY {lambda {:x :y :s} {{G :x :y :s} {CIRCLE 0.5 0.5 0.5 black 0 0} {{G 0.5 0 1} {HALF_CIRCLE}} {CIRCLE 0.5 0.25 0.25 black 0 0} {CIRCLE 0.5 0.75 0.25 white 0 0} {CIRCLE 0.5 0.25 0.1 white 0 0} {CIRCLE 0.5 0.75 0.1 black 0 0} {CIRCLE 0.5 0.5 0.5 none gray 0.01} }}}   {def CIRCLE {lambda {:x :y :r :f :s :w} {circle {@ cx=":x" cy=":y" r=":r" fill=":f" stroke=":s" stroke-width=":w"}}}}   {def HALF_CIRCLE {path {@ d="M 0 0 A 0.5 0.5 0 0 0 0 1" fill="white"}}}   {def SVG {lambda {:w :h} svg {@ width=":w" height=":h" style="box-shadow:0 0 8px #888;"}}}   {def G {lambda {:x :y :s} g {@ transform="translate(:x,:y) scale(:s,:s)"}}}   Output: Sorry, I was unable to upload the following PNG picture (45kb). Need help.   http://lambdaway.free.fr/lambdawalks/data/lambdatalk_yinyang.png    
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
#Elena
Elena
import extensions;   singleton YCombinator { fix(func) = (f){(x){ x(x) }((g){ f((x){ (g(g))(x) })})}(func); }   public program() { var fib := YCombinator.fix:(f => (i => (i <= 1) ? i : (f(i-1) + f(i-2)) )); var fact := YCombinator.fix:(f => (i => (i == 0) ? 1 : (f(i-1) * i) ));   console.printLine("fib(10)=",fib(10)); console.printLine("fact(10)=",fact(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
#Fan
Fan
using gfx // for Point; convenient x/y wrapper   ** ** A couple methods for generating a 'zigzag' array like ** ** 0 1 5 6 ** 2 4 7 12 ** 3 8 11 13 ** 9 10 14 15 ** class ZigZag { ** return an n x n array of uninitialized Int static Int[][] makeSquareArray(Int n) { Int[][] grid := Int[][,] {it.size=n} n.times |i| { grid[i] = Int[,] {it.size=n} } return grid }     Int[][] zig(Int n) { grid := makeSquareArray(n)   move := |Int i, Int j->Point| { return j < n - 1 ? Point(i <= 0 ? 0 : i-1, j+1) : Point(i+1, j) } pt := Point(0,0) (n*n).times |i| { grid[pt.y][pt.x] = i if ((pt.x+pt.y)%2 != 0) pt = move(pt.x,pt.y) else {tmp:= move(pt.y,pt.x); pt = Point(tmp.y, tmp.x) } } return grid }   public static Int[][] zag(Int size) { data := makeSquareArray(size)   Int i := 1 Int j := 1 for (element:=0; element < size * size; element++) { data[i - 1][j - 1] = element if((i + j) % 2 == 0) { // Even stripes if (j < size) { j++ } else { i += 2 } if (i > 1) { i-- } } else { // Odd stripes if (i < size) { i++; } else { j += 2 } if (j > 1) { j-- } } } return data; }   Void print(Int[][] data) { data.each |row| { buf := StrBuf() row.each |num| { buf.add(num.toStr.justr(3)) } echo(buf) } }   Void main() { echo("zig method:") print(zig(8)) echo("\nzag method:") print(zag(8)) } }
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
#Prolog
Prolog
  task(Length) :- N is 5^4^3^2,   number_codes(N, Codes), append(`62060698786608744707`, _, Codes), append(_, `92256259918212890625`, Codes),   length(Codes, Length).  
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
#PureBasic
PureBasic
IncludeFile "Decimal.pbi"   ;- Declare the variables that will be used Define.Decimal *a Define n, L$, R$, out$, digits.s   ;- 4^3^2 is withing 32 bit range, so normal procedures can be used n=Pow(4,Pow(3,2))   ;- 5^n is larger then 31^2, so the same library call as in the "Long multiplication" task is used *a=PowerDecimal(IntegerToDecimal(5),IntegerToDecimal(n))   ;- Convert the large number into a string & present the results out$=DecimalToString(*a) L$ = Left(out$,20) R$ = Right(out$,20) digits=Str(Len(out$)) out$="First 20 & last 20 chars of 5^4^3^2 are;"+#CRLF$+L$+#CRLF$+R$+#CRLF$ out$+"and the result is "+digits+" digits long."   MessageRequester("Arbitrary-precision integers, PureBasic",out$)
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
#Raku
Raku
printf "%2d: %8s\n", $_, zeckendorf($_) for 0 .. 20;   multi zeckendorf(0) { '0' } multi zeckendorf($n is copy) { constant FIBS = (1,2, *+* ... *).cache; [~] map { $n -= $_ if my $digit = $n >= $_; +$digit; }, reverse FIBS ...^ * > $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.
#Draco
Draco
proc nonrec main() void: byte DOORS = 100; [DOORS+1] bool door_open; unsigned DOORS i, j;   /* make sure all doors are closed */ for i from 1 upto DOORS do door_open[i] := false od;   /* pass through the doors */ for i from 1 upto DOORS do for j from i by i upto DOORS do door_open[j] := not door_open[j] od od;   /* show the open doors */ for i from 1 upto DOORS do if door_open[i] then writeln("Door ", i, " is open.") fi od corp
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)
#Icon_and_Unicon
Icon and Unicon
record aThing(a, b, c) # arbitrary object (record or class) for illustration   procedure main() A0 := [] # empty list A0 := list() # empty list (default size 0) A0 := list(0) # empty list (literal size 0)   A1 := list(10) # 10 elements, default initializer &null A2 := list(10, 1) # 10 elements, initialized to 1   # literal array construction - arbitrary dynamically typed members A3 := [1, 2, 3, ["foo", "bar", "baz"], aThing(1, 2, 3), "the end"]   # left-end workers # NOTE: get() is a synonym for pop() which allows nicely-worded use of put() and get() to implement queues # Q := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] x := pop(A0) # x is 1 x := get(A0) # x is 2 push(Q,0) # Q is now [0,3, 4, 5, 6, 7, 8, 9, 10]   # right-end workers x := pull(Q) # x is 10 put(Q, 100) # Q is now [0, 3, 4, 5, 6, 7, 8, 9, 100]   # push and put return the list they are building # they also can have multiple arguments which work like repeated calls   Q2 := put([],1,2,3) # Q2 is [1,2,3] Q3 := push([],1,2,3) # Q3 is [3,2,1] Q4 := push(put(Q2),4),0] # Q4 is [0,1,2,3,4] and so is Q2   # array access follows with A as the sample array A := [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]   # get element indexed from left x := A[1] # x is 10 x := A[2] # x is 20 x := A[10] # x is 100   # get element indexed from right x := A[-1] # x is 100 x := A[-2] # x is 90 x := A[-10] # x is 10   # copy array to show assignment to elements B := copy(A)   # assign element indexed from left B[1] := 11 B[2] := 21 B[10] := 101 # B is now [11, 21, 30, 50, 60, 60, 70, 80, 90, 101]   # assign element indexed from right - see below B[-1] := 102 B[-2] := 92 B[-10] := 12 # B is now [12, 21, 30, 50, 60, 60, 70, 80, 92, 102]   # list slicing # the unusual nature of the slice - returning 1 less element than might be expected # in many languages - is best understood if you imagine indexes as pointing to BEFORE # the item of interest. When a slice is made, the elements between the two points are # collected. eg in the A[3 : 6] sample, it will get the elements between the [ ] marks # # sample list: 10 20 [30 40 50] 60 70 80 90 100 # positive indexes: 1 2 3 4 5 6 7 8 9 10 11 # non-positive indexes: -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 # # I have deliberately drawn the indexes between the positions of the values. # The nature of this indexing brings simplicity to string operations # # list slicing can also use non-positive indexes to access values from the right. # The final index of 0 shown above shows how the end of the list can be nominated # without having to know it's length # # NOTE: list slices are distinct lists, so assigning to the slice # or a member of the slice does not change the values in A # # Another key fact to understand: once the non-positive indexes and length-offsets are # resolved to a simple positive index, the index pair (if two are given) are swapped # if necessary to yield the elements between the two. # S := A[3 : 6] # S is [30, 40, 50] S := A[6 : 3] # S is [30, 40, 50] not illegal or erroneous S := A[-5 : -8] # S is [30, 40, 50] S := A[-8 : -5] # S is [30, 40, 50] also legal and meaningful   # list slicing with length request S := A[3 +: 3] # S is [30, 40, 50] S := A[6 -: 3] # S is [30, 40, 50] S := A[-8 +: 3] # S is [30, 40, 50] S := A[-5 -: 3] # S is [30, 40, 50] S := A[-8 -: -3] # S is [30, 40, 50] S := A[-5 +: -3] # S is [30, 40, 50] 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
#Sidef
Sidef
[0, Complex(0, 0)].each {|n| say n**n }
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
#Sinclair_ZX81_BASIC
Sinclair ZX81 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
#Smalltalk
Smalltalk
  0 raisedTo: 0 0.0 raisedTo: 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
#jq
jq
  # Attempt to unify the input object with the specified object def unify( object ): # Attempt to unify the input object with the specified tag:value def unify2(tag; value): if . == null then null elif .[tag] == value then . elif .[tag] == null then .[tag] = value else null end; reduce (object|keys[]) as $key (.; unify2($key; object[$key]) );   # Input: an array # Output: if the i-th element can be made to satisfy the condition, # then the updated array, otherwise empty. def enforce(i; cond): if 0 <= i and i < length then (.[i] | cond) as $ans | if $ans then .[i] = $ans else empty end else empty end ;