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/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.
#SNOBOL4
SNOBOL4
* # Define complex datatype data('complex(r,i)')   * # Addition define('addx(x1,x2)a,b,c,d') :(addx_end) addx a = r(x1); b = i(x1); c = r(x2); d = i(x2) addx = complex(a + c, b + d) :(return) addx_end   * # Multiplication define('multx(x1,x2)a,b,c,d') :(multx_end) multx a = r(x1); b = i(x1); c = r(x2); d = i(x2) multx = complex(a * c - b * d, b * c + a * d) :(return) multx_end   * # Negation define('negx(x)') :(negx_end) negx negx = complex(-r(x), -i(x)) :(return) negx_end   * # Inverse define('invx(x)d') :(invx_end) invx d = (r(x) * r(x)) + (i(x) * i(x)) invx = complex(1.0 * r(x) / d, 1.0 * -i(x) / d) :(return) invx_end   * # Print compex number: a+bi / a-bi define('printx(x)sign') :(printx_end) printx sign = ge(i(x),0) '+' printx = r(x) sign i(x) 'i' :(return) printx_end   * # Test and display a = complex(1,1) b = complex(3.14159, 1.2) output = printx( addx(a,b) ) output = printx( multx(a,b) ) output = printx( negx(a) ) ', ' printx( negx(b) ) output = printx( invx(a) ) ', ' printx( invx(b) ) end
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.
#Standard_ML
Standard ML
  (* Signature for complex numbers *) signature COMPLEX = sig type num   val complex : real * real -> num   val negative : num -> num val plus : num -> num -> num val minus : num -> num -> num val times : num -> num -> num val invert : num -> num val print_number : num -> unit end;   (* Actual implementation *) structure Complex :> COMPLEX = struct type num = real * real   fun complex (a, b) = (a, b)   fun negative (a, b) = (Real.~a, Real.~b) fun plus (a1, b1) (a2, b2) = (Real.+ (a1, a2), Real.+(b1, b2)) fun minus i1 i2 = plus i1 (negative i2) fun times (a1, b1) (a2, b2)= (Real.*(a1, a2) - Real.*(b1, b2), Real.*(a1, b2) + Real.*(a2, b1)) fun invert (a, b) = let val denom = a * a + b * b in (a / denom, ~b / denom) end   fun print_number (a, b) = print (Real.toString(a) ^ " + " ^ Real.toString(b) ^ "i\n") end;   val i1 = Complex.complex(1.0,2.0); (* 1 + 2i *) val i2 = Complex.complex(3.0,4.0); (* 3 + 4i *)   Complex.print_number(Complex.negative(i1)); (* -1 - 2i *) Complex.print_number(Complex.plus i1 i2); (* 4 + 6i *) Complex.print_number(Complex.minus i2 i1); (* 2 + 2i *) Complex.print_number(Complex.times i1 i2); (* -5 + 10i *) Complex.print_number(Complex.invert i1); (* 1/5 - 2i/5 *)  
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
#Pascal
Pascal
program ZToZ; uses math; begin write('0.0 ^ 0 :',IntPower(0.0,0):4:2); writeln(' 0.0 ^ 0.0 :',Power(0.0,0.0):4:2); 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
#Perl
Perl
print 0 ** 0, "\n";   use Math::Complex;   print cplx(0,0) ** cplx(0,0), "\n";
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives in the red house.   The Swede has a dog.   The Dane drinks tea.   The green house is immediately to the left of the white house.   They drink coffee in the green house.   The man who smokes Pall Mall has birds.   In the yellow house they smoke Dunhill.   In the middle house they drink milk.   The Norwegian lives in the first house.   The man who smokes Blend lives in the house next to the house with cats.   In a house next to the house where they have a horse, they smoke Dunhill.   The man who smokes Blue Master drinks beer.   The German smokes Prince.   The Norwegian lives next to the blue house.   They drink water in a house next to the house where they smoke Blend. The question is, who owns the zebra? Additionally, list the solution for all the houses. Optionally, show the solution is unique. Related tasks   Dinesman's multiple-dwelling problem   Twelve statements
#D
D
import std.stdio, std.traits, std.algorithm, std.math;   enum Content { Beer, Coffee, Milk, Tea, Water, Danish, English, German, Norwegian, Swedish, Blue, Green, Red, White, Yellow, Blend, BlueMaster, Dunhill, PallMall, Prince, Bird, Cat, Dog, Horse, Zebra } enum Test { Drink, Person, Color, Smoke, Pet } enum House { One, Two, Three, Four, Five }   alias TM = Content[EnumMembers!Test.length][EnumMembers!House.length];   bool finalChecks(in ref TM M) pure nothrow @safe @nogc { int diff(in Content a, in Content b, in Test ca, in Test cb) nothrow @safe @nogc { foreach (immutable h1; EnumMembers!House) foreach (immutable h2; EnumMembers!House) if (M[ca][h1] == a && M[cb][h2] == b) return h1 - h2; assert(0); // Useless but required. }   with (Content) with (Test) return abs(diff(Norwegian, Blue, Person, Color)) == 1 && diff(Green, White, Color, Color) == -1 && abs(diff(Horse, Dunhill, Pet, Smoke)) == 1 && abs(diff(Water, Blend, Drink, Smoke)) == 1 && abs(diff(Blend, Cat, Smoke, Pet)) == 1; }   bool constrained(in ref TM M, in Test atest) pure nothrow @safe @nogc { with (Content) with (Test) with (House) final switch (atest) { case Drink: return M[Drink][Three] == Milk; case Person: foreach (immutable h; EnumMembers!House) if ((M[Person][h] == Norwegian && h != One) || (M[Person][h] == Danish && M[Drink][h] != Tea)) return false; return true; case Color: foreach (immutable h; EnumMembers!House) if ((M[Person][h] == English && M[Color][h] != Red) || (M[Drink][h] == Coffee && M[Color][h] != Green)) return false; return true; case Smoke: foreach (immutable h; EnumMembers!House) if ((M[Color][h] == Yellow && M[Smoke][h] != Dunhill) || (M[Smoke][h] == BlueMaster && M[Drink][h] != Beer) || (M[Person][h] == German && M[Smoke][h] != Prince)) return false; return true; case Pet: foreach (immutable h; EnumMembers!House) if ((M[Person][h] == Swedish && M[Pet][h] != Dog) || (M[Smoke][h] == PallMall && M[Pet][h] != Bird)) return false; return finalChecks(M); } }   void show(in ref TM M) { foreach (h; EnumMembers!House) { writef("%5s: ", h); foreach (immutable t; EnumMembers!Test) writef("%10s ", M[t][h]); writeln; } }   void solve(ref TM M, in Test t, in size_t n) { if (n == 1 && constrained(M, t)) { if (t < 4) { solve(M, [EnumMembers!Test][t + 1], 5); } else { show(M); return; } } foreach (immutable i; 0 .. n) { solve(M, t, n - 1); swap(M[t][n % 2 ? 0 : i], M[t][n - 1]); } }   void main() { TM M; foreach (immutable t; EnumMembers!Test) foreach (immutable h; EnumMembers!House) M[t][h] = EnumMembers!Content[t * 5 + h];   solve(M, Test.Drink, 5); }
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>
#E
E
? def xml__quasiParser := <import:org.switchb.e.xml.makeXMLQuasiParser>() > def xpath__quasiParser := xml__quasiParser.xPathQuasiParser() > null   ? def doc := 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>n> > </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>` # value: xml`...`   ? doc[xpath`inventory/section/item`][0] # value: xml`<item stock="12" upc="123456789"> # <name>Invisibility Cream</name> # <price>14.50</price> # <description>Makes you invisible</description> # </item>`   ? for price in doc[xpath`inventory/section/item/price/text()`] { println(price :String) } 14.50 23.99 4.95 3.56   ? doc[xpath`inventory/section/item/name`] # value: [xml`<name>Invisibility Cream</name>`, # xml`<name>Levitation Salve</name>`, # xml`<name>Blork and Freen Instameal</name>`, # xml`<name>Grob winglets</name>`]  
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#Delphi
Delphi
procedure DrawYinAndYang(Canv: TCanvas; R: TRect); begin Canv.Brush.Color := clWhite; Canv.Pen.Color := clWhite; Canv.Pie(R.Left, R.Top, R.Right, R.Bottom, (R.Right + R.Left) div 2, R.Top, (R.Right + R.Left) div 2, R.Bottom); Canv.Brush.Color := clBlack; Canv.Pen.Color := clBlack; Canv.Pie(R.Left, R.Top, R.Right, R.Bottom, (R.Right + R.Left) div 2, R.Bottom, (R.Right + R.Left) div 2, R.Top); Canv.Brush.Color := clWhite; Canv.Pen.Color := clWhite; Canv.Ellipse((R.Right + 3 * R.Left) div 4, R.Top, (3 * R.Right + R.Left) div 4, (R.Top + R.Bottom) div 2); Canv.Brush.Color := clBlack; Canv.Pen.Color := clBlack; Canv.Ellipse((R.Right + 3 * R.Left) div 4, (R.Top + R.Bottom) div 2, (3 * R.Right + R.Left) div 4, R.Bottom);   Canv.Brush.Color := clWhite; Canv.Pen.Color := clWhite; Canv.Ellipse((7 * R.Right + 9 * R.Left) div 16, (11 * R.Bottom + 5 * R.Top) div 16, (9 * R.Right + 7 * R.Left) div 16, (13 * R.Bottom + 3 * R.Top) div 16); Canv.Brush.Color := clBlack; Canv.Pen.Color := clBlack; Canv.Ellipse((7 * R.Right + 9 * R.Left) div 16, (3 * R.Bottom + 13 * R.Top) div 16, (9 * R.Right + 7 * R.Left) div 16, (5 * R.Bottom + 11 * R.Top) div 16); end;   procedure TForm1.FormCreate(Sender: TObject); begin ClientWidth := 400; ClientHeight := 400; end;   procedure TForm1.FormPaint(Sender: TObject); var R: TRect; begin R := ClientRect; Canvas.Brush.Color := clGray; Canvas.FillRect(R);   InflateRect(R, -50, -50); OffsetRect(R, -40, -40); DrawYinAndYang(Canvas, R);   InflateRect(R, -90, -90); OffsetRect(R, 170, 170); DrawYinAndYang(Canvas, R); end;  
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#CoffeeScript
CoffeeScript
Y = (f) -> g = f( (t...) -> g(t...) )
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
#CoffeeScript
CoffeeScript
  # Calculate a zig-zag pattern of numbers like so: # 0 1 5 # 2 4 6 # 3 7 8 # # There are many interesting ways to solve this; we # try for an algebraic approach, calculating triangle # areas, so that me minimize space requirements.   zig_zag_value = (x, y, n) ->   upper_triangle_zig_zag = (x, y) -> # calculate the area of the triangle from the prior # diagonals diag = x + y triangle_area = diag * (diag+1) / 2 # then add the offset along the diagonal if diag % 2 == 0 triangle_area + y else triangle_area + x   if x + y < n upper_triangle_zig_zag x, y else # For the bottom right part of the matrix, we essentially # use reflection to count backward. bottom_right_cell = n * n - 1 n -= 1 v = upper_triangle_zig_zag(n-x, n-y) bottom_right_cell - v   zig_zag_matrix = (n) -> row = (i) -> (zig_zag_value i, j, n for j in [0...n]) (row i for i in [0...n])   do -> for n in [4..6] console.log "---- n=#{n}" console.log zig_zag_matrix(n) console.log "\n"  
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].
#REXX
REXX
/*REXX program calculates any number of terms in the Yellowstone (permutation) sequence.*/ parse arg m . /*obtain optional argument from the CL.*/ if m=='' | m=="," then m= 30 /*Not specified? Then use the default.*/ !.= 0 /*initialize an array of numbers(used).*/ # = 0 /*count of Yellowstone numbers in seq. */ $= /*list " " " " " */ do j=1 until #==m; prev= # - 1 if j<5 then do; #= #+1; @.#= j;  !.#= j;  !.j= 1; $= strip($ j); iterate; end   do k=1; if !.k then iterate /*Already used? Then skip this number.*/ if gcd(k, @.prev)<2 then iterate /*Not meet requirement? Then skip it. */ if gcd(k, @.#) \==1 then iterate /* " " " " " " */ #= #+1; @.#= k;  !.k= 1; $= $ k /*bump ctr; assign; mark used; add list*/ leave /*find the next Yellowstone seq. number*/ end /*k*/ end /*j*/ say $ /*display a list of a Yellowstone seq. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ gcd: parse arg x,y; do until y==0; parse value x//y y with y x; end; return x
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].
#Ring
Ring
  see "working..." + nl row = 3 num = 2 numbers = 1:51 first = 2 second = 3 see "Yellowstone numbers are:" + nl see "1 " + first + " " + second + " "   for n = 4 to len(numbers) flag1 = 1 flag2 = 1 if first < numbers[n] min = first else min = numbers[n] ok for m = 2 to min if first%m = 0 and numbers[n]%m = 0 flag1 = 0 exit ok next if second < numbers[n] min = second else min = numbers[n] ok for m = 2 to min if second%m = 0 and numbers[n]%m = 0 flag2 = 0 exit ok next if flag1 = 0 and flag2 = 1 see "" + numbers[n] + " " first = second second = numbers[n] del(numbers,n) row = row+1 if row%10 = 0 see nl ok num = num + 1 if num = 29 exit ok n = 3 ok next   see "Found " + row + " Yellowstone numbers" + nl see "done..." + nl  
