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/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's stat...
#C.23
C#
using System;   static class YCombinator<T, TResult> { // RecursiveFunc is not needed to call Fix() and so can be private. private delegate Func<T, TResult> RecursiveFunc(RecursiveFunc r);   public static Func<Func<Func<T, TResult>, Func<T, TResult>>, Func<T, TResult>> Fix { get; } = f => ((Recursiv...
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, gi...
#Beads
Beads
beads 1 program 'Zig-zag Matrix'   calc main_init var test : array^2 of num = create_array(5) printMatrix(test)   calc create_array( dimension:num ):array^2 of num var result : array^2 of num lastValue = dimension^2 - 1 loopFrom loopTo row col currDiag = 0 currNum = 0 loop if (currDiag < dimensi...
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, gi...
#Befunge
Befunge
>> 5 >>00p0010p:1:>20p030pv >0g-:0`*:*-:00g:*1-55+/>\55+/:v v:,*84< v:++!\**2p01:+1g01:g02$$_>>#^4#00#+p#1:#+1#g0#0g#3<^/+ 55\_$:>55+/\| >55+,20g!00g10g`>#^_$$$@^!`g03g00!g04++**2p03:+1g03!\*+1*2g01:g04.$<
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 n...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
state = {1, 2, 3}; MakeNext[state_List] := Module[{i = First[state], done = False, out}, While[! done, If[FreeQ[state, i], If[GCD[Last[state], i] == 1, If[GCD[state[[-2]], i] > 1, out = Append[state, i]; done = True; ] ] ]; i++; ]; out ] Nest[MakeNext, state, 30 - 3] L...
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 n...
#Nim
Nim
import math   proc yellowstone(n: int): seq[int] = assert n >= 3 result = @[1, 2, 3] var present = {1, 2, 3} var start = 4 while result.len < n: var candidate = start while true: if candidate notin present and gcd(candidate, result[^1]) == 1 and gcd(candidate, result[^2]) != 1: result.ad...
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 n...
#Perl
Perl
use strict; use warnings; use feature 'say';   use List::Util qw(first); use GD::Graph::bars;   use constant Inf => 1e5;   sub gcd { my ($u, $v) = @_; while ($v) { ($u, $v) = ($v, $u % $v); } return abs($u); }   sub yellowstone { my($terms) = @_; my @s = (1, 2, 3); my @used = (1) x 4; my $m...
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.
#Oz
Oz
declare [HTTPClient] = {Module.link ['x-ozlib://mesaros/net/HTTPClient.ozf']} [StringX] = {Module.link ['x-oz://system/String.ozf']} [Regex] = {Module.link ['x-oz://contrib/regex']}   %% Displays page 1 and 3 of the search results. %% The user can request and display more with context menu->Actions->Make Need...
http://rosettacode.org/wiki/Zumkeller_numbers
Zumkeller numbers
Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that ...
#Vlang
Vlang
fn get_divisors(n int) []int { mut divs := [1, n] for i := 2; i*i <= n; i++ { if n%i == 0 { j := n / i divs << i if i != j { divs << j } } } return divs }   fn sum(divs []int) int { mut sum := 0 for div in divs { ...
http://rosettacode.org/wiki/Zumkeller_numbers
Zumkeller numbers
Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that ...
#Wren
Wren
import "/math" for Int, Nums import "/fmt" for Fmt import "io" for Stdout   var isPartSum // recursive isPartSum = Fn.new { |divs, sum| if (sum == 0) return true if (divs.count == 0) return false var last = divs[-1] divs = divs[0...-1] if (last > sum) return isPartSum.call(divs, sum) return isPa...
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 ...
#J
J
Pow5432=: 5^4^3^2x Pow5432=: ^/ 5 4 3 2x NB. alternate J solution # ": Pow5432 NB. number of digits 183231 20 ({. , '...' , -@[ {. ]) ": Pow5432 NB. 20 first & 20 last digits 62060698786608744707...92256259918212890625
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
#Java
Java
import java.math.BigInteger;   class IntegerPower { public static void main(String[] args) { BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact()); String str = power.toString(); int len = str.length(); S...
http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm
Zhang-Suen thinning algorithm
This is an algorithm used to thin a black and white i.e. one bit per pixel images. For example, with an input image of: ################# ############# ################## ################ #################...
#VBA
VBA
Public n As Variant Private Sub init() n = [{-1,0;-1,1;0,1;1,1;1,0;1,-1;0,-1;-1,-1;-1,0}] End Sub   Private Function AB(text As Variant, y As Integer, x As Integer, step As Integer) As Variant Dim wtb As Integer Dim bn As Integer Dim prev As String: prev = "#" Dim next_ As String Dim p2468 As St...
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, ...
#Liberty_BASIC
Liberty BASIC
samples = 20 call zecklist samples   print "Decimal","Zeckendorf" for n = 0 to samples print n, zecklist$(n) next n   Sub zecklist inDEC dim zecklist$(inDEC) do bin$ = dec2bin$(count) if instr(bin$,"11") = 0 then zecklist$(found) = bin$ found = found + 1 end if count = count+1 loop u...
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...
#Coco
Coco
doors = [false] * 100   for pass til doors.length for i from pass til doors.length by pass + 1  ! = doors[i]   for i til doors.length console.log 'Door %d is %s.', i + 1, if doors[i] then 'open' else 'closed'
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,...
#Futhark
Futhark
  [1, 2, 3]  
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  Typica...
#Scheme
Scheme
(define a 1+i) (define b 3.14159+1.25i)   (define c (+ a b)) (define c (* a b)) (define c (/ 1 a)) (define c (- 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  Typica...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i"; include "complex.s7i";   const proc: main is func local var complex: a is complex(1.0, 1.0); var complex: b is complex(3.14159, 1.2); begin writeln("a=" <& a digits 5); writeln("b=" <& b digits 5); # addition writeln("a+b=" <& a + b digits 5...
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Fur...
#TI-89_BASIC
TI-89 BASIC
import "/math" for Int import "/rat" for Rat   System.print("The following numbers (less than 2^19) are perfect:") for (i in 2...(1<<19)) { var sum = Rat.new(1, i) for (j in Int.properDivisors(i)[1..-1]) sum = sum + Rat.new(1, j) if (sum == Rat.one) System.print("  %(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, ...
#NetRexx
NetRexx
x=0 Say '0**0='||x**x
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, ...
#NewLISP
NewLISP
(pow 0 0)
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives ...
#C.2B.2B
C++
  #include <stdio.h> #include <string.h>   #define defenum(name, val0, val1, val2, val3, val4) \ enum name { val0, val1, val2, val3, val4 }; \ const char *name ## _str[] = { # val0, # val1, # val2, # val3, # val4 }   defenum( Attrib, Color, Man, Drink, Animal, Smoke ); defenum( Colors, Red, Green, White, ...
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="heal...
#Cach.C3.A9_ObjectScript
Caché ObjectScript
Class XML.Inventory [ Abstract ] {   XData XMLData { <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" sto...
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="heal...
#CoffeeScript
CoffeeScript
  # Retrieve the first "item" element doc.evaluate('//item', doc, {}, 7, {}).snapshotItem 0   # Perform an action on each "price" element (print it out) prices = doc.evaluate "//price", doc, {}, 7, {} for i in [0...prices.snapshotLength] by 1 console.log prices.snapshotItem(i).textContent   # Get an array of all ...
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.
#Befunge
Befunge
55+:#. 00p:2*10p:2/20p6/30p01v @#!`g01:+1g07,+55$<v0-g010p07_ 0g-20g+:*+30g:*`v ^_:2/:*:70g0 3+*:-g02-g00g07:_ 0v v!`*:g0 g-20g+:*+20g:*`>v> ^ v1_:70g00 2+*:-g02-g00g07:_ 1v v!`*:g0 g-:*+00g:*`#v_$:0`!0\v0_:70g00 0#+g#1,#$< > 2 #^>#g>#04#1+#:
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.
#C
C
#include <stdio.h>   void draw_yinyang(int trans, double scale) { printf("<use xlink:href='#y' transform='translate(%d,%d) scale(%g)'/>", trans, trans, scale); }   int main() { printf( "<?xml version='1.0' encoding='UTF-8' standalone='no'?>\n" "<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN'\n" " 'http://www.w3.or...
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's stat...
#C.2B.2B_2
C++
g++ --std=c++11 ycomb.cc
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, gi...
#BQN
BQN
Flip ← {m←2|+⌜˜↕≠𝕩 ⋄ (⍉𝕩׬m)+𝕩×m} Zz ← {Flip ⍋∘⍋⌾⥊+⌜˜↕𝕩}
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, gi...
#C
C
#include <stdio.h> #include <stdlib.h>   int main(int c, char **v) { int i, j, m, n, *s;   /* default size: 5 */ if (c < 2 || ((m = atoi(v[1]))) <= 0) m = 5;   /* alloc array*/ s = malloc(sizeof(int) * m * m);   for (i = n = 0; i < m * 2; i++) for (j = (i < m) ? 0 : i-m+1; j <= i && j < m; j++) s[(i&1)? j*(m...
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 n...
#Phix
Phix
-- -- demo\rosetta\Yellowstone_sequence.exw -- with javascript_semantics requires("1.0.2") function yellowstone(integer N) sequence a = {1, 2, 3}, b = repeat(true,3) integer i = 4 while length(a) < N do if (i>length(b) or b[i]=false) and gcd(i,a[$])=1 and gcd(i,a[$-1])>...
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.
#Perl
Perl
package YahooSearch;   use Encode; use HTTP::Cookies; use WWW::Mechanize;   # --- Internals -------------------------------------------------   sub apply (&$) {my $f = shift; local $_ = shift; $f->(); return $_;}   # We construct a cookie to get 100 results per page and prevent # "enhanced results". my $search_prefs...
http://rosettacode.org/wiki/Zumkeller_numbers
Zumkeller numbers
Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that ...
#zkl
zkl
fcn properDivs(n){ // does not include n // if(n==1) return(T); // we con't care about this case ( pd:=[1..(n).toFloat().sqrt()].filter('wrap(x){ n%x==0 }) ) .pump(pd,'wrap(pd){ if(pd!=1 and (y:=n/pd)!=pd ) y else Void.Skip }) } fcn canSum(goal,divs){ if(goal==0 or divs[0]==goal) return(True); if(divs.len...
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
#JavaScript
JavaScript
>>> const y = (5n**4n**3n**2n).toString(); >>> console.log(`5**4**3**2 = ${y.slice(0,20)}...${y.slice(-20)} and has ${y.length} digits`); 5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
#jq
jq
  def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);   5|power(4|power(3|power(2))) | tostring | .[:20], .[-20:], length  
http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm
Zhang-Suen thinning algorithm
This is an algorithm used to thin a black and white i.e. one bit per pixel images. For example, with an input image of: ################# ############# ################## ################ #################...
#Wren
Wren
class Point { construct new(x, y) { _x = x _y = y } x { _x } y { _y } }   var image = [ " ", " ################# ############# ", " ################## ################ ", ...
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, ...
#Lingo
Lingo
-- Return the distinct Fibonacci numbers not greater than 'n' on fibsUpTo (n) fibList = [] last = 1 current = 1 repeat while current <= n fibList.add(current) nxt = last + current last = current current = nxt end repeat return fibList end   -- Return the Zecke...
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, ...
#Little_Man_Computer
Little Man Computer
  // Little Man Computer, for Rosetta Code. // Writes Zeckendorf representations of numbers 0..20. // Works with Peter Higginson's LMC simulator, except that // user must intervene manually to capture all the output. LDA c0 // initialize to N = 0 loop STA N OUT // write 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...
#CoffeeScript
CoffeeScript
doors = []   for pass in [1..100] for i in [pass..100] by pass doors[i] = !doors[i]   console.log "Doors #{index for index, open of doors when open} are open"   # matrix output console.log doors.map (open) -> +open  
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#Gambas
Gambas
  DIM mynumbers AS INTEGER[] myfruits AS STRING[]   mynumbers[0] = 1.5 mynumbers[1] = 2.3   myfruits[0] = "apple" myfruits[1] = "banana"  
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  Typica...
#Sidef
Sidef
var a = 1:1 # Complex(1, 1) var b = 3.14159:1.25 # Complex(3.14159, 1.25)   [ a + b, # addition a * b, # multiplication -a, # negation a.inv, # multiplicative inverse a.conj, # complex conjuga...
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Fur...
#Wren
Wren
import "/math" for Int import "/rat" for Rat   System.print("The following numbers (less than 2^19) are perfect:") for (i in 2...(1<<19)) { var sum = Rat.new(1, i) for (j in Int.properDivisors(i)[1..-1]) sum = sum + Rat.new(1, j) if (sum == Rat.one) System.print("  %(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, ...
#Nial
Nial
0 0.0 o outer power 0 0.0 o +--+--+--+ | 1|1.| 1| +--+--+--+ |1.|1.|1.| +--+--+--+ | 1|1.| 1| +--+--+--+
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time, ...
#Nim
Nim
import math   echo pow(0.0, 0.0) # Floating point exponentiation. echo 0 ^ 0 # Integer exponentiation.
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 ...
#Clojure
Clojure
(ns zebra.core (:refer-clojure :exclude [==]) (:use [clojure.core.logic] [clojure.tools.macro :as macro]))   (defne lefto [x y l] ([_ _ [x y . ?r]]) ([_ _ [_ . ?r]] (lefto x y ?r)))   (defn nexto [x y l] (conde ((lefto x y l)) ((lefto y x l))))   (defn zebrao [hs] (macro/symbol-mac...
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="heal...
#ColdFusion
ColdFusion
<cfsavecontent variable="xmlString"> <inventory ... </inventory> </cfsavecontent> <cfset xml = xmlParse(xmlString)> <!--- First Task ---> <cfset itemSearch = xmlSearch(xml, "//item")> <!--- item = the first Item (xml element object) ---> <cfset item = itemSearch[1]> <!--- Second Task ---> <cfset priceSearch = xmlSearch...
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.
#C.2B.2B
C++
#include <iostream>   bool circle(int x, int y, int c, int r) { return (r * r) >= ((x = x / 2) * x) + ((y = y - c) * y); }   char pixel(int x, int y, int r) { if (circle(x, y, -r / 2, r / 6)) { return '#'; } if (circle(x, y, r / 2, r / 6)) { return '.'; } if (circle(x, y, -r / 2,...
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's stat...
#Ceylon_2
Ceylon
Result(*Args) y1<Result,Args>( Result(*Args)(Result(*Args)) f) given Args satisfies Anything[] {   class RecursiveFunction(o) { shared Result(*Args)(RecursiveFunction) o; }   value r = RecursiveFunction((RecursiveFunction w) => f(flatten((Args args) => w.o(w)(*args))));   ...
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, gi...
#C.23
C#
public static int[,] ZigZag(int n) { int[,] result = new int[n, n]; int i = 0, j = 0; int d = -1; // -1 for top-right move, +1 for bottom-left move int start = 0, end = n * n - 1; do { result[i, j] = start++; result[n - i - 1, n - j - 1] = end--;   i += d; j -= d; ...
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 n...
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   def gcd /# u v -- n #/ abs int swap abs int swap   dup while over over mod rot drop dup endwhile drop enddef   def test enddef   def yellow var n ( 1 2 3 ) var a newd ( 1 true ) setd ( 2 true ) setd ( 3 true ) setd var b 4 var i test while b i getd "Un...
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 n...
#PicoLisp
PicoLisp
(load "@lib/frac.l") (de yellow (N) (let (L (list 3 2 1) I 4 C 3 D) (while (> N C) (when (and (not (idx 'D I)) (=1 (gcd I (get L 1))) (> (gcd I (get L 2)) 1) ) (push 'L I) (idx 'D I T) (setq I 4) ...
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.
#Phix
Phix
constant glyphs = {{"\xC2\xB7 ","*"}, -- bullet point {"&#39;",`'`}, -- single quote {"&quot;",`"`}, -- double quote {"&amp;","&"}, -- ampersand {"\xE2\x94\xAC\xC2\xAB","[R]"}, -- registered ...
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.
#PicoLisp
PicoLisp
(load "@lib/http.l")   (de yahoo (Query Page) (default Page 1) (client "search.yahoo.com" 80 (pack "search?p=" (ht:Fmt Query) "&b=" (inc (* 10 (dec Page))) ) (make (while (from "<a class=\"yschttl spt\" href=\"") (link (make (link...
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 ...
#Julia
Julia
julia> @elapsed bigstr = string(BigInt(5)^4^3^2) 0.017507363   julia> length(bigstr) 183231   julia> bigstr[1:20] "62060698786608744707"   julia> bigstr[end-20:end] "892256259918212890625"
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 ...
#Klong
Klong
n::$5^4^3^2 .p("5^4^3^2 = ",(20#n),"...",((-20)#n)," and has ",($#n)," 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 ...
#Kotlin
Kotlin
import java.math.BigInteger   fun main(args: Array<String>) { val x = BigInteger.valueOf(5).pow(Math.pow(4.0, 3.0 * 3.0).toInt()) val y = x.toString() val len = y.length println("5^4^3^2 = ${y.substring(0, 20)}...${y.substring(len - 20)} and has $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, ...
#Logo
Logo
; return the (N+1)th Fibonacci number (1,2,3,5,8,13,...) to fib m local "n make "n sum :m 1 if [lessequal? :n 0] [output difference fib sum :n 2 fib sum :n 1] global "_fib if [not name? "_fib] [ make "_fib [1 1] ] local "length make "length count :_fib while [greater? :n :length] [ make "_fib ...
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, ...
#Lua
Lua
-- Return the distinct Fibonacci numbers not greater than 'n' function fibsUpTo (n) local fibList, last, current, nxt = {}, 1, 1 while current <= n do table.insert(fibList, current) nxt = last + current last = current current = nxt end return fibList end   -- Return t...
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...
#ColdFusion
ColdFusion
  doorCount = 1; doorList = ""; // create all doors and set all doors to open while (doorCount LTE 100) { doorList = ListAppend(doorList,"1"); doorCount = doorCount + 1; } loopCount = 2; doorListLen = ListLen(doorList); while (loopCount LTE 100) { loopDoorListCount = 1; while (loopDoorListCount LTE 100)...
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#GAP
GAP
# Arrays are better called lists in GAP. Lists may have elements of mixed types, e$ v := [ 10, 7, "bob", true, [ "inner", 5 ] ]; # [ 10, 7, "bob", true, [ "inner", 5 ] ]   # List index runs from 1 to Size(v) v[1]; # 10   v[0]; # error   v[5]; # [ "inner", 5 ]   v[6]; # error   # One can assign a value to an undefined e...
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  Typica...
#Slate
Slate
[| a b | a: 1 + 1 i. b: Pi + 1.2 i. print: a + b. print: a * b. print: a / b. print: a reciprocal. print: a conjugated. print: a abs. print: a negated. ].
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  Typica...
#Smalltalk
Smalltalk
PackageLoader fileInPackage: 'Complex'. |a b| a := 1 + 1 i. b := 3.14159 + 1.2 i. (a + b) displayNl. (a * b) displayNl. (a / b) displayNl. a reciprocal displayNl. a conjugate displayNl. a abs displayNl. a real displayNl. a imaginary displayNl. a negated displayNl.
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Fur...
#zkl
zkl
class Rational{ // Weenie Rational class, can handle BigInts fcn init(_a,_b){ var a=_a, b=_b; normalize(); } fcn toString{ if(b==1) a.toString() else "%d//%d".fmt(a,b) } var [proxy] isZero=fcn{ a==0 }; fcn normalize{ // divide a and b by gcd g:= a.gcd(b); a/=g; b/=g; ...
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, ...
#OCaml
OCaml
# 0.0 ** 0.0;; - : float = 1. # Complex.pow Complex.zero Complex.zero;; - : Complex.t = {Complex.re = nan; Complex.im = nan} # #load "nums.cma";; # open Num;; # Int 0 **/ Int 0;; - : Num.num = Int 1
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time, ...
#Oforth
Oforth
0 0 pow println
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, ...
#Ol
Ol
  (print "0^0: " (expt 0 0)) (print "0.0^0: " (expt (inexact 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 ...
#Crystal
Crystal
CONTENT = {House: [""], Nationality: %i[English Swedish Danish Norwegian German], Colour: %i[Red Green White Blue Yellow], Pet: %i[Dog Birds Cats Horse Zebra], Drink: %i[Tea Coffee Milk Beer Water], Smoke: %i[PallMall Dunhill BlueMast...
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="heal...
#Common_Lisp
Common Lisp
(dolist (system '(:xpath :cxml-stp :cxml)) (asdf:oos 'asdf:load-op system))   (defparameter *doc* (cxml:parse-file "xml" (stp:make-builder)))   (xpath:first-node (xpath:evaluate "/inventory/section[1]/item[1]" *doc*))   (xpath:do-node-set (node (xpath:evaluate "/inventory/section/item/price/text()" *doc*)) (format ...
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="heal...
#D
D
import kxml.xml; char[]xmlinput = "<inventory title=\"OmniCorp Store #45x10^3\"> <section name=\"health\"> <item upc=\"123456789\" stock=\"12\"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item upc=\"445322344\" stock=\"18\...
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#C.23
C#
  public partial class Form1 : Form { public Form1() { InitializeComponent(); Paint += Form1_Paint; }   private void Form1_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; g.SmoothingMode = System.Drawing.Dr...
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's stat...
#Chapel
Chapel
proc fixz(f) { record InnerFunc { const xi; proc this(a) { return xi(xi)(a); } } record XFunc { const fi; proc this(x) { return fi(new InnerFunc(x)); } } const g = new XFunc(f); return g(g); }   record Facz { record FacFunc { const fi; proc this(n: int): int { return if n <= ...
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, gi...
#C.2B.2B
C++
#include <vector> #include <memory> // for auto_ptr #include <cmath> // for the log10 and floor functions #include <iostream> #include <iomanip> // for the setw function   using namespace std;   typedef vector< int > IntRow; typedef vector< IntRow > IntTable;   auto_ptr< IntTable > getZigZagArray( int dimension ) { au...
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 n...
#PureBasic
PureBasic
Procedure.i gcd(x.i,y.i) While y<>0 : t=x : x=y : y=t%y : Wend : ProcedureReturn x EndProcedure   If OpenConsole() Dim Y.i(100) For i=1 To 100 If i<=3 : Y(i)=i : Continue : EndIf : k=3 Repeat RepLoop: k+1 For j=1 To i-1 : If Y(j)=k : Goto RepLoop : EndIf : Next ...
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 n...
#Python
Python
'''Yellowstone permutation OEIS A098550'''   from itertools import chain, count, islice from operator import itemgetter from math import gcd   from matplotlib import pyplot     # yellowstone :: [Int] def yellowstone(): '''A non-finite stream of terms from the Yellowstone permutation. OEIS A098550. ...
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.
#Python
Python
import urllib import re   def fix(x): p = re.compile(r'<[^<]*?>') return p.sub('', x).replace('&amp;', '&')   class YahooSearch: def __init__(self, query, page=1): self.query = query self.page = page self.url = "http://search.yahoo.com/search?p=%s&b=%s" %(self.query, ((self.pa...
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 ...
#Lasso
Lasso
define integer->pow(factor::integer) => { #factor <= 0  ? return 0   local(retVal) = 1   loop(#factor) => { #retVal *= self }   return #retVal }   local(bigint) = string(5->pow(4->pow(3->pow(2)))) #bigint->sub(1,20) + ` ... ` + #bigint->sub(#bigint->size - 19) "\n" `Number of digits: ` + #bigint-...
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 ...
#Liberty_BASIC
Liberty BASIC
a$ = str$( 5^(4^(3^2))) print len( a$) print left$( a$, 20); "......"; right$( a$, 20)
http://rosettacode.org/wiki/Zeckendorf_number_representation
Zeckendorf number representation
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
zeckendorf[0] = 0; zeckendorf[n_Integer] := 10^(# - 1) + zeckendorf[n - Fibonacci[# + 1]] &@ LengthWhile[ Fibonacci /@ Range[2, Ceiling@Log[GoldenRatio, n Sqrt@5]], # <= n &]; zeckendorf /@ Range[0, 20]
http://rosettacode.org/wiki/Zeckendorf_number_representation
Zeckendorf number representation
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, ...
#Nim
Nim
import strformat, strutils   proc z(n: Natural): string = if n == 0: return "0" var fib = @[2,1] var n = n while fib[0] < n: fib.insert(fib[0] + fib[1]) for f in fib: if f <= n: result.add '1' dec n, f else: result.add '0' if result[0] == '0': result = result[1..result.high]   ...
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...
#Comal
Comal
0010 DIM doors#(100) 0020 FOR pass#:=1 TO 100 DO 0030 FOR door#:=pass# TO 100 STEP pass# DO doors#(door#):=NOT doors#(door#) 0040 ENDFOR pass# 0050 FOR door#:=1 TO 100 DO 0060 IF doors#(door#) THEN PRINT "Door ",door#," is open." 0070 ENDFOR door# 0080 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,...
#Genie
Genie
[indent=4] /* Arrays, in Genie   valac --pkg=gee-0.8 arrays.gs ./arrays */   uses Gee   init /* allocate a fixed array */ var arr = new array of int[10]   /* initialized array of strings */ initialized:array of string = {"This", "is", "Genie"}   /* length is an array property */ s...
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  Typica...
#smart_BASIC
smart BASIC
' complex numbers are native for "smart BASIC" A=1+2i B=3-5i   ' all math operations and functions work with complex numbers C=A*B PRINT SQR(-4)   ' example of solving quadratic equation with complex roots ' x^2+2x+5=0 a=1 ! b=2 ! c=5 x1=(-b+SQR(b^2-4*a*c))/(2*a) x2=(-b-SQR(b^2-4*a*c))/(2*a) PRINT x1,x2   ' gives outpu...
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, ...
#ooRexx
ooRexx
/********************************************************************** * 21.04.2014 Walter Pachl **********************************************************************/ Say 'rxCalcpower(0,0) ->' rxCalcpower(0,0) Say '0**0 ->' 0**0 ::requires rxmath library
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, ...
#Openscad
Openscad
echo (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, ...
#PARI.2FGP
PARI/GP
0^0 0.^0 0^0.
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives ...
#Curry
Curry
import Constraint (allC, anyC) import Findall (findall)     data House = H Color Man Pet Drink Smoke   data Color = Red | Green | Blue | Yellow | White data Man = Eng | Swe | Dan | Nor | Ger data Pet = Dog | Birds | Cats | Horse | Zebra data Drink = Coffee | Tea | Milk | Beer | Wat...
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="heal...
#Delphi
Delphi
program XMLXPath;   {$APPTYPE CONSOLE}   uses ActiveX, MSXML;   const 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...
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.
#CLU
CLU
taijitu = cluster is make rep = null   circle = proc (x,y,c,r: int) returns (bool) return (r**2 >= (x/2)**2 + (y-c)**2) end circle   pixel = proc (x,y,r: int) returns (char) if circle(x,y,-r/2,r/6) then return('#') elseif circle(x,y, r/2,r/6) then return('.') elseif c...
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.
#D
D
import std.stdio, std.algorithm, std.array, std.math, std.range, std.conv, std.typecons;   string yinYang(in int n) pure /*nothrow @safe*/ { enum : char { empty = ' ', white = '.', black = '#' }   const radii = [1, 3, 6].map!(i => i * n).array; auto ranges = radii.map!(r => iota(-r, r + 1).array).arr...
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's stat...
#Clojure
Clojure
(defn Y [f] ((fn [x] (x x)) (fn [x] (f (fn [& args] (apply (x x) args))))))   (def fac (fn [f] (fn [n] (if (zero? n) 1 (* n (f (dec n)))))))   (def fib (fn [f] (fn [n] (condp = n 0 0 1 1 (+ (f (dec n)) (f (dec (...
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, gi...
#Ceylon
Ceylon
class ZigZag(Integer size) {   value data = Array { for (i in 0:size) Array.ofSize(size, 0) };   variable value i = 1; variable value j = 1;   for (element in 0 : size^2) { data[j - 1]?.set(i - 1, element); if ((i + j).even) { if (j < size) { j++; } else { i += 2; } if (i > 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, gi...
#Clojure
Clojure
(defn partitions [sizes coll] (lazy-seq (when-let [n (first sizes)] (when-let [s (seq coll)] (cons (take n coll) (partitions (next sizes) (drop n coll)))))))   (defn take-from [n colls] (lazy-seq (when-let [s (seq colls)] (let [[first-n rest-n] (split-at n s)] (cons (map first fi...
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 n...
#Quackery
Quackery
[ stack ] is seqbits ( --> s )   [ bit seqbits take | seqbits put ] is seqadd ( n --> )   [ bit seqbits share & not ] is notinseq ( n --> b )   [ temp put ' [ 1 2 3 ] 7 seqbits put 4 [ dip [ dup -1 peek over -2 peek ] dup...
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 n...
#Racket
Racket
#lang racket   (require plot)   (define a098550 (let ((hsh# (make-hash '((1 . 1) (2 . 2) (3 . 3)))) (rev# (make-hash '((1 . 1) (2 . 2) (3 . 3))))) (λ (n) (hash-ref hsh# n (λ () (let ((a_n (for/first ((i (in-naturals 4)) #:unl...
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 n...
#Raku
Raku
my @yellowstone = 1, 2, 3, -> $q, $p { state @used = True xx 4; state $min = 3; my \index = ($min .. *).first: { not @used[$_] and $_ gcd $q != 1 and $_ gcd $p == 1 }; @used[index] = True; $min = @used.first(!*, :k) // +@used - 1; index } … *;   put "The first 30 terms in the Yellowstone sequen...
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.
#R
R
YahooSearch <- function(query, page=1, .opts=list(), ignoreMarkUpErrors=TRUE) { if(!require(RCurl) || !require(XML)) { stop("Could not load required packages") }   # Replace " " with "%20", etc query <- curlEscape(query)   # Retrieve page b <- 10*(page-1)+1 theurl <- paste("http://uk.se...
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.
#Racket
Racket
#lang racket (require net/url) (define *yaho-url* "http://search.yahoo.com/search?p=~a&b=~a") (define *current-page* 0) (define *current-query* "") (define request (compose port->string get-pure-port string->url))   ;;strip html tags (define (remove-tags text) (regexp-replace* #px"<[^<]+?>" text ""))   ;;search, pars...
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 ...
#Lua
Lua
bc = require("bc") -- since 5$=5^4$, and IEEE754 can handle 4$, this would be sufficient: -- n = bc.pow(bc.new(5), bc.new(4^3^2)) -- but for this task: n = bc.pow(bc.new(5), bc.pow(bc.new(4), bc.pow(bc.new(3), bc.new(2)))) s = n:tostring() print(string.format("%s...%s (%d digits)", s:sub(1,20), s:sub(-20,-1), #s))
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
#Maple
Maple
  > n := 5^(4^(3^2)): > length( n ); # number of digits 183231   > s := convert( n, 'string' ): > s[ 1 .. 20 ], s[ -20 .. -1 ]; # extract first and last twenty digits "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, ...
#PARI.2FGP
PARI/GP
Z(n)=if(!n,print1(0));my(k=2);while(fibonacci(k)<=n,k++); forstep(i=k-1,2,-1,print1(if(fibonacci(i)<=n,n-=fibonacci(i);1,0)));print for(n=0,20,Z(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...
#Commodore_BASIC_2
Commodore BASIC
  10 D=100: DIMD(D): P=1 20 PRINT CHR$(147);"PASS: ";P 22 FOR I=P TO D STEP P: D(I)=NOTD(I): NEXT 30 IF P=100 THEN 40 32 P=P+1: GOTO20 40 PRINT: PRINT"THE FOLLOWING DOORS ARE OPEN: " 42 FOR I=1 TO D: IF D(I)=-1 THEN PRINTI; 44 NEXT  
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,...
#GML
GML
array[0] = ' ' array[1] = 'A' array[2] = 'B' array[3] = 'C'