http://rosettacode.org/wiki/Yahoo!_search_interface
Yahoo! search interface
Create a class for searching Yahoo! results. It must implement a Next Page method, and read URL, Title and Content from results.
#Raku
Raku
  use Gumbo; use LWP::Simple; use XML::Text;   class YahooSearch { has $!dom;   submethod BUILD (:$!dom) { }   method new($term) { self.bless( dom => parse-html( LWP::Simple.get("http://search.yahoo.com/search?p={ $term }") ) ); }   method next { $!dom = parse-html( LWP::Simple.get( $!dom.lookfor( TAG => 'a', class => 'next' ).head.attribs<href> ) ); self; }   method text ($node) { return '' unless $node; return $node.text if $node ~~ XML::Text;   $node.nodes.map({ self.text($_).trim }).join(' '); }   method results { state $n = 0; for $!dom.lookfor( TAG => 'h3', class => 'title') { given .lookfor( TAG => 'a' )[0] { next unless $_; # No Link next if .attribs<href> ~~ / ^ 'https://r.search.yahoo.com' /; # Ad say "=== #{ ++$n } ==="; say "Title: { .contents[0] ?? self.text( .contents[0] ) !! '' }"; say " URL: { .attribs<href> }";   my $pt = .parent.parent.parent.elements( TAG => 'div' ).tail; say " Text: { self.text($pt) }"; } } self; }   }   sub MAIN (Str $search-term) is export { YahooSearch.new($search-term).results.next.results; }  
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
s:=ToString[5^4^3^2]; Print[StringTake[s,20]<>"..."<>StringTake[s,-20]<>" ("<>ToString@StringLength@s<>" 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
#MATLAB
MATLAB
>> answer = vpi(5)^(vpi(4)^(vpi(3)^vpi(2))); >> numDigits = order(answer) + 1   numDigits =   183231   >> [sprintf('%d',leadingdigit(answer,20)) '...' sprintf('%d',trailingdigit(answer,20))] %First and Last 20 Digits   ans =   62060698786608744707...92256259918212890625
http://rosettacode.org/wiki/Zeckendorf_number_representation
Zeckendorf number representation
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100. 10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution. Task Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. Also see   OEIS A014417   for the the sequence of required results.   Brown's Criterion - Numberphile Related task   Fibonacci sequence
#Pascal
Pascal
  program ZeckendorfRep_RC;   {$mode objfpc}{$H+}   uses SysUtils;   // Return Zeckendorf representation of the passed-in cardinal. function ZeckRep( C : cardinal) : string; var a, b, rem : cardinal; j, nrDigits: integer; begin // Case C = 0 has to be treated specially if (C = 0) then begin result := '0'; exit; end; // Find largest Fibonacci number not exceeding C a := 1; b := 1; nrDigits := 1; rem := C - 1; while (rem >= b) do begin dec( rem, b); inc( a, b); b := a - b; inc( nrDigits); end; // Fill in digits by reversing Fibonacci back to start SetLength( result, nrDigits); j := 1; result[j] := '1'; for j := 2 to nrDigits do begin if (rem >= b) then begin dec( rem, b); result[j] := '1'; end else result[j] := '0'; b := a - b; dec( a, b); end; // Assert((a = 1) and (b = 1)); // optional check end;   // Main routine var C : cardinal; begin for C := 1 to 20 do WriteLn( SysUtils.Format( '%2d: %s', [C, ZeckRep(C)])); end.  
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#Common_Lisp
Common Lisp
(defun visit-door (doors doornum value1 value2) "visits a door, swapping the value1 to value2 or vice-versa" (let ((d (copy-list doors)) (n (- doornum 1))) (if (eql (nth n d) value1) (setf (nth n d) value2) (setf (nth n d) value1)) d))   (defun visit-every (doors num iter value1 value2) "visits every 'num' door in the list" (if (> (* iter num) (length doors)) doors (visit-every (visit-door doors (* num iter) value1 value2) num (+ 1 iter) value1 value2)))   (defun do-all-visits (doors cnt value1 value2) "Visits all doors changing the values accordingly" (if (< cnt 1) doors (do-all-visits (visit-every doors cnt 1 value1 value2) (- cnt 1) value1 value2)))   (defun print-doors (doors) "Pretty prints the doors list" (format T "~{~A ~A ~A ~A ~A ~A ~A ~A ~A ~A~%~}~%" doors))   (defun start (&optional (size 100)) "Start the program" (let* ((open "_") (shut "#") (doors (make-list size :initial-element shut))) (print-doors (do-all-visits doors size open shut))))
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)
#Go
Go
package main   import ( "fmt" )   func main() { // creates an array of five ints. // specified length must be a compile-time constant expression. // this allows compiler to do efficient bounds checking. var a [5]int   // since length is compile-time constant, len() is a compile time constant // and does not have the overhead of a function call. fmt.Println("len(a) =", len(a))   // elements are always initialized to 0 fmt.Println("a =", a)   // assign a value to an element. indexing is 0 based. a[0] = 3 fmt.Println("a =", a)   // retrieve element value with same syntax fmt.Println("a[0] =", a[0])   // a slice references an underlying array s := a[:4] // this does not allocate new array space. fmt.Println("s =", s)   // slices have runtime established length and capacity, but len() and // cap() are built in to the compiler and have overhead more like // variable access than function call. fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))   // slices can be resliced, as long as there is space // in the underlying array. s = s[:5] fmt.Println("s =", s)   // s still based on a a[0] = 22 fmt.Println("a =", a) fmt.Println("s =", s)   // append will automatically allocate a larger underlying array as needed. s = append(s, 4, 5, 6) fmt.Println("s =", s) fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))   // s no longer based on a a[4] = -1 fmt.Println("a =", a) fmt.Println("s =", s)   // make creates a slice and allocates a new underlying array s = make([]int, 8) fmt.Println("s =", s) fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))   // the cap()=10 array is no longer referenced // and would be garbage collected eventually. }
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.
#Stata
Stata
mata C(2,3) 2 + 3i   a=2+3i b=1-2*i     a+b -5 + 3i   a-b 9 + 3i   a*b -14 - 21i   a/b -.285714286 - .428571429i   -a -2 - 3i   1/a .153846154 - .230769231i   conj(a) 2 - 3i   abs(a) 3.605551275   arg(a) .9827937232   exp(a) -7.31511009 + 1.04274366i   log(a) 1.28247468 + .982793723i   end
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.
#Swift
Swift
  public struct Complex {   public let real : Double public let imaginary : Double   public init(real inReal:Double, imaginary inImaginary:Double) { real = inReal imaginary = inImaginary }   public static var i : Complex = Complex(real:0, imaginary: 1) public static var zero : Complex = Complex(real: 0, imaginary: 0)   public var negate : Complex { return Complex(real: -real, imaginary: -imaginary) }   public var invert : Complex { let d = (real*real + imaginary*imaginary) return Complex(real: real/d, imaginary: -imaginary/d) }   public var conjugate : Complex { return Complex(real: real, imaginary: -imaginary) }   } public func + (left: Complex, right: Complex) -> Complex {   return Complex(real: left.real+right.real, imaginary: left.imaginary+right.imaginary) } public func * (left: Complex, right: Complex) -> Complex {   return Complex(real: left.real*right.real - left.imaginary*right.imaginary, imaginary: left.real*right.imaginary+left.imaginary*right.real) } public prefix func - (right:Complex) -> Complex { return right.negate }   // Checking equality is almost necessary for a struct of this type to be useful extension Complex : Equatable {} public func == (left:Complex, right:Complex) -> Bool { return left.real == right.real && left.imaginary == right.imaginary }    
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
#Phix
Phix
?power(0,0) requires("0.8.4") -- (now fixed/crashes on earlier versions) include complex.e complex a = complex_new(0,0), b = complex_power(a,a) string sa = complex_sprint(a,true), sb = complex_sprint(b,true) printf(1,"%s ^ %s = %s\n",{sa,sa,sb})
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
#Phixmonti
Phixmonti
def mypower dup not if . sign dup 0 == if . 1 endif else power endif enddef   0 0 mypower print
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives in the red house.   The Swede has a dog.   The Dane drinks tea.   The green house is immediately to the left of the white house.   They drink coffee in the green house.   The man who smokes Pall Mall has birds.   In the yellow house they smoke Dunhill.   In the middle house they drink milk.   The Norwegian lives in the first house.   The man who smokes Blend lives in the house next to the house with cats.   In a house next to the house where they have a horse, they smoke Dunhill.   The man who smokes Blue Master drinks beer.   The German smokes Prince.   The Norwegian lives next to the blue house.   They drink water in a house next to the house where they smoke Blend. The question is, who owns the zebra? Additionally, list the solution for all the houses. Optionally, show the solution is unique. Related tasks   Dinesman's multiple-dwelling problem   Twelve statements
#EchoLisp
EchoLisp
  (lib 'hash) (lib 'amb)   ;; return #f or house# for thing/category ;; houses := (0 1 2 3 4) (define (house-get H category thing houses) (for/or ((i houses)) #:continue (!equal? (hash-ref (vector-ref H i) category) thing) i))   ;; return house # for thing (eg cat) in category (eq animals) ;; add thing if not already here (define-syntax-rule (house-set thing category) (or (house-get H 'category 'thing houses) (dispatch H 'category 'thing context houses )))   ;; we know that thing/category is in a given house (define-syntax-rule (house-force thing category house) (dispatch H 'category 'thing context houses house))   ;; return house# or fail if impossible (define (dispatch H category thing context houses (forced #f)) (define house (or forced (amb context houses))) ;; get a house number (when (hash-ref (vector-ref H house) category) (amb-fail)) ;; fail if occupied (hash-set (vector-ref H house) category thing) ;; else remember house contents house)   (define (house-next h1 h2) (amb-require (or (= h1 (1+ h2)) (= h1 (1- h2)))))   (define (zebra-puzzle context houses ) (define H (build-vector 5 make-hash)) ;; house[i] := hash(category) -> thing ; In the middle house they drink milk. (house-force milk drinks 2) ;The Norwegian lives in the first house. (house-force norvegian people 0) ; The English man lives in the red house. (house-force red colors(house-set english people)) ; The Swede has a dog. (house-force dog animals (house-set swede people)) ; The Dane drinks tea. (house-force tea drinks (house-set dane people)) ; The green house is immediately to the left of the white house. (amb-require (= (house-set green colors) (1- (house-set white colors)))) ; They drink coffee in the green house. (house-force coffee drinks (house-set green colors)) ; The man who smokes Pall Mall has birds. (house-force birds animals (house-set pallmall smoke)) ; In the yellow house they smoke Dunhill. (house-force dunhill smoke (house-set yellow colors)) ; The Norwegian lives next to the blue house. (house-next (house-set norvegian people) (house-set blue colors)) ; The man who smokes Blend lives in the house next to the house with cats. (house-next (house-set blend smoke) (house-set cats animals)) ; In a house next to the house where they have a horse, they smoke Dunhill. (house-next (house-set horse animals) (house-set dunhill smoke)) ; The man who smokes Blue Master drinks beer. (house-force beer drinks (house-set bluemaster smoke)) ; The German smokes Prince. (house-force prince smoke (house-set german people)) ; They drink water in a house next to the house where they smoke Blend. (house-next (house-set water drinks) (house-set blend smoke))   ;; Finally .... the zebra 🐴 (house-set 🐴 animals)   (for ((i houses)) (writeln i (hash-values (vector-ref H i)))) (writeln '----------)   (amb-fail) ;; will ensure ALL solutions are printed )  
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>
#Erlang
Erlang
  -module(xml_xpath). -include_lib("xmerl/include/xmerl.hrl").   -export([main/0]).   main() -> XMLDocument = "<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>", {Document,_} = xmerl_scan:string(XMLDocument),   io:format("First item:\n~s\n", [lists:flatten( xmerl:export_simple( [hd(xmerl_xpath:string("//item[1]", Document))], xmerl_xml, [{prolog, ""}]))]),   io:format("Prices:\n"), [ io:format("~s\n",[Content#xmlText.value]) || #xmlElement{content = [Content|_]} <- xmerl_xpath:string("//price", Document)],   io:format("Names:\n"), [ Content#xmlText.value || #xmlElement{content = [Content|_]} <- xmerl_xpath:string("//name", Document)].  
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.
#DWScript
DWScript
type TColorFuncX = function (x : Integer) : Integer;   type TSquareBoard = class Scale : Integer; Pix : array of array of Integer;   constructor Create(aScale : Integer); begin Scale := aScale; Pix := new Integer[aScale*12+1, aScale*12+1]; end;   method Print; begin var i, j : Integer; for i:=0 to Pix.High do begin for j:=0 to Pix.High do begin case Pix[j, i] of 1 : Print('.'); 2 : Print('#'); else Print(' '); end; end; PrintLn(''); end; end;   method DrawCircle(cx, cy, cr : Integer; color : TColorFuncX); begin var rr := Sqr(cr*Scale); var x, y : Integer; for x := 0 to Pix.High do begin for y := 0 to Pix.High do begin if Sqr(x-cx*Scale)+Sqr(y-cy*Scale)<=rr then Pix[x, y] := color(x); end; end; end;   method ColorHalf(x : Integer) : Integer; begin if (x<6*Scale) then Result:=1 else Result:=2; end;   method ColorYin(x : Integer) : Integer; begin Result:=2; end;   method ColorYang(x : Integer) : Integer; begin Result:=1; end;   method YinYang; begin DrawCircle(6, 6, 6, ColorHalf); DrawCircle(6, 3, 3, ColorYang); DrawCircle(6, 9, 3, ColorYin); DrawCircle(6, 9, 1, ColorYang); DrawCircle(6, 3, 1, ColorYin); end;   end;   var sq := new TSquareBoard(2); sq.YinYang; sq.Print;   sq := new TSquareBoard(1); sq.YinYang; sq.Print;
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
#Common_Lisp
Common Lisp
(defun Y (f) ((lambda (g) (funcall g g)) (lambda (g) (funcall f (lambda (&rest a) (apply (funcall g g) a))))))   (defun fac (n) (funcall (Y (lambda (f) (lambda (n) (if (zerop n) 1 (* n (funcall f (1- n))))))) n))   (defun fib (n) (funcall (Y (lambda (f) (lambda (n a b) (if (< n 1) a (funcall f (1- n) b (+ a b)))))) n 0 1))   ? (mapcar #'fac '(1 2 3 4 5 6 7 8 9 10)) (1 2 6 24 120 720 5040 40320 362880 3628800))   ? (mapcar #'fib '(1 2 3 4 5 6 7 8 9 10)) (1 1 2 3 5 8 13 21 34 55)
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 0 1 5 6 14 2 4 7 13 15 3 8 12 16 21 9 11 17 20 22 10 18 19 23 24 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Common_Lisp
Common Lisp
(defun zigzag (n) (flet ((move (i j) (if (< j (1- n)) (values (max 0 (1- i)) (1+ j)) (values (1+ i) j)))) (loop with a = (make-array (list n n) :element-type 'integer) with x = 0 with y = 0 for v from 0 below (* n n) do (setf (aref a x y) v) (if (evenp (+ x y)) (setf (values x y) (move x y)) (setf (values y x) (move y x))) finally (return a))))
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].
#Ruby
Ruby
def yellow(n) a = [1, 2, 3] b = { 1 => true, 2 => true, 3 => true } i = 4 while n > a.length if !b[i] && i.gcd(a[-1]) == 1 && i.gcd(a[-2]) > 1 a << i b[i] = true i = 4 end i += 1 end a end   p yellow(30)
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].
#Rust
Rust
// [dependencies] // num = "0.3" // plotters = "^0.2.15"   use num::integer::gcd; use plotters::prelude::*; use std::collections::HashSet;   fn yellowstone_sequence() -> impl std::iter::Iterator<Item = u32> { let mut sequence: HashSet<u32> = HashSet::new(); let mut min = 1; let mut n = 0; let mut n1 = 0; let mut n2 = 0; std::iter::from_fn(move || { n2 = n1; n1 = n; if n < 3 { n += 1; } else { n = min; while !(!sequence.contains(&n) && gcd(n1, n) == 1 && gcd(n2, n) > 1) { n += 1; } } sequence.insert(n); while sequence.contains(&min) { sequence.remove(&min); min += 1; } Some(n) }) }   // Based on the example in the "Quick Start" section of the README file for // the plotters library. fn plot_yellowstone(filename: &str) -> Result<(), Box<dyn std::error::Error>> { let root = BitMapBackend::new(filename, (800, 600)).into_drawing_area(); root.fill(&WHITE)?; let mut chart = ChartBuilder::on(&root) .caption("Yellowstone Sequence", ("sans-serif", 24).into_font()) .margin(10) .x_label_area_size(20) .y_label_area_size(20) .build_ranged(0usize..100usize, 0u32..180u32)?; chart.configure_mesh().draw()?; chart.draw_series(LineSeries::new( yellowstone_sequence().take(100).enumerate(), &BLUE, ))?; Ok(()) }   fn main() { println!("First 30 Yellowstone numbers:"); for y in yellowstone_sequence().take(30) { print!("{} ", y); } println!(); match plot_yellowstone("yellowstone.png") { Ok(()) => {} Err(error) => eprintln!("Error: {}", error), } }
http://rosettacode.org/wiki/Yahoo!_search_interface
Yahoo! search interface
Create a class for searching Yahoo! results. It must implement a Next Page method, and read URL, Title and Content from results.
#Ruby
Ruby
require 'open-uri' require 'hpricot'   SearchResult = Struct.new(:url, :title, :content)   class SearchYahoo @@urlinfo = [nil, 'ca.search.yahoo.com', 80, '/search', nil, nil]   def initialize(term) @term = term @page = 1 @results = nil @url = URI::HTTP.build(@@urlinfo) end   def next_result if not @results @results = [] fetch_results elsif @results.empty? next_page end @results.shift end   def fetch_results @url.query = URI.escape("p=%s&b=%d" % [@term, @page]) doc = open(@url) { |f| Hpricot(f) } parse_html(doc) end   def next_page @page += 10 fetch_results end   def parse_html(doc) doc.search("div#main").search("div").each do |div| next unless div.has_attribute?("class") and div.get_attribute("class").index("res") == 0 result = SearchResult.new div.search("a").each do |link| next unless link.has_attribute?("class") and link.get_attribute("class") == "yschttl spt" result.url = link.get_attribute("href") result.title = link.inner_text end div.search("div").each do |abstract| next unless abstract.has_attribute?("class") and abstract.get_attribute("class").index("abstr") result.content = abstract.inner_text end @results << result end end end   s = SearchYahoo.new("test") 15.times do |i| result = s.next_result puts i+1 puts result.title puts result.url puts result.content puts end
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 {\displaystyle 5^{4^{3^{2}}}} Confirm that the first and last twenty digits of the answer are: 62060698786608744707...92256259918212890625 Find and show the number of decimal digits in the answer. Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead. Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value. Related tasks   Long multiplication   Exponentiation order   exponentiation operator   Exponentiation with infix operators in (or operating on) the base
#Maxima
Maxima
block([s, n], s: string(5^4^3^2), n: slength(s), print(substring(s, 1, 21), "...", substring(s, n - 19)), n); /* 62060698786608744707...92256259918212890625 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
#Nanoquery
Nanoquery
value = str(5^(4^(3^2)))   first20 = value.substring(0,20) last20 = value.substring(len(value) - 20)   println "The first twenty digits are " + first20 println "The last twenty digits are " + last20   if (first20 = "62060698786608744707") && (last20 = "92256259918212890625") println "\nThese digits are correct.\n" end   println "The result is " + len(str(value)) + " digits long"
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
#Nemerle
Nemerle
using System.Console; using System.Numerics; using System.Numerics.BigInteger;   module BigInt { Main() : void { def n = Pow(5, Pow(4, Pow(3, 2) :> int) :> int).ToString(); def len = n.Length; def first20 = n.Substring(0, 20); def last20 = n.Substring(len - 20, 20);   assert (first20 == "62060698786608744707", "High order digits are incorrect"); assert (last20 == "92256259918212890625", "Low order digits are incorrect"); assert (len == 183231, "Result contains wrong number of digits");   WriteLine("Result: {0} ... {1}", first20, last20); WriteLine($"Length of result: $len digits"); } }
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
#Perl
Perl
my @fib;   sub fib { my $n = shift; return 1 if $n < 2; return $fib[$n] //= fib($n-1)+fib($n-2); }   sub zeckendorf { my $n = shift; return "0" unless $n; my $i = 1; $i++ while fib($i) <= $n; my $z = ''; while( --$i ) { $z .= "0", next if fib( $i ) > $n; $z .= "1"; $n -= fib( $i ); } return $z; }   printf "%4d: %8s\n", $_, zeckendorf($_) for 0..20;  
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#Component_Pascal
Component Pascal
  MODULE Doors100; IMPORT StdLog;   PROCEDURE Do*; VAR i,j: INTEGER; closed: ARRAY 101 OF BOOLEAN; BEGIN (* initialization of closed to true *) FOR i := 0 TO LEN(closed) - 1 DO closed[i] := TRUE END; (* process *) FOR i := 1 TO LEN(closed) DO; j := 1; WHILE j < LEN(closed) DO IF j MOD i = 0 THEN closed[j] := ~closed[j] END;INC(j) END END; (* print results *) i := 1; WHILE i < LEN(closed) DO IF (i - 1) MOD 10 = 0 THEN StdLog.Ln END; IF closed[i] THEN StdLog.String("C ") ELSE StdLog.String("O ") END; INC(i) END; END Do; END Doors100.    
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)
#Golfscript
Golfscript
[1 2 3]:a; # numeric only array, assigned to a and then dropped 10,:a; # assign to a [0 1 2 3 4 5 6 7 8 9] a 0= puts # pick element at index 0 (stack: 0) a 10+puts # append 10 to the end of a 10 a+puts # prepend 10 to a
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.
#Tcl
Tcl
package require math::complexnumbers namespace import math::complexnumbers::*   set a [complex 1 1] set b [complex 3.14159 1.2] puts [tostring [+ $a $b]] ;# ==> 4.14159+2.2i puts [tostring [* $a $b]] ;# ==> 1.94159+4.34159i puts [tostring [pow $a [complex -1 0]]] ;# ==> 0.5-0.4999999999999999i puts [tostring [- $a]] ;# ==> -1.0-i
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
#PHP
PHP
<?php echo pow(0,0); echo 0 ** 0; // PHP 5.6+ only ?>
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
#PicoLisp
PicoLisp
  (** 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
#Pike
Pike
write( pow(0, 0) +"\n" );
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives in the red house.   The Swede has a dog.   The Dane drinks tea.   The green house is immediately to the left of the white house.   They drink coffee in the green house.   The man who smokes Pall Mall has birds.   In the yellow house they smoke Dunhill.   In the middle house they drink milk.   The Norwegian lives in the first house.   The man who smokes Blend lives in the house next to the house with cats.   In a house next to the house where they have a horse, they smoke Dunhill.   The man who smokes Blue Master drinks beer.   The German smokes Prince.   The Norwegian lives next to the blue house.   They drink water in a house next to the house where they smoke Blend. The question is, who owns the zebra? Additionally, list the solution for all the houses. Optionally, show the solution is unique. Related tasks   Dinesman's multiple-dwelling problem   Twelve statements
#Elixir
Elixir
defmodule ZebraPuzzle do defp adjacent?(n,i,g,e) do Enum.any?(0..3, fn x -> (Enum.at(n,x)==i and Enum.at(g,x+1)==e) or (Enum.at(n,x+1)==i and Enum.at(g,x)==e) end) end   defp leftof?(n,i,g,e) do Enum.any?(0..3, fn x -> Enum.at(n,x)==i and Enum.at(g,x+1)==e end) end   defp coincident?(n,i,g,e) do Enum.with_index(n) |> Enum.any?(fn {x,idx} -> x==i and Enum.at(g,idx)==e end) end   def solve(content) do colours = permutation(content[:Colour]) pets = permutation(content[:Pet]) drinks = permutation(content[:Drink]) smokes = permutation(content[:Smoke]) Enum.each(permutation(content[:Nationality]), fn nation -> if hd(nation) == :Norwegian, do: # 10 Enum.each(colours, fn colour -> if leftof?(colour, :Green, colour, :White) and # 5 coincident?(nation, :English, colour, :Red) and # 2 adjacent?(nation, :Norwegian, colour, :Blue), do: # 15 Enum.each(pets, fn pet -> if coincident?(nation, :Swedish, pet, :Dog), do: # 3 Enum.each(drinks, fn drink -> if Enum.at(drink,2) == :Milk and # 9 coincident?(nation, :Danish, drink, :Tea) and # 4 coincident?(colour, :Green, drink, :Coffee), do: # 6 Enum.each(smokes, fn smoke -> if coincident?(smoke, :PallMall, pet, :Birds) and # 7 coincident?(smoke, :Dunhill, colour, :Yellow) and # 8 coincident?(smoke, :BlueMaster, drink, :Beer) and # 13 coincident?(smoke, :Prince, nation, :German) and # 14 adjacent?(smoke, :Blend, pet, :Cats) and # 11 adjacent?(smoke, :Blend, drink, :Water) and # 16 adjacent?(smoke, :Dunhill, pet, :Horse), do: # 12 print_out(content, transpose([nation, colour, pet, drink, smoke])) end)end)end)end)end) end   defp permutation([]), do: [[]] defp permutation(list) do for x <- list, y <- permutation(list -- [x]), do: [x|y] end   defp transpose(lists) do List.zip(lists) |> Enum.map(&Tuple.to_list/1) end   defp print_out(content, result) do width = for {k,v}<-content, do: Enum.map([k|v], &length(to_char_list &1)) |> Enum.max fmt = Enum.map_join(width, " ", fn w -> "~-#{w}s" end) <> "~n" nation = Enum.find(result, fn x -> :Zebra in x end) |> hd IO.puts "The Zebra is owned by the man who is #{nation}\n"  :io.format fmt, Keyword.keys(content)  :io.format fmt, Enum.map(width, fn w -> String.duplicate("-", w) end) fmt2 = String.replace(fmt, "s", "w", global: false) Enum.with_index(result) |> Enum.each(fn {x,i} -> :io.format fmt2, [i+1 | x] end) end end   content = [ House: '', Nationality: ~w[English Swedish Danish Norwegian German]a, Colour: ~w[Red Green White Blue Yellow]a, Pet: ~w[Dog Birds Cats Horse Zebra]a, Drink: ~w[Tea Coffee Milk Beer Water]a, Smoke: ~w[PallMall Dunhill BlueMaster Prince Blend]a ]   ZebraPuzzle.solve(content)
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>
#F.23
F#
  open System.IO open System.Xml.XPath   let xml = new StringReader(""" <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> """)   let nav = XPathDocument(xml).CreateNavigator()   // first "item"; throws if none exists let item = nav.SelectSingleNode(@"//item[1]")   // apply a operation (print text value) to all price elements for price in nav.Select(@"//price") do printfn "%s" (price.ToString())   // array of all name elements let names = seq { for name in nav.Select(@"//name") do yield name } |> Seq.toArray
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#F.C5.8Drmul.C3.A6
Fōrmulæ
: circle ( x y r h -- f ) rot - dup * rot dup * + swap dup * swap < invert ;   : pixel ( r x y -- r c ) 2dup 4 pick 6 / 5 pick 2 / negate circle if 2drop '#' exit then 2dup 4 pick 6 / 5 pick 2 / circle if 2drop '.' exit then 2dup 4 pick 2 / 5 pick 2 / negate circle if 2drop '.' exit then 2dup 4 pick 2 / 5 pick 2 / circle if 2drop '#' exit then 2dup 4 pick 0 circle if drop 0< if '.' exit else '#' exit then then 2drop bl ;   : yinyang ( r -- ) dup dup 1+ swap -1 * do cr dup dup 2 * 1+ swap -2 * do I 2 / J pixel emit loop loop drop ;
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.
#Forth
Forth
: circle ( x y r h -- f ) rot - dup * rot dup * + swap dup * swap < invert ;   : pixel ( r x y -- r c ) 2dup 4 pick 6 / 5 pick 2 / negate circle if 2drop '#' exit then 2dup 4 pick 6 / 5 pick 2 / circle if 2drop '.' exit then 2dup 4 pick 2 / 5 pick 2 / negate circle if 2drop '.' exit then 2dup 4 pick 2 / 5 pick 2 / circle if 2drop '#' exit then 2dup 4 pick 0 circle if drop 0< if '.' exit else '#' exit then then 2drop bl ;   : yinyang ( r -- ) dup dup 1+ swap -1 * do cr dup dup 2 * 1+ swap -2 * do I 2 / J pixel emit loop loop drop ;
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
#Crystal
Crystal
require "big"   struct RecursiveFunc(T) # a generic recursive function wrapper... getter recfnc : RecursiveFunc(T) -> T def initialize(@recfnc) end end   struct YCombo(T) # a struct or class needs to be used so as to be generic... def initialize (@fnc : Proc(T) -> T) end def fixy g = -> (x : RecursiveFunc(T)) { @fnc.call(-> { x.recfnc.call(x) }) } g.call(RecursiveFunc(T).new(g)) end end   def fac(x) # horrendouly inefficient not using tail calls... facp = -> (fn : Proc(BigInt -> BigInt)) { -> (n : BigInt) { n < 2 ? n : n * fn.call.call(n - 1) } } YCombo.new(facp).fixy.call(BigInt.new(x)) end   def fib(x) # horrendouly inefficient not using tail calls... facp = -> (fn : Proc(BigInt -> BigInt)) { -> (n : BigInt) { n < 3 ? n - 1 : fn.call.call(n - 2) + fn.call.call(n - 1) } } YCombo.new(facp).fixy.call(BigInt.new(x)) end   puts fac(10) puts fib(11) # starts from 0 not 1!
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 0 1 5 6 14 2 4 7 13 15 3 8 12 16 21 9 11 17 20 22 10 18 19 23 24 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#Crystal
Crystal
def zigzag(n) (seq=(0...n).to_a).product(seq) .sort_by {|x,y| [x+y, (x+y).even? ? y : -y]} .map_with_index{|v, i| {v, i}}.sort.map(&.last).each_slice(n).to_a end   def print_matrix(m) format = "%#{m.flatten.max.to_s.size}d " * m[0].size m.each {|row| puts format % row} end   print_matrix zigzag(5)
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].
#Tcl
Tcl
proc gcd {a b} { while {$b} { lassign [list $b [expr {$a % $b}]] a b } return $a }   proc gen_yellowstones {{maxN 30}} { set r {} for {set n 1} {$n <= $maxN} {incr n} { if {$n <= 3} { lappend r $n } else { ## NB: list indices start at 0, not 1. set pred [lindex $r end ] ;# a(n-1): coprime set prepred [lindex $r end-1] ;# a(n-2): not coprime for {set k 4} {1} {incr k} { if {[lsearch -exact $r $k] >= 0} { continue } if {1 != [gcd $k $pred ]} { continue } if {1 == [gcd $k $prepred]} { continue } ## candidate k survived all tests... break } lappend r $k } } return $r } puts "The first 30 Yellowstone numbers are:" puts [gen_yellowstones]
http://rosettacode.org/wiki/Yahoo!_search_interface
Yahoo! search interface
Create a class for searching Yahoo! results. It must implement a Next Page method, and read URL, Title and Content from results.
#Run_BASIC
Run BASIC
'-------------------------------------------------------------------------- ' send this from the server to the clients browser '-------------------------------------------------------------------------- html "<table border=1 cellpadding=0 cellspacing=0 bgcolor=wheat>" html "<tr><td align=center colspan=2>Yahoo Search</td></tr>" html "<tr><td align=right>Find</td><td>" textbox #find,findThis$,30   html "</td></tr><tr><td align=right>Page</td><td>" textbox #page,findPage$,2   html "</td></tr><tr><td align=center colspan=2>" button #s, "Search", [search] html " " button #ex, "Exit", [exit]   html "</td><td></td></tr></table>" wait   '-------------------------------------------------------------------------- ' get search stuff from the clients browser '-------------------------------------------------------------------------- [search] findThis$ = trim$(#find contents$()) findPage$ = trim$(#page contents$()) findPage = max(val(findPage$),1) ' must be at least 1   '-------------------------------------------------------------------------- ' sho page but keep user interface at the top by not clearing the page (cls) ' so they can change the search or page ' ------------------------------------------------------------------------- url$ = "http://search.yahoo.com/search?p=";findThis$;"&b=";((findPage - 1) * 10) + 1 html httpget$(url$) wait   [exit] cls ' clear browser screen and get outta here wait
http://rosettacode.org/wiki/Yahoo!_search_interface
Yahoo! search interface
Create a class for searching Yahoo! results. It must implement a Next Page method, and read URL, Title and Content from results.
#Tcl
Tcl
package require http   proc fix s { string map {<b>...</b> "" <b> "" </b> "" <wbr> "" "<wbr />" ""} \ [regsub "</a></h3></div>.*" $s ""] } proc YahooSearch {term {page 1}} { # Build the (ugly) scraper URL append re {<a class="yschttl spt" href=".+?" >(.+?)</a></h3>} append re {</div><div class="abstr">(.+?)} append re {</div><span class=url>(.+?)</span>}   # Perform the query; note that this handles special characters # in the query term correctly set q [http::formatQuery p $term b [expr {$page*10-9}]] set token [http::geturl http://search.yahoo.com/search?$q] set data [http::data $token] http::cleanup $token   # Assemble the results into a nice list set results {} foreach {- title content url} [regexp -all -inline $re $data] { lappend results [fix $title] [fix $content] [fix $url] }   # set up the call for the next page interp alias {} Nextpage {} YahooSearch $term [incr page]   return $results }   # Usage: get the first two pages of results foreach {title content url} [YahooSearch "test"] { puts $title } foreach {title content url} [Nextpage] { puts $title }
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
#NewLisp
NewLisp
  ;;; No built-in big integer exponentiation (define (exp-big x n) (setq x (bigint x)) (let (y 1L) (if (= n 0) 1L (while (> n 1) (if (odd? n) (setq y (* x y))) (setq x (* x x) n (/ n 2))) (* x y)))) ; ;;; task (define (test) (local (res) ; drop the "L" at the end (setq res (0 (- (length res) 1) (string (exp-big 5 (exp-big 4 (exp-big 3 2)))))) (println "The result has: " (length res) " digits") (println "First 20 digits: " (0 20 res)) (println "Last 20 digits: " (-20 20 res))))  
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
#Phix
Phix
function zeckendorf(integer n) integer r = 0, c sequence fib = {1,1} while fib[$]<n do fib &= fib[$] + fib[$-1] end while for i=length(fib) to 2 by -1 do c = n>=fib[i] r += r+c n -= c*fib[i] end for return r end function for i=0 to 20 do printf(1,"%2d: %7b\n",{i,zeckendorf(i)}) end for
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.
#Coq
Coq
Require Import List.   Fixpoint rep {A} (a : A) n := match n with | O => nil | S n' => a::(rep a n') end.   Fixpoint flip (l : list bool) (n k : nat) : list bool := match l with | nil => nil | cons h t => match k with | O => (negb h) :: (flip t n n) | S k' => h :: (flip t n k') end end.   Definition flipeach l n := flip l n n.   Fixpoint flipwhile l n := match n with | O => flipeach l 0 | S n' => flipwhile (flipeach l (S n')) n' end.   Definition prison cells := flipwhile (rep false cells) cells.
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)
#Groovy
Groovy
def aa = [ 1, 25, 31, -3 ] // list def a = [0] * 100 // list of 100 zeroes def b = 1..9 // range notation def c = (1..10).collect { 2.0**it } // each output element is 2**(corresponding invoking list element)   // There are no true "multi-dimensional" arrays in Groovy (as in most C-derived languages). // Use lists of lists in natural ("row major") order as a stand in. def d = (0..1).collect { i -> (1..5).collect { j -> 2**(5*i+j) as double } } def e = [ [ 1.0, 2.0, 3.0, 4.0 ], [ 5.0, 6.0, 7.0, 8.0 ], [ 9.0, 10.0, 11.0, 12.0 ], [ 13.0, 14.0, 15.0, 16.0 ] ]   println aa println b println c println() d.each { print "["; it.each { elt -> printf "%7.1f ", elt }; println "]" } println() e.each { print "["; it.each { elt -> printf "%7.1f ", elt }; println "]" }
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.
#TI-83_BASIC
TI-83 BASIC
■ √(–1)  ■ ^2 —1 ■  + 1 1 +  ■ (1+) * 2 2 + 2* ■ (1+) (2) —2 + 2* ■ —(1+) —1 -  ■ 1/(2) —1 -  ■ real(1 + 2) 1 ■ imag(1 + 2) 2
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.
#TI-89_BASIC
TI-89 BASIC
■ √(–1)  ■ ^2 —1 ■  + 1 1 +  ■ (1+) * 2 2 + 2* ■ (1+) (2) —2 + 2* ■ —(1+) —1 -  ■ 1/(2) —1 -  ■ real(1 + 2) 1 ■ imag(1 + 2) 2
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time,   you may also try something like: x = 0 y = 0 z = x**y say 'z=' z Show the result here. And of course use any symbols or notation that is supported in your computer programming language for exponentiation. See also The Wiki entry: Zero to the power of zero. The Wiki entry: History of differing points of view. The MathWorld™ entry: exponent laws. Also, in the above MathWorld™ entry, see formula (9): x 0 = 1 {\displaystyle x^{0}=1} . The OEIS entry: The special case of zero to the zeroth power
#PL.2FI
PL/I
zhz: Proc Options(Main); Dcl a dec float(10) Init(1); Dcl b dec float(10) Init(0); Put skip list('1**0=',a**b); Put skip list('0**1=',b**a); Put skip list('0**0=',b**b); 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
#Plain_English
Plain English
To run: Start up. Put 0 into a number. Raise the number to 0. Convert the number to a string. Write the string to the console. Wait for the escape key. Shut down.
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
#Erlang
Erlang
  -module( zebra_puzzle ).   -export( [task/0] ).   -record( house, {colour, drink, nationality, number, pet, smoke} ). -record( sorted_houses, {house_1s=[], house_2s=[], house_3s=[], house_4s=[], house_5s=[]} ).   task() -> Houses = [#house{colour=C, drink=D, nationality=N, number=Nr, pet=P, smoke=S} || C <- all_colours(), D <- all_drinks(), N <- all_nationalities(), Nr <- all_numbers(), P <- all_pets(), S <- all_smokes(), is_all_single_house_rules_ok(C, D, N, Nr, P, S)], Sorted_houses = lists:foldl( fun house_number_sort/2, #sorted_houses{}, Houses ), Streets = [[H1, H2, H3, H4, H5] || H1 <- Sorted_houses#sorted_houses.house_1s, H2 <- Sorted_houses#sorted_houses.house_2s, H3 <- Sorted_houses#sorted_houses.house_3s, H4 <- Sorted_houses#sorted_houses.house_4s, H5 <- Sorted_houses#sorted_houses.house_5s, is_all_multi_house_rules_ok(H1, H2, H3, H4, H5)], [Nationality] = [N || #house{nationality=N, pet=zebra} <- lists:flatten(Streets)], io:fwrite( "~p owns the zebra~n", [Nationality] ), io:fwrite( "All solutions ~p~n", [Streets] ), io:fwrite( "Number of solutions ~p~n", [erlang:length(Streets)] ).       all_colours() -> [blue, green, red, white, yellow].   all_drinks() -> [beer, coffe, milk, tea, water].   all_nationalities() -> [danish, english, german, norveigan, swedish].   all_numbers() -> [1, 2, 3, 4, 5].   all_pets() -> [birds, cats, dog, horse, zebra].   all_smokes() -> [blend, 'blue master', dunhill, 'pall mall', prince].   house_number_sort( #house{number=1}=House, #sorted_houses{house_1s=Houses_1s}=Sorted_houses ) -> Sorted_houses#sorted_houses{house_1s=[House | Houses_1s]}; house_number_sort( #house{number=2}=House, #sorted_houses{house_2s=Houses_2s}=Sorted_houses ) -> Sorted_houses#sorted_houses{house_2s=[House | Houses_2s]}; house_number_sort( #house{number=3}=House, #sorted_houses{house_3s=Houses_3s}=Sorted_houses ) -> Sorted_houses#sorted_houses{house_3s=[House | Houses_3s]}; house_number_sort( #house{number=4}=House, #sorted_houses{house_4s=Houses_4s}=Sorted_houses ) -> Sorted_houses#sorted_houses{house_4s=[House | Houses_4s]}; house_number_sort( #house{number=5}=House, #sorted_houses{house_5s=Houses_5s}=Sorted_houses ) -> Sorted_houses#sorted_houses{house_5s=[House | Houses_5s]}.   is_all_different( [_H] ) -> true; is_all_different( [H | T] ) -> not lists:member( H, T ) andalso is_all_different( T ).   is_all_multi_house_rules_ok( House1, House2, House3, House4, House5 ) -> is_rule_1_ok( House1, House2, House3, House4, House5 ) andalso is_rule_5_ok( House1, House2, House3, House4, House5 ) andalso is_rule_11_ok( House1, House2, House3, House4, House5 ) andalso is_rule_12_ok( House1, House2, House3, House4, House5 ) andalso is_rule_15_ok( House1, House2, House3, House4, House5 ) andalso is_rule_16_ok( House1, House2, House3, House4, House5 ).   is_all_single_house_rules_ok( Colour, Drink, Nationality, Number, Pet, Smoke ) -> is_rule_ok( {rule_number, 2}, {Nationality, english}, {Colour, red}) andalso is_rule_ok( {rule_number, 3}, {Nationality, swedish}, {Pet, dog}) andalso is_rule_ok( {rule_number, 4}, {Nationality, danish}, {Drink, tea}) andalso is_rule_ok( {rule_number, 6}, {Drink, coffe}, {Colour, green}) andalso is_rule_ok( {rule_number, 7}, {Smoke, 'pall mall'}, {Pet, birds}) andalso is_rule_ok( {rule_number, 8}, {Colour, yellow}, {Smoke, dunhill}) andalso is_rule_ok( {rule_number, 9}, {Number, 3}, {Drink, milk}) andalso is_rule_ok( {rule_number, 10}, {Nationality, norveigan}, {Number, 1}) andalso is_rule_ok( {rule_number, 13}, {Smoke, 'blue master'}, {Drink, beer}) andalso is_rule_ok( {rule_number, 14}, {Nationality, german}, {Smoke, prince}).   is_rule_ok( _Rule_number, {A, A}, {B, B} ) -> true; is_rule_ok( _Rule_number, _A, {B, B} ) -> false; is_rule_ok( _Rule_number, {A, A}, _B ) -> false; is_rule_ok( _Rule_number, _A, _B ) -> true.   is_rule_1_ok( #house{number=1}=H1, #house{number=2}=H2, #house{number=3}=H3, #house{number=4}=H4, #house{number=5}=H5 ) -> is_all_different( [H1#house.colour, H2#house.colour, H3#house.colour, H4#house.colour, H5#house.colour] ) andalso is_all_different( [H1#house.drink, H2#house.drink, H3#house.drink, H4#house.drink, H5#house.drink] ) andalso is_all_different( [H1#house.nationality, H2#house.nationality, H3#house.nationality, H4#house.nationality, H5#house.nationality] ) andalso is_all_different( [H1#house.pet, H2#house.pet, H3#house.pet, H4#house.pet, H5#house.pet] ) andalso is_all_different( [H1#house.smoke, H2#house.smoke, H3#house.smoke, H4#house.smoke, H5#house.smoke] ); is_rule_1_ok( _House1, _House2, _House3, _House4, _House5 ) -> false.   is_rule_5_ok( #house{colour=green}, #house{colour=white}, _House3, _House4, _House5 ) -> true; is_rule_5_ok( _House1, #house{colour=green}, #house{colour=white}, _House4, _House5 ) -> true; is_rule_5_ok( _House1, _House2, #house{colour=green}, #house{colour=white}, _House5 ) -> true; is_rule_5_ok( _House1, _House2, _House3, #house{colour=green}, #house{colour=white} ) -> true; is_rule_5_ok( _House1, _House2, _House3, _House4, _House5 ) -> false.   is_rule_11_ok( #house{smoke=blend}, #house{pet=cats}, _House3, _House4, _House5 ) -> true; is_rule_11_ok( _House1, #house{smoke=blend}, #house{pet=cats}, _House4, _House5 ) -> true; is_rule_11_ok( _House1, _House2, #house{smoke=blend}, #house{pet=cats}, _House5 ) -> true; is_rule_11_ok( _House1, _House2, _House3, #house{smoke=blend}, #house{pet=cats} ) -> true; is_rule_11_ok( #house{pet=cats}, #house{smoke=blend}, _House3, _House4, _House5 ) -> true; is_rule_11_ok( _House1, #house{pet=cats}, #house{smoke=blend}, _House4, _House5 ) -> true; is_rule_11_ok( _House1, _House2, #house{pet=cats}, #house{smoke=blend}, _House5 ) -> true; is_rule_11_ok( _House1, _House2, _House3, #house{pet=cats}, #house{smoke=blend} ) -> true; is_rule_11_ok( _House1, _House2, _House3, _House4, _House5 ) -> false.   is_rule_12_ok( #house{smoke=dunhill}, #house{pet=horse}, _House3, _House4, _House5 ) -> true; is_rule_12_ok( _House1, #house{smoke=dunhill}, #house{pet=horse}, _House4, _House5 ) -> true; is_rule_12_ok( _House1, _House2, #house{smoke=dunhill}, #house{pet=horse}, _House5 ) -> true; is_rule_12_ok( _House1, _House2, _House3, #house{smoke=dunhill}, #house{pet=horse} ) -> true; is_rule_12_ok( #house{pet=horse}, #house{smoke=dunhill}, _House3, _House4, _House5 ) -> true; is_rule_12_ok( _House1, #house{pet=horse}, #house{smoke=dunhill}, _House4, _House5 ) -> true; is_rule_12_ok( _House1, _House2, #house{pet=horse}, #house{smoke=dunhill}, _House5 ) -> true; is_rule_12_ok( _House1, _House2, _House3, #house{pet=horse}, #house{smoke=dunhill} ) -> true; is_rule_12_ok( _House1, _House2, _House3, _House4, _House5 ) -> false.   is_rule_15_ok( #house{nationality=norveigan}, #house{colour=blue}, _House3, _House4, _House5 ) -> true; is_rule_15_ok( _House1, #house{nationality=norveigan}, #house{colour=blue}, _House4, _House5 ) -> true; is_rule_15_ok( _House1, _House2, #house{nationality=norveigan}, #house{colour=blue}, _House5 ) -> true; is_rule_15_ok( _House1, _House2, _House3, #house{nationality=norveigan}, #house{colour=blue} ) -> true; is_rule_15_ok( #house{colour=blue}, #house{nationality=norveigan}, _House3, _House4, _House5 ) -> true; is_rule_15_ok( _House1, #house{colour=blue}, #house{nationality=norveigan}, _House4, _House5 ) -> true; is_rule_15_ok( _House1, _House2, #house{drink=water}, #house{nationality=norveigan}, _House5 ) -> true; is_rule_15_ok( _House1, _House2, _House3, #house{drink=water}, #house{nationality=norveigan} ) -> true; is_rule_15_ok( _House1, _House2, _House3, _House4, _House5 ) -> false.   is_rule_16_ok( #house{smoke=blend}, #house{drink=water}, _House3, _House4, _House5 ) -> true; is_rule_16_ok( _House1, #house{smoke=blend}, #house{drink=water}, _House4, _House5 ) -> true; is_rule_16_ok( _House1, _House2, #house{smoke=blend}, #house{drink=water}, _House5 ) -> true; is_rule_16_ok( _House1, _House2, _House3, #house{smoke=blend}, #house{drink=water} ) -> true; is_rule_16_ok( #house{drink=water}, #house{smoke=blend}, _House3, _House4, _House5 ) -> true; is_rule_16_ok( _House1, #house{drink=water}, #house{smoke=blend}, _House4, _House5 ) -> true; is_rule_16_ok( _House1, _House2, #house{drink=water}, #house{smoke=blend}, _House5 ) -> true; is_rule_16_ok( _House1, _House2, _House3, #house{drink=water}, #house{smoke=blend} ) -> true; is_rule_16_ok( _House1, _House2, _House3, _House4, _House5 ) -> 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>
#Factor
Factor
    ! Get first item element """<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>""" string>xml "item" deep-tag-named   ! Print out prices """<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>""" string>xml "price" deep-tags-named [ children>> first ] map   ! Array of all name elements """<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>""" string>xml "name" deep-tags-named  
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>
#Gastona
Gastona
#javaj#   <frames> oSal, XML Path sample, 300, 400   #data#   <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>   <DEEP_SQL_XML> DEEP DB, SELECT, xmelon_data ,, path pathStr ,, tag tagStr ,, patCnt ,, dataPlace ,, value   #listix#   <main> //parsing xml data ... GEN, :mem datos, xml XMELON, FILE2DB, :mem datos // //first item ... // // LOOP, SQL,, //SELECT patCnt AS patITEM1 FROM (@<DEEP_SQL_XML>) WHERE path_pathStr == '/inventory/section/item' LIMIT 1 ,HEAD, //<item ,, LOOP, SQL,, //SELECT * FROM (@<DEEP_SQL_XML>) WHERE patCnt == @<patITEM1> AND dataPlace == 'A' ,, , LINK, "" ,, ,, // @<tag_tagStr>="@<value>" ,, //> ,, // ,, LOOP, SQL,, //SELECT * FROM (@<DEEP_SQL_XML>) WHERE patCnt == @<patITEM1> AND dataPlace != 'A' ,, ,, // <@<tag_tagStr>>@<value></@<tag_tagStr>> ,TAIL, // ,TAIL, //</item> // // //report prices ... // LOOP, SQL,, //SELECT value FROM (@<DEEP_SQL_XML>) WHERE tag_tagStr == 'price' , LINK, ", " ,, @<value> // //put names into a variable // VAR=, tabnames, "name" LOOP, SQL,, //SELECT value FROM (@<DEEP_SQL_XML>) WHERE tag_tagStr == 'name' , LINK, "" ,, VAR+, tabnames, @<value> DUMP, data,, tabnames  
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.
#Go
Go
package main   import ( "fmt" "os" "text/template" )   var tmpl = `<?xml version="1.0"?> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="210" height="150"> <symbol id="yy" viewBox="0 0 200 200"> <circle stroke="black" stroke-width="2" fill="white" cx="100" cy="100" r="99" /> <path fill="black" d="M100 100 a49 49 0 0 0 0 -98 v-1 a99 99 0 0 1 0 198 v-1 a49 49 0 0 1 0 -98" /> <circle fill="black" cx="100" cy="51" r="17" /> <circle fill="white" cx="100" cy="149" r="17" /> </symbol> {{range .}}<use xlink:href="#yy" x="{{.X}}" y="{{.Y}}" width="{{.Sz}}" height="{{.Sz}}"/> {{end}}</svg> `   // structure specifies position and size to draw symbol type xysz struct { X, Y, Sz int }   // example data to specify drawing the symbol twice, // with different position and size. var yys = []xysz{ {20, 20, 100}, {140, 30, 60}, }   func main() { xt := template.New("") template.Must(xt.Parse(tmpl)) f, err := os.Create("yy.svg") if err != nil { fmt.Println(err) return } if err := xt.Execute(f, yys); err != nil { fmt.Println(err) } f.Close() }
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
D
import std.stdio, std.traits, std.algorithm, std.range;   auto Y(S, T...)(S delegate(T) delegate(S delegate(T)) f) { static struct F { S delegate(T) delegate(F) f; alias f this; } return (x => x(x))(F(x => f((T v) => x(x)(v)))); }   void main() { // Demo code: auto factorial = Y((int delegate(int) self) => (int n) => 0 == n ? 1 : n * self(n - 1) );   auto ackermann = Y((ulong delegate(ulong, ulong) self) => (ulong m, ulong n) { if (m == 0) return n + 1; if (n == 0) return self(m - 1, 1); return self(m - 1, self(m, n - 1)); });   writeln("factorial: ", 10.iota.map!factorial); writeln("ackermann(3, 5): ", ackermann(3, 5)); }
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, 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
#D
D
int[][] zigZag(in int n) pure nothrow @safe { static void move(in int n, ref int i, ref int j) pure nothrow @safe @nogc { if (j < n - 1) { if (i > 0) i--; j++; } else i++; }   auto a = new int[][](n, n); int x, y; foreach (v; 0 .. n ^^ 2) { a[y][x] = v; (x + y) % 2 ? move(n, x, y) : move(n, y, x); } return a; }   void main() { import std.stdio;   writefln("%(%(%2d %)\n%)", 5.zigZag); }
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].
#uBasic.2F4tH
uBasic/4tH
Dim @y(30)   @y(0) = 1 @y(1) = 2 @y(2) = 3   For i = 3 To 29 k = 3 Do k = k + 1 If (FUNC(_gcd(k, @y(i-2))) = 1) + (FUNC(_gcd(k, @y(i-1))) > 1) Then Continue EndIf   For j = 0 To i - 1 If @y(j) = k Then Unloop : Continue Next   @y(i) = k : Break Loop Next   For i = 0 To 29 Print @y(i); " "; Next   Print : End   _gcd Param (2) If b@ = 0 Then Return (a@) Return (FUNC(_gcd(b@, a@ % b@)))
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].
#VBA
VBA
  Function gcd(a As Long, b As Long) As Long If b = 0 Then gcd = a Exit Function End If gcd = gcd(b, a Mod b) End Function   Sub Yellowstone() Dim i As Long, j As Long, k As Long, Y(1 To 30) As Long   Y(1) = 1 Y(2) = 2 Y(3) = 3   For i = 4 To 30 k = 3 Do k = k + 1 If gcd(k, Y(i - 2)) = 1 Or gcd(k, Y(i - 1)) > 1 Then GoTo EndLoop: For j = 1 To i - 1 If Y(j) = k Then GoTo EndLoop: Next j Y(i) = k Exit Do EndLoop: Loop Next i   For i = 1 To 30 Debug.Print Y(i) & " "; Next i End Sub  
http://rosettacode.org/wiki/Yahoo!_search_interface
Yahoo! search interface
Create a class for searching Yahoo! results. It must implement a Next Page method, and read URL, Title and Content from results.
#TXR
TXR
#!/usr/bin/txr -f @(next :args) @(cases) @ QUERY @ PAGE @(or) @ (throw error "specify query and page# (from zero)") @(end) @(next (open-command "!wget -O - http://search.yahoo.com/search?p=@QUERY\&b=@{PAGE}1 2> /dev/null")) @(all) @ (coll)<a class="yschttl spt" href="@URL" @/[^>]+/>@TITLE</a>@(end) @(and) @ (coll)<div class="@/abstr|sm-abs/">@ABSTR</div>@(end) @(end) @(output) @ (repeat) TITLE: @TITLE URL: @URL TEXT: @ABSTR --- @ (end) @(end)  
http://rosettacode.org/wiki/Yahoo!_search_interface
Yahoo! search interface
Create a class for searching Yahoo! results. It must implement a Next Page method, and read URL, Title and Content from results.
#Wren
Wren
/* yahoo_search_interface.wren */   import "./pattern" for Pattern   class YahooSearch { construct new(url, title, desc) { _url = url _title = title _desc = desc }   toString { "URL: %(_url)\nTitle: %(_title)\nDescription: %(_desc)\n" } }   var CURLOPT_URL = 10002 var CURLOPT_FOLLOWLOCATION = 52 var CURLOPT_WRITEFUNCTION = 20011 var CURLOPT_WRITEDATA = 10001   foreign class Buffer { construct new() {} // C will allocate buffer of a suitable size   foreign value // returns buffer contents as a string }   foreign class Curl { construct easyInit() {}   foreign easySetOpt(opt, param)   foreign easyPerform()   foreign easyCleanup() }   var curl = Curl.easyInit()   var getContent = Fn.new { |url| var buffer = Buffer.new() curl.easySetOpt(CURLOPT_URL, url) curl.easySetOpt(CURLOPT_FOLLOWLOCATION, 1) curl.easySetOpt(CURLOPT_WRITEFUNCTION, 0) // write function to be supplied by C curl.easySetOpt(CURLOPT_WRITEDATA, buffer) curl.easyPerform() return buffer.value }   var p1 = Pattern.new("class/=\" d-ib ls-05 fz-20 lh-26 td-hu tc va-bot mxw-100p\" href/=\"[+1^\"]\"") var p2 = Pattern.new("class/=\" d-ib p-abs t-0 l-0 fz-14 lh-20 fc-obsidian wr-bw ls-n pb-4\">[+1^<]<") var p3 = Pattern.new("<span class/=\" fc-falcon\">[+1^<]<")   var pageSize = 7 var totalCount = 0   var yahooSearch = Fn.new { |query, page| System.print("Page %(page):\n=======\n") var next = (page - 1) * pageSize + 1 var url = "https://search.yahoo.com/search?fr=opensearch&pz=%(pageSize)&p=%(query)&b=%(next)" var content = getContent.call(url).replace("<b>", "").replace("</b>", "") var matches1 = p1.findAll(content) var count = matches1.count if (count == 0) return false var matches2 = p2.findAll(content) var matches3 = p3.findAll(content) totalCount = totalCount + count var ys = List.filled(count, null) for (i in 0...count) { var url = matches1[i].capsText[0] var title = matches2[i].capsText[0] var desc = matches3[i].capsText[0].replace("&#39;", "'") ys[i] = YahooSearch.new(url, title, desc) } System.print(ys.join("\n")) return true }   var page = 1 var limit = 2 var query = "rosettacode" System.print("Searching for '%(query)' on Yahoo!\n") while (page <= limit && yahooSearch.call(query, page)) { page = page + 1 System.print() } System.print("Displayed %(limit) pages with a total of %(totalCount) entries.") curl.easyCleanup()
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
#NetRexx
NetRexx
/* NetRexx */   options replace format comments java crossref savelog symbols   import java.math.BigInteger   numeric digits 30 -- needed to report the run-time   nanoFactor = 10 ** 9   t1 = System.nanoTime x = BigInteger.valueOf(5) x = x.pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValue()).intValue()) n = Rexx(x.toString) t2 = System.nanoTime td = t2 - t1 say "Run time in seconds:" td / nanoFactor say   check = "62060698786608744707...92256259918212890625" sample = n.left(20)"..."n.right(20)   say "Expected result:" check say " Actual result:" sample say " digits:" n.length say   if check = sample then say "Result confirmed" else say "Result does not satisfy test"   return
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
#Nim
Nim
import bigints   var x = 5.pow 4.pow 3.pow 2 var s = $x   echo s[0..19] echo s[s.high - 19 .. s.high] echo s.len
http://rosettacode.org/wiki/Zeckendorf_number_representation
Zeckendorf number representation
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100. 10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution. Task Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. Also see   OEIS A014417   for the the sequence of required results.   Brown's Criterion - Numberphile Related task   Fibonacci sequence
#Phixmonti
Phixmonti
def Zeckendorf /# n -- #/ 0 var i 0 var c 1 1 2 tolist var pattern true while i 8 int>bit reverse pattern find not if c print ":\t" print print nl dup c == if false else c 1 + var c true endif endif i 1 + var i endwhile drop enddef   20 Zeckendorf
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
#PHP
PHP
  <?php $m = 20;   $F = array(1,1); while ($F[count($F)-1] <= $m) $F[] = $F[count($F)-1] + $F[count($F)-2];   while ($n = $m--) { while ($F[count($F)-1] > $n) array_pop($F); $l = count($F)-1; print "$n: "; while ($n) { if ($n >= $F[$l]) { $n = $n - $F[$l]; print '1'; } else print '0'; --$l; } print str_repeat('0',$l); print "\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.
#Cowgol
Cowgol
include "cowgol.coh";   var doors: uint8[101]; # one extra so we can start at 1 var pass: @indexof doors; var door: @indexof doors;   MemZero(&doors as [uint8], @bytesof doors);   pass := 1; while pass <= 100 loop door := pass; while door <= 100 loop doors[door] := 1-doors[door]; door := door + pass; end loop; pass := pass + 1; end loop;   door := 1; while door <= 100 loop if doors[door] == 1 then print_i8(door); print(" is open\n"); end if; door := door + 1; end loop;
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)
#GUISS
GUISS
Start,Programs,Lotus 123,Type:Bob[downarrow],Kat[downarrow],Sarah[downarrow]
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.
#UNIX_Shell
UNIX Shell
typeset -T Complex_t=( float real=0 float imag=0   function to_s { print -- "${_.real} + ${_.imag} i" }   function dup { nameref other=$1 _=( real=${other.real} imag=${other.imag} ) }   function add { typeset varname for varname; do nameref other=$varname (( _.real += other.real )) (( _.imag += other.imag )) done }   function negate { (( _.real *= -1 )) (( _.imag *= -1 )) }   function conjugate { (( _.imag *= -1 )) }   function multiply { typeset varname for varname; do nameref other=$varname float a=${_.real} b=${_.imag} c=${other.real} d=${other.imag} (( _.real = a*c - b*d )) (( _.imag = b*c + a*d )) done }   function inverse { if (( _.real == 0 && _.imag == 0 )); then print -u2 "division by zero" return 1 fi float denom=$(( _.real*_.real + _.imag*_.imag )) (( _.real = _.real / denom )) (( _.imag = -1 * _.imag / denom )) } )   Complex_t a=(real=1 imag=1) a.to_s # 1 + 1 i   Complex_t b=(real=3.14159 imag=1.2) b.to_s # 3.14159 + 1.2 i   Complex_t c c.add a b c.to_s # 4.14159 + 2.2 i   c.negate c.to_s # -4.14159 + -2.2 i   c.conjugate c.to_s # -4.14159 + 2.2 i   c.dup a c.multiply b c.to_s # 1.94159 + 4.34159 i   Complex_t d=(real=2 imag=1) d.inverse d.to_s # 0.4 + -0.2 i
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
#PowerShell
PowerShell
Write-Host "0 ^ 0 = " ([math]::pow(0,0))
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time,   you may also try something like: x = 0 y = 0 z = x**y say 'z=' z Show the result here. And of course use any symbols or notation that is supported in your computer programming language for exponentiation. See also The Wiki entry: Zero to the power of zero. The Wiki entry: History of differing points of view. The MathWorld™ entry: exponent laws. Also, in the above MathWorld™ entry, see formula (9): x 0 = 1 {\displaystyle x^{0}=1} . The OEIS entry: The special case of zero to the zeroth power
#PureBasic
PureBasic
  If OpenConsole() PrintN("Zero to the zero power is " + Pow(0,0)) PrintN("") PrintN("Press any key to close the console") Repeat: Delay(10) : Until Inkey() <> "" CloseConsole() EndIf  
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
#Pyret
Pyret
num-expt(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
#ERRE
ERRE
  PROGRAM ZEBRA_PUZZLE   DIM DRINK$[4],NATION$[4],COLR$[4],SMOKE$[4],ANIMAL$[4] DIM PERM$[120],X$[4]   PROCEDURE PERMUTATION(X$[]->X$[],OK) LOCAL I%,J% FOR I%=UBOUND(X$,1)-1 TO 0 STEP -1 DO EXIT IF X$[I%]<X$[I%+1] END FOR IF I%<0 THEN OK=FALSE EXIT PROCEDURE END IF J%=UBOUND(X$,1) WHILE X$[J%]<=X$[I%] DO J%=J%-1 END WHILE SWAP(X$[I%],X$[J%]) I%=I%+1 J%=UBOUND(X$,1) WHILE I%<J% DO SWAP(X$[I%],X$[J%]) I%=I%+1 J%=J%-1 END WHILE OK=TRUE END PROCEDURE   BEGIN   ! The names (only used for printing the results)   DATA("Beer","Coffee","Milk","Tea","Water") DATA("Denmark","England","Germany","Norway","Sweden") DATA("Blue","Green","Red","White","Yellow") DATA("Blend","BlueMaster","Dunhill","PallMall","Prince") DATA("Birds","Cats","Dog","Horse","Zebra")   FOR I%=0 TO 4 DO READ(DRINK$[I%]) END FOR FOR I%=0 TO 4 DO READ(NATION$[I%]) END FOR FOR I%=0 TO 4 DO READ(COLR$[I%]) END FOR FOR I%=0 TO 4 DO READ(SMOKE$[I%]) END FOR FOR I%=0 TO 4 DO READ(ANIMAL$[I%]) END FOR   ! Some single-character tags: A$="A" B$="B" c$="C" d$="D" e$="E"   ! ERRE doesn't have enumerations! Beer$=A$ Coffee$=B$ Milk$=c$ TeA$=d$ Water$=e$ Denmark$=A$ England$=B$ Germany$=c$ Norway$=d$ Sweden$=e$ Blue$=A$ Green$=B$ Red$=c$ White$=d$ Yellow$=e$ Blend$=A$ BlueMaster$=B$ Dunhill$=c$ PallMall$=d$ Prince$=e$ Birds$=A$ Cats$=B$ Dog$=c$ Horse$=d$ ZebrA$=e$   PRINT(CHR$(12);)   ! Create the 120 permutations of 5 objects:   X$[0]=A$ X$[1]=B$ X$[2]=C$ X$[3]=D$ X$[4]=E$   REPEAT P%=P%+1 PERM$[P%]=X$[0]+X$[1]+X$[2]+X$[3]+X$[4] PERMUTATION(X$[]->X$[],OK) UNTIL NOT OK   ! Solve: SOLUTIONS%=0 T1=TIMER FOR NATION%=1 TO 120 DO NATION$=PERM$[NATION%] IF LEFT$(NATION$,1)=Norway$ THEN FOR COLR%=1 TO 120 DO COLR$=PERM$[COLR%] IF INSTR(COLR$,Green$+White$)<>0 AND INSTR(NATION$,England$)=INSTR(COLR$,Red$) AND ABS(INSTR(NATION$,Norway$)-INSTR(COLR$,Blue$))=1 THEN FOR DRINK%=1 TO 120 DO DRINK$=PERM$[DRINK%] IF MID$(DRINK$,3,1)=Milk$ AND INSTR(NATION$,Denmark$)=INSTR(DRINK$,TeA$) AND INSTR(DRINK$,Coffee$)=INSTR(COLR$,Green$) THEN FOR SmOKe%=1 TO 120 DO SmOKe$=PERM$[SMOKE%] IF INSTR(NATION$,Germany$)=INSTR(SmOKe$,Prince$) AND INSTR(SmOKe$,BlueMaster$)=INSTR(DRINK$,Beer$) AND ABS(INSTR(SmOKe$,Blend$)-INSTR(DRINK$,Water$))=1 AND INSTR(SmOKe$,Dunhill$)=INSTR(COLR$,Yellow$) THEN FOR ANIMAL%=1 TO 120 DO ANIMAL$=PERM$[ANIMAL%] IF INSTR(NATION$,Sweden$)=INSTR(ANIMAL$,Dog$) AND INSTR(SmOKe$,PallMall$)=INSTR(ANIMAL$,Birds$) AND ABS(INSTR(SmOKe$,Blend$)-INSTR(ANIMAL$,Cats$))=1 AND ABS(INSTR(SmOKe$,Dunhill$)-INSTR(ANIMAL$,Horse$))=1 THEN PRINT("House Drink Nation Colour Smoke Animal") PRINT("---------------------------------------------------------------------------") FOR house%=1 TO 5 DO PRINT(house%;) PRINT(TAB(10);DRINK$[ASC(MID$(DRINK$,house%))-65];) PRINT(TAB(25);NATION$[ASC(MID$(NATION$,house%))-65];) PRINT(TAB(40);COLR$[ASC(MID$(COLR$,house%))-65];) PRINT(TAB(55);SMOKE$[ASC(MID$(SmOKe$,house%))-65];) PRINT(TAB(70);ANIMAL$[ASC(MID$(ANIMAL$,house%))-65]) END FOR SOLUTIONS%=SOLUTIONS%+1 END IF END FOR ! ANIMAL% END IF END FOR ! SmOKe% END IF END FOR ! DRINK% END IF END FOR ! COLR% END IF END FOR ! NATION% PRINT("Number of solutions=";SOLUTIONS%) PRINT("Solved in ";TIMER-T1;" seconds") END PROGRAM
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>
#Go
Go
package main   import ( "encoding/xml" "fmt" "log" "os" )   type Inventory struct { XMLName xml.Name `xml:"inventory"` Title string `xml:"title,attr"` Sections []struct { XMLName xml.Name `xml:"section"` Name string `xml:"name,attr"` Items []struct { XMLName xml.Name `xml:"item"` Name string `xml:"name"` UPC string `xml:"upc,attr"` Stock int `xml:"stock,attr"` Price float64 `xml:"price"` Description string `xml:"description"` } `xml:"item"` } `xml:"section"` }   // To simplify main's error handling func printXML(s string, v interface{}) { fmt.Println(s) b, err := xml.MarshalIndent(v, "", "\t") if err != nil { log.Fatal(err) } fmt.Println(string(b)) fmt.Println() }   func main() { fmt.Println("Reading XML from standard input...")   var inv Inventory dec := xml.NewDecoder(os.Stdin) if err := dec.Decode(&inv); err != nil { log.Fatal(err) }   // At this point, inv is Go struct with all the fields filled // in from the XML data. Well-formed XML input that doesn't // match the specification of the fields in the Go struct are // discarded without error.   // We can reformat the parts we parsed: //printXML("Got:", inv)   // 1. Retrieve first item: item := inv.Sections[0].Items[0] fmt.Println("item variable:", item) printXML("As XML:", item)   // 2. Action on each price: fmt.Println("Prices:") var totalValue float64 for _, s := range inv.Sections { for _, i := range s.Items { fmt.Println(i.Price) totalValue += i.Price * float64(i.Stock) } } fmt.Println("Total inventory value:", totalValue) fmt.Println()   // 3. Slice of all the names: var names []string for _, s := range inv.Sections { for _, i := range s.Items { names = append(names, i.Name) } } fmt.Printf("names: %q\n", names) }
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#Haskell
Haskell
{-# LANGUAGE NoMonomorphismRestriction #-}   import Diagrams.Prelude import Diagrams.Backend.Cairo.CmdLine   yinyang = lw 0 $ perim # lw 0.003 <> torus white black # xform id <> torus black white # xform negate <> clipBy perim base where perim = arc 0 (360 :: Deg) # scale (1/2) torus c c' = circle (1/3) # fc c' <> circle 1 # fc c xform f = translateY (f (1/4)) . scale (1/4) base = rect (1/2) 1 # fc white ||| rect (1/2) 1 # fc black   main = defaultMain $ pad 1.1 $ beside (2,-1) yinyang (yinyang # scale (1/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
#Delphi
Delphi
program Y;   {$APPTYPE CONSOLE}   uses SysUtils;   type YCombinator = class sealed class function Fix<T> (F: TFunc<TFunc<T, T>, TFunc<T, T>>): TFunc<T, T>; static; end;   TRecursiveFuncWrapper<T> = record // workaround required because of QC #101272 (http://qc.embarcadero.com/wc/qcmain.aspx?d=101272) type TRecursiveFunc = reference to function (R: TRecursiveFuncWrapper<T>): TFunc<T, T>; var O: TRecursiveFunc; end;   class function YCombinator.Fix<T> (F: TFunc<TFunc<T, T>, TFunc<T, T>>): TFunc<T, T>; var R: TRecursiveFuncWrapper<T>; begin R.O := function (W: TRecursiveFuncWrapper<T>): TFunc<T, T> begin Result := F (function (I: T): T begin Result := W.O (W) (I); end); end; Result := R.O (R); end;     type IntFunc = TFunc<Integer, Integer>;   function AlmostFac (F: IntFunc): IntFunc; begin Result := function (N: Integer): Integer begin if N <= 1 then Result := 1 else Result := N * F (N - 1); end; end;   function AlmostFib (F: TFunc<Integer, Integer>): TFunc<Integer, Integer>; begin Result := function (N: Integer): Integer begin if N <= 2 then Result := 1 else Result := F (N - 1) + F (N - 2); end; end;   var Fib, Fac: IntFunc; begin Fib := YCombinator.Fix<Integer> (AlmostFib); Fac := YCombinator.Fix<Integer> (AlmostFac); Writeln ('Fib(10) = ', Fib (10)); Writeln ('Fac(10) = ', Fac (10)); end.
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, given   5,   produce this array: 0 1 5 6 14 2 4 7 13 15 3 8 12 16 21 9 11 17 20 22 10 18 19 23 24 Related tasks   Spiral matrix   Identity matrix   Ulam spiral (for primes) See also   Wiktionary entry:   anti-diagonals
#E
E
/** Missing scalar multiplication, but we don't need it. */ def makeVector2(x, y) { return def vector { to x() { return x } to y() { return y } to add(other) { return makeVector2(x + other.x(), y + other.y()) } to clockwise() { return makeVector2(-y, x) } } }   /** Bugs: (1) The printing is specialized. (2) No bounds check on the column. */ def makeFlex2DArray(rows, cols) { def storage := ([null] * (rows * cols)).diverge() return def flex2DArray { to __printOn(out) { for y in 0..!rows { for x in 0..!cols { out.print(<import:java.lang.makeString>.format("%3d", [flex2DArray[y, x]])) } out.println() } } to get(r, c) { return storage[r * cols + c] } to put(r, c, v) { storage[r * cols + c] := v } } }
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].
#Vlang
Vlang
fn gcd(xx int, yy int) int { mut x := xx mut y := yy for y != 0 { x, y = y, x%y } return x }   fn yellowstone(n int) []int { mut m := map[int]bool{} mut a := []int{len: n+1} for i in 1..4 { a[i] = i m[i] = true } mut min := 4 for c := 4; c <= n; c++ { for i := min; ; i++ { if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 { a[c] = i m[i] = true if i == min { min++ } break } } } return a[1..] }   fn main() { mut x := []int{len: 100} for i in 0..100 { x[i] = i + 1 } y := yellowstone(100) println("The first 30 Yellowstone numbers are:") println(y[..30]) }
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].
#Wren
Wren
import "/math" for Int   var yellowstone = Fn.new { |n| var m = {} var a = List.filled(n + 1, 0) for (i in 1..3) { a[i] = i m[i] = true } var min = 4 for (c in 4..n) { var i = min while (true) { if (!m[i] && Int.gcd(a[c-1], i) == 1 && Int.gcd(a[c-2], i) > 1) { a[c] = i m[i] = true if (i == min) min = min + 1 break } i = i + 1 } } return a[1..-1] }   var x = List.filled(30, 0) for (i in 0...30) x[i] = i + 1 var y = yellowstone.call(30) System.print("The first 30 Yellowstone numbers are:") System.print(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
#OCaml
OCaml
open Num open Str open String   let () = let answer = (Int 5) **/ (Int 4) **/ (Int 3) **/ (Int 2) in let answer_string = string_of_num answer in Printf.printf "has %d digits: %s ... %s\n" (length answer_string) (first_chars answer_string 20) (last_chars answer_string 20)
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 {\displaystyle 5^{4^{3^{2}}}} Confirm that the first and last twenty digits of the answer are: 62060698786608744707...92256259918212890625 Find and show the number of decimal digits in the answer. Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead. Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value. Related tasks   Long multiplication   Exponentiation order   exponentiation operator   Exponentiation with infix operators in (or operating on) the base
#Oforth
Oforth
import: mapping   5 4 3 2 pow pow pow >string dup left( 20 ) . dup right( 20 ) . size .
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
#Picat
Picat
go => foreach(Num in 0..20) zeckendorf_cp(Num,X,F), Nums = [F[I] : I in 1..X.length, X[I] = 1], printf("%2d %6s %w\n",Num, rep(X),Nums), end, nl.   zeckendorf_cp(Num, X,F) => F = get_fibs(Num).reverse(), N = F.length, X = new_list(N), X :: 0..1,    % From the task description:  % """  % 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.  % """ foreach(I in 2..N) X[I-1] #= 1 #=> X[I] #= 0 end,   scalar_product(F,X,Num),   solve([ff,split],X).   % % Fibonacci numbers % table fib(0) = 0. fib(1) = 1. fib(N) = fib(N-1) + fib(N-2).   % % Remove leading 0's and stringify it % rep(X) = Str => First = 1, if X.length > 1, X[First] = 0 then while (X[First] == 0) First := First + 1 end end, Str = [X[I].to_string() : I in First..X.length].join('').   % % Return a list of fibs <= N % get_fibs(N) = Fibs => I = 2, Fib = fib(I), Fibs1 = [Fib], while (Fib < N) I := I + 1, Fib := fib(I), Fibs1 := Fibs1 ++ [Fib] end, Fibs = Fibs1.
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
#PicoLisp
PicoLisp
(de fib (N) (let Fibs (1 1) (while (>= N (+ (car Fibs) (cadr Fibs))) (push 'Fibs (+ (car Fibs) (cadr Fibs))) ) (uniq Fibs) ) )   (de zecken1 (N) (make (for I (fib N) (if (> I N) (link 0) (link 1) (dec 'N I) ) ) ) )   (de zecken2 (N) (make (when (=0 N) (link 0)) (for I (fib N) (when (<= I N) (link I) (dec 'N I) ) ) ) )   (for (N 0 (> 21 N) (inc N)) (tab (2 4 6 2 -10) N " -> " (zecken1 N) " " (glue " + " (zecken2 N)) ) )   (bye)
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.
#Crystal
Crystal
doors = Array.new(100, false)   1.upto(100) do |i| i.step(by: i, to: 100) do |j| doors[j - 1] = !doors[j - 1] end end   doors.each_with_index do |open, i| puts "Door #{i + 1} is #{open ? "open" : "closed"}" end
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#GW-BASIC
GW-BASIC
10 DATA 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 20 DIM A(9) ' Array with size 10 (9 is maximum subscript), all elements are set to 0 30 FOR I = 0 TO 9 40 READ A(I) ' Initialize by reading data 50 NEXT I 60 PRINT A(4) ' Get 4th element of array 70 A(4) = 400 ' Set 4th element of array 80 PRINT A(4)  
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.
#Ursala
Ursala
u = 3.785e+00-1.969e+00i v = 9.545e-01-3.305e+00j   #cast %jL   examples =   < complex..add (u,v), complex..mul (u,v), complex..sub (0.,u), complex..div (1.,v)>
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.
#VBA
VBA
  Public Type Complex re As Double im As Double End Type   Function CAdd(a As Complex, b As Complex) As Complex CAdd.re = a.re + b.re CAdd.im = a.im + b.im End Function   Function CSub(a As Complex, b As Complex) As Complex CSub.re = a.re - b.re CSub.im = a.im - b.im End Function   Function CMult(a As Complex, b As Complex) As Complex CMult.re = (a.re * b.re) - (a.im * b.im) CMult.im = (a.re * b.im) + (a.im * b.re) End Function   Function CConj(a As Complex) As Complex CConj.re = a.re CConj.im = -a.im End Function   Function CNeg(a As Complex) As Complex CNeg.re = -a.re CNeg.im = -a.im End Function   Function CInv(a As Complex) As Complex CInv.re = a.re / (a.re * a.re + a.im * a.im) CInv.im = -a.im / (a.re * a.re + a.im * a.im) End Function   Function CDiv(a As Complex, b As Complex) As Complex CDiv = CMult(a, CInv(b)) End Function   Function CAbs(a As Complex) As Double CAbs = Math.Sqr(a.re * a.re + a.im * a.im) End Function   Function CSqr(a As Complex) As Complex CSqr.re = Math.Sqr((a.re + Math.Sqr(a.re * a.re + a.im * a.im)) / 2) CSqr.im = Math.Sgn(a.im) * Math.Sqr((-a.re + Math.Sqr(a.re * a.re + a.im * a.im)) / 2) End Function   Function CPrint(a As Complex) As String If a.im > 0 Then Sep = "+" Else Sep = "" End If CPrint = a.re & Sep & a.im & "i" End Function   Sub ShowComplexCalc() Dim a As Complex Dim b As Complex Dim c As Complex   a.re = 1.5 a.im = 3 b.re = 1.5 b.im = 1.5   Debug.Print "a = " & CPrint(a) Debug.Print "b = " & CPrint(b)   c = CAdd(a, b) Debug.Print "a + b = " & CPrint(c) c = CSub(a, b) Debug.Print "a - b = " & CPrint(c) c = CMult(a, b) Debug.Print "a * b = " & CPrint(c) c = CConj(a) Debug.Print "Conj(a) = " & CPrint(c) c = CNeg(a) Debug.Print "-a = " & CPrint(c) c = CInv(a) Debug.Print "Inv(a) = " & CPrint(c) c = CDiv(a, b) Debug.Print "a / b = " & CPrint(c) Debug.Print "Abs(a) = " & CAbs(a) c = CSqr(a) Debug.Print "Sqrt(a) = " & CPrint(c) End Sub  
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time,   you may also try something like: x = 0 y = 0 z = x**y say 'z=' z Show the result here. And of course use any symbols or notation that is supported in your computer programming language for exponentiation. See also The Wiki entry: Zero to the power of zero. The Wiki entry: History of differing points of view. The MathWorld™ entry: exponent laws. Also, in the above MathWorld™ entry, see formula (9): x 0 = 1 {\displaystyle x^{0}=1} . The OEIS entry: The special case of zero to the zeroth power
#Python
Python
from decimal import Decimal from fractions import Fraction from itertools import product   zeroes = [0, 0.0, 0j, Decimal(0), Fraction(0, 1), -0.0, -0.0j, Decimal(-0.0)] for i, j in product(zeroes, repeat=2): try: ans = i**j except: ans = '<Exception raised>' print(f'{i!r:>15} ** {j!r:<15} = {ans!r}')
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
#QB64
QB64
Print 0 ^ 0
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives in the red house.   The Swede has a dog.   The Dane drinks tea.   The green house is immediately to the left of the white house.   They drink coffee in the green house.   The man who smokes Pall Mall has birds.   In the yellow house they smoke Dunhill.   In the middle house they drink milk.   The Norwegian lives in the first house.   The man who smokes Blend lives in the house next to the house with cats.   In a house next to the house where they have a horse, they smoke Dunhill.   The man who smokes Blue Master drinks beer.   The German smokes Prince.   The Norwegian lives next to the blue house.   They drink water in a house next to the house where they smoke Blend. The question is, who owns the zebra? Additionally, list the solution for all the houses. Optionally, show the solution is unique. Related tasks   Dinesman's multiple-dwelling problem   Twelve statements
#F.23
F#
  (*Here I solve the Zebra puzzle using Plain Changes, definitely a challenge to some campanoligist to solve it using Grandsire Doubles. Nigel Galloway: January 27th., 2017 *) type N = |English=0 |Swedish=1|Danish=2 |German=3|Norwegian=4 type I = |Tea=0 |Coffee=1 |Milk=2 |Beer=3 |Water=4 type G = |Dog=0 |Birds=1 |Cats=2 |Horse=3 |Zebra=4 type E = |Red=0 |Green=1 |White=2 |Blue=3 |Yellow=4 type L = |PallMall=0|Dunhill=1|BlueMaster=2|Prince=3|Blend=4 type NIGELz={Nz:N[];Iz:I[];Gz:G[];Ez:E[];Lz:L[]} let fn (i:'n[]) g (e:'g[]) l = //coincident? let rec _fn = function |5 -> false |ig when (i.[ig]=g && e.[ig]=l) -> true |ig -> _fn (ig+1) _fn 0 let fi (i:'n[]) g (e:'g[]) l = //leftof? let rec _fn = function |4 -> false |ig when (i.[ig]=g && e.[ig+1]=l) -> true |ig -> _fn (ig+1) _fn 0 let fg (i:'n[]) g (e:'g[]) l = (fi i g e l || fi e l i g) //adjacent? let n = Ring.PlainChanges [|for n in System.Enum.GetValues(typeof<N>)->n:?>N|]|>Seq.filter(fun n->n.[0]=N.Norwegian) //#10 let i = Ring.PlainChanges [|for n in System.Enum.GetValues(typeof<I>)->n:?>I|]|>Seq.filter(fun n->n.[2]=I.Milk) //# 9 let g = Ring.PlainChanges [|for n in System.Enum.GetValues(typeof<G>)->n:?>G|] let e = Ring.PlainChanges [|for n in System.Enum.GetValues(typeof<E>)->n:?>E|]|>Seq.filter(fun n->fi n E.Green n E.White) //# 5 let l = Ring.PlainChanges [|for n in System.Enum.GetValues(typeof<L>)->n:?>L|] match n|>Seq.map(fun n->{Nz=n;Iz=[||];Gz=[||];Ez=[||];Lz=[||]}) |>Seq.collect(fun n->i|>Seq.map(fun i->{n with Iz=i}))|>Seq.filter(fun n-> fn n.Nz N.Danish n.Iz I.Tea) //# 4 |>Seq.collect(fun n->g|>Seq.map(fun i->{n with Gz=i}))|>Seq.filter(fun n-> fn n.Nz N.Swedish n.Gz G.Dog) //# 3 |>Seq.collect(fun n->e|>Seq.map(fun i->{n with Ez=i}))|>Seq.filter(fun n-> fn n.Nz N.English n.Ez E.Red && //# 2 fn n.Ez E.Green n.Iz I.Coffee&& //# 6 fg n.Nz N.Norwegian n.Ez E.Blue) //#15 |>Seq.collect(fun n->l|>Seq.map(fun i->{n with Lz=i}))|>Seq.tryFind(fun n->fn n.Lz L.PallMall n.Gz G.Birds && //# 7 fg n.Lz L.Blend n.Gz G.Cats && //#11 fn n.Lz L.Prince n.Nz N.German&& //#14 fg n.Lz L.Blend n.Iz I.Water && //#16 fg n.Lz L.Dunhill n.Gz G.Horse && //#12 fn n.Lz L.Dunhill n.Ez E.Yellow&& //# 8 fn n.Iz I.Beer n.Lz L.BlueMaster) with //#13 |Some(nn) -> nn.Gz |> Array.iteri(fun n g -> if (g = G.Zebra) then printfn "\nThe man who owns a zebra is %A\n" nn.Nz.[n]); printfn "%A" nn |None -> printfn "No solution found"  
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="health"> <item upc="123456789" stock="12"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item upc="445322344" stock="18"> <name>Levitation Salve</name> <price>23.99</price> <description>Levitate yourself for up to 3 hours per application</description> </item> </section> <section name="food"> <item upc="485672034" stock="653"> <name>Blork and Freen Instameal</name> <price>4.95</price> <description>A tasty meal in a tablet; just add water</description> </item> <item upc="132957764" stock="44"> <name>Grob winglets</name> <price>3.56</price> <description>Tender winglets of Grob. Just add water</description> </item> </section> </inventory>
#Groovy
Groovy
def inventory = new XmlSlurper().parseText("<inventory...") //optionally parseText(new File("inv.xml").text) def firstItem = inventory.section.item[0] //1. first item inventory.section.item.price.each { println it } //2. print each price def allNamesArray = inventory.section.item.name.collect {it} //3. collect item names into 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>
#Haskell
Haskell
import Data.List import Control.Arrow import Control.Monad   takeWhileIncl :: (a -> Bool) -> [a] -> [a] takeWhileIncl _ [] = [] takeWhileIncl p (x:xs) | p x = x : takeWhileIncl p xs | otherwise = [x]   getmultiLineItem n = takeWhileIncl(not.isInfixOf ("</" ++ n)). dropWhile(not.isInfixOf ('<': n)) getsingleLineItems n = map (takeWhile(/='<'). drop 1. dropWhile(/='>')). filter (isInfixOf ('<': n))   main = do xml <- readFile "./Rosetta/xmlpath.xml" let xmlText = lines xml   putStrLn "\n== First item ==\n" mapM_ putStrLn $ head $ unfoldr (Just. liftM2 (id &&&) (\\) (getmultiLineItem "item")) xmlText   putStrLn "\n== Prices ==\n" mapM_ putStrLn $ getsingleLineItems "price" xmlText   putStrLn "\n== Names ==\n" print $ getsingleLineItems "name" xmlText
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.
#Icon_and_Unicon
Icon and Unicon
link graphics   procedure main() YinYang(100) YinYang(40,"blue","yellow","white") WDone() # quit on Q/q end   procedure YinYang(R,lhs,rhs,bg) # draw YinYang with radius of R pixels and ... /lhs := "white" # left hand side /rhs := "black" # right hand side /bg := "grey" # background   wsize := 2*(C := R + (margin := R/5))   W := WOpen("size="||wsize||","||wsize,"bg="||bg) | stop("Unable to open Window") WAttrib(W,"fg="||lhs) & FillCircle(W,C,C,R,+dtor(90),dtor(180)) # main halves WAttrib(W,"fg="||rhs) & FillCircle(W,C,C,R,-dtor(90),dtor(180)) WAttrib(W,"fg="||lhs) & FillCircle(W,C,C+R/2,R/2,-dtor(90),dtor(180)) # sub halves WAttrib(W,"fg="||rhs) & FillCircle(W,C,C-R/2,R/2,dtor(90),dtor(180)) WAttrib(W,"fg="||lhs) & FillCircle(W,C,C-R/2,R/8) # dots WAttrib(W,"fg="||rhs) & FillCircle(W,C,C+R/2,R/8) end
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. Task Define the stateless   Y combinator   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions. Cf Jim Weirich: Adventures in Functional Programming
#Dhall
Dhall
let const  : ∀(b : Type) → ∀(a : Type) → a → b → a = λ(r : Type) → λ(a : Type) → λ(x : a) → λ(y : r) → x   let fac  : ∀(n : Natural) → Natural = λ(n : Natural) → let factorial = λ(f : Natural → Natural → Natural) → λ(n : Natural) → λ(i : Natural) → if Natural/isZero i then n else f (i * n) (Natural/subtract 1 i)   in Natural/fold n (Natural → Natural → Natural) factorial (const Natural Natural) 1 n   let fib  : ∀(n : Natural) → Natural = λ(n : Natural) → let fibFunc = Natural → Natural → Natural → Natural   let fibonacci = λ(f : fibFunc) → λ(a : Natural) → λ(b : Natural) → λ(i : Natural) → if Natural/isZero i then a else f b (a + b) (Natural/subtract 1 i)   in Natural/fold n fibFunc fibonacci (λ(a : Natural) → λ(_ : Natural) → λ(_ : Natural) → a) 0 1 n   in [fac 50, fib 50]
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
#Elena
Elena
import extensions;   extension op : IntNumber { zigzagMatrix() { auto result := IntMatrix.allocate(self, self);   int i := 0; int j := 0; int d := -1; int start := 0; int end := self*self - 1;   while (start < end) { result.setAt(i, j, start); start += 1; result.setAt(self - i - 1, self - j - 1, end); end -= 1;   i := i + d; j := j - d; if (i < 0) { i:=i+1; d := d.Negative } else if (j < 0) { j := j + 1; d := d.Negative } };   if (start == end) { result.setAt(i, j, start) };   ^ result } }   public program() { console.printLine(5.zigzagMatrix()).readChar() }
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
#Elixir
Elixir
defmodule RC do require Integer def zigzag(n) do fmt = "~#{to_char_list(n*n-1) |> length}w " (for x <- 1..n, y <- 1..n, do: {x,y}) |> Enum.sort_by(fn{x,y}->{x+y, if(Integer.is_even(x+y), do: y, else: x)} end) |> Enum.with_index |> Enum.sort |> Enum.each(fn {{_x,y},i} ->  :io.format fmt, [i] if y==n, do: IO.puts "" end) end end   RC.zigzag(5)