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/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...
#Icon_and_Unicon
Icon and Unicon
procedure main(args) n := integer(!args) | 5 every !(A := list(n)) := list(n) A := zigzag(A) show(A) end   procedure show(A) every writes(right(!A,5) | "\n") end   procedure zigzag(A) x := [0,0] every i := 0 to (*A^2 -1) do { x := nextIndices(*A, x) A[x[1]][x[2]] := i } ...
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 ...
#SIMPOL
SIMPOL
constant FIRST20 "62060698786608744707" constant LAST20 "92256259918212890625"   function main() integer i string s, s2   i = .ipower(5, .ipower(4, .ipower(3, 2))) s2 = .tostr(i, 10) if .lstr(s2, 20) == FIRST20 and .rstr(s2, 20) == LAST20 s = "Success! The integer matches both the first 20 and the last 2...
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
#Smalltalk
Smalltalk
|num| num := (5 raisedTo: (4 raisedTo: (3 raisedTo: 2))) asString. Transcript show: (num first: 20), '...', (num last: 20); cr; show: 'digits: ', num size asString.
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, ...
#Standard_ML
Standard ML
  val zeckList = fn from => fn to =>   let open IntInf   val rec npow = fn n => fn 0 => fromInt 1 | m => n* (npow n (m-1)) ;   val fib = fn 0 => 1 | 1 => 1 | n => let val rec fb = fn x => fn y => fn 1=>y | n=> fb y (x+y) (n-1) in fb 0 1 n end;   val argminfi = fn 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...
#EchoLisp
EchoLisp
  ; initial state = closed = #f (define doors (make-vector 101 #f)) ; run pass 100 to 1 (for* ((pass (in-range 100 0 -1)) (door (in-range 0 101 pass))) (when (and (vector-set! doors door (not (vector-ref doors door))) (= pass 1)) (writeln door "is open")))   1 "is open" ...
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#Julia
Julia
julia> A = cell(3) # create an heterogeneous array of length 3 3-element Array{Any,1}: #undef #undef #undef julia> A[1] = 4.5 ; A[3] = "some string" ; show(A) {4.5,#undef,"some string"} julia> A[1] # access a value. Arrays are 1-indexed 4.5 julia> push!(A, :symbol) ; show(A) # append an element {4....
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, ...
#XLISP
XLISP
XLISP 3.3, September 6, 2002 Copyright (c) 1984-2002, by David Betz [1] (expt 0 0)   1 [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, ...
#XPL0
XPL0
RlOut(0, 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 ...
#Nim
Nim
import algorithm, strformat, sequtils   type   Color {.pure.} = enum Blue, Green, Red, White, Yellow Person {.pure.} = enum Dane, English, German, Norwegian, Swede Pet {.pure.} = enum Birds, Cats, Dog, Horse, Zebra Drink {.pure.} = enum Beer, Coffee, Milk, Tea, Water Cigarettes {.pure.} = enum Blend, 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...
#Ruby
Ruby
#Example taken from the REXML tutorial (http://www.germane-software.com/software/rexml/docs/tutorial.html) require "rexml/document" include REXML #create the REXML Document from the string (%q is Ruby's multiline string, everything between the two @-characters is the string) doc = Document.new( %q@<inventory ti...
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...
#Scala
Scala
  scala> val xml: scala.xml.Elem = | <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...
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.
#Perl
Perl
sub circle { my ($radius, $cx, $cy, $fill, $stroke) = @_; print "<circle cx='$cx' cy='$cy' r='$radius' ", "fill='$fill' stroke='$stroke' stroke-width='1'/>\n"; }   sub yin_yang { my ($rad, $cx, $cy, %opt) = @_; my ($c, $w) = (1, 0); $opt{fill} //= 'white'; ...
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...
#GAP
GAP
Y := function(f) local u; u := x -> x(x); return u(y -> f(a -> y(y)(a))); end;   fib := function(f) local u; u := function(n) if n < 2 then return n; else return f(n-1) + f(n-2); fi; end; return u; end;   Y(fib)(10); # 55   fac := function(f) ...
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...
#IS-BASIC
IS-BASIC
100 PROGRAM "ZigZag.bas" 110 LET SIZE=5 120 NUMERIC A(1 TO SIZE,1 TO SIZE) 130 LET I,J=1 140 FOR E=0 TO SIZE^2-1 150 LET A(I,J)=E 160 IF ((I+J) BAND 1)=0 THEN 170 IF J<SIZE THEN 180 LET J=J+1 190 ELSE 200 LET I=I+2 210 END IF 220 IF I>1 THEN LET I=I-1 230 ELSE 240 IF I<SIZE THEN 25...
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 ...
#SPL
SPL
t = #.str(5^(4^(3^2))) n = #.size(t) #.output(n," digits") #.output(#.mid(t,1,20),"...",#.mid(t,n-19,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 ...
#Standard_ML
Standard ML
let val answer = IntInf.pow (5, IntInf.toInt (IntInf.pow (4, IntInf.toInt (IntInf.pow (3, 2))))) val s = IntInf.toString answer val len = size s in print ("has " ^ Int.toString len ^ " digits: " ^ substring (s, 0, 20) ^ " ... " ^ substring (s, len-20, 20) ^ "\n") end;
http://rosettacode.org/wiki/Zeckendorf_number_representation
Zeckendorf number representation
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, ...
#Tcl
Tcl
package require Tcl 8.5   # Generates the Fibonacci sequence (starting at 1) up to the largest item that # is no larger than the target value. Could use tricks to precompute, but this # is actually a pretty cheap linear operation. proc fibseq target { set seq {}; set prev 1; set fib 1 for {set n 1;set i 1} {$fi...
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...
#ECL
ECL
  Doors := RECORD UNSIGNED1 DoorNumber; STRING6 State; END;   AllDoors := DATASET([{0,0}],Doors);   Doors OpenThem(AllDoors L,INTEGER Cnt) := TRANSFORM SELF.DoorNumber := Cnt; SELF.State  := IF((CNT * 10) % (SQRT(CNT)*10)<>0,'Closed','Opened'); END;   OpenDoors := NORMALIZE(AllDoors,100,OpenThem(LEFT,COUNTER...
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,...
#KonsolScript
KonsolScript
//creates an array of length 3 Array:New array[3]:Number;   function main() { Var:Number length; Array:GetLength(array, length) //retrieve length of array Konsol:Log(length)   array[0] = 5; //assign value Konsol:Log(array[0]) //retrieve value and display }
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, ...
#Zig
Zig
const std = @import("std");   pub fn main() !void { const stdout = std.io.getStdOut().writer(); try stdout.print("0^0 = {d:.8}\n", .{std.math.pow(f32, 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, ...
#zkl
zkl
(0.0).pow(0) //--> 1.0 var BN=Import("zklBigNum"); // big ints BN(0).pow(0) //--> 1
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives ...
#Pari.2FGp
Pari/Gp
  perm(arr) = { n=#arr;i=n-1; while(i > -1,if (arr[i] < arr[i+1],break);i--); j=n; while(arr[j]<= arr[i],j -=1); tmp = arr[i] ;arr[i]=arr[j];arr[j]=tmp; i +=1; j = n; while(i < j ,tmp = arr[i] ;arr[i]=arr[j];arr[j]=tmp; i +=1; j -=1); return(arr); } perms(arr)={ n=#arr; result = List(); listput(result,arr); for(i=1,n!-...
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="heal...
#SenseTalk
SenseTalk
Set XMLSource to {{ <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 S...
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...
#Sidef
Sidef
require('XML::XPath');   var x = %s'XML::XPath'.new(ARGF.slurp);   [x.findnodes('//item[1]')][0]; say [x.findnodes('//price')].map{x.getNodeText(_)}; [x.findnodes('//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.
#Phix
Phix
-- -- demo\rosetta\Yin_and_yang.exw -- ============================= -- with javascript_semantics include pGUI.e Ihandle dlg, canvas cdCanvas cd_canvas procedure cdCanvasSecArc(cdCanvas hCdCanvas, atom xc, atom yc, atom w, atom h, atom angle1, atom angle2) -- cdCanvasSector does not draw anti-aliased edges, but cdCa...
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...
#Genyris
Genyris
def fac (f) function (n) if (equal? n 0) 1 * n (f (- n 1)) def fib (f) function (n) cond (equal? n 0) 0 (equal? n 1) 1 else (+ (f (- n 1)) (f (- n 2)))   def Y (f) (function (x) (x x)) function (y) f function (&rest args) (apply (y y) args)   asse...
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...
#J
J
($ [: /:@; <@|.`</.@i.)@,~ 5 0 1 5 6 14 2 4 7 13 15 3 8 12 16 21 9 11 17 20 22 10 18 19 23 24
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
#Stata
Stata
set bigValue [expr {5**4**3**2}] puts "5**4**3**2 has [string length $bigValue] digits" if {[string match "62060698786608744707*92256259918212890625" $bigValue]} { puts "Value starts with 62060698786608744707, ends with 92256259918212890625" } else { puts "Value does not match 62060698786608744707...92256259918...
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 ...
#Tcl
Tcl
set bigValue [expr {5**4**3**2}] puts "5**4**3**2 has [string length $bigValue] digits" if {[string match "62060698786608744707*92256259918212890625" $bigValue]} { puts "Value starts with 62060698786608744707, ends with 92256259918212890625" } else { puts "Value does not match 62060698786608744707...92256259918...
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, ...
#uBasic.2F4tH
uBasic/4tH
For x = 0 to 20 ' Print Zeckendorf numbers 0 - 20 Print x, Push x : Gosub _Zeckendorf ' get Zeckendorf number repres. Print ' terminate line Next   End   _Fibonacci Push Tos() ' duplicate TOS() @(0) = 0 ...
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...
#EDSAC_order_code
EDSAC order code
  [Hundred doors problem from Rosetta Code website] [EDSAC program, Initial Orders 2]   [Library subroutine M3. Prints header and is then overwritten. Here, the last character sets the teleprinter to figures.] PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF @&*THE!OPEN!DOORS!ARE@&# ..PZ [blank tape, needed to mar...
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,...
#Kotlin
Kotlin
fun main(x: Array<String>) { var a = arrayOf(1, 2, 3, 4) println(a.asList()) a += 5 println(a.asList()) println(a.reversedArray().asList()) }
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 ...
#Perl
Perl
#!/usr/bin/perl   use utf8; use strict; binmode STDOUT, ":utf8";   my (@tgt, %names); sub setprops { my %h = @_; my @p = keys %h; for my $p (@p) { my @v = @{ $h{$p} }; @tgt = map(+{idx=>$_-1, map{ ($_, undef) } @p}, 1 .. @v) unless @tgt; $names{$_} = $p for @v; } }   my $solve = sub { for my $i (@tgt) { ...
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...
#Tcl
Tcl
# assume $xml holds the XML data package require tdom set doc [dom parse $xml] set root [$doc documentElement]   set allNames [$root selectNodes //name] puts [llength $allNames] ;# ==> 4   set firstItem [lindex [$root selectNodes //item] 0] puts [$firstItem @upc] ;# ==> 123456789   foreach node [$root selectNodes //pri...
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="heal...
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT,{} MODE DATA $$ XML=* <inventory title="OmniCorp Store #45x10³"> <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.
#PHL
PHL
module circles;   extern printf;   @Boolean in_circle(@Integer centre_x, @Integer centre_y, @Integer radius, @Integer x, @Integer y) [ return (x-centre_x)*(x-centre_x)+(y-centre_y)*(y-centre_y) <= radius*radius; ]   @Boolean in_big_circle (@Integer radius, @Integer x, @Integer y) [ return in_circle(0, 0, radius, x, y...
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.
#PicoLisp
PicoLisp
(de circle (X Y C R) (>= (* R R) (+ (* (setq X (/ X 2)) X) (* (dec 'Y C) Y) ) ) )   (de yinYang (R) (for Y (range (- R) R) (for X (range (- 0 R R) (+ R R)) (prin (cond ((circle X Y (- (/ R 2)) (/ R 6)) "#" ) (...
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...
#Go_2
Go
package main   import "fmt"   type Func func(int) int type FuncFunc func(Func) Func type RecursiveFunc func (RecursiveFunc) Func   func main() { fac := Y(almost_fac) fib := Y(almost_fib) fmt.Println("fac(10) = ", fac(10)) fmt.Println("fib(10) = ", fib(10)) }   func Y(f FuncFunc) Func { g := func(r RecursiveFunc) F...
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...
#Java
Java
public static int[][] Zig_Zag(final int size) { int[][] data = new int[size][size]; int i = 1; int j = 1; for (int element = 0; element < size * size; element++) { data[i - 1][j - 1] = element; if ((i + j) % 2 == 0) { // Even stripes if (j < size) j++; else i+= 2; if (i > 1) i--; } ...
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 ...
#TXR
TXR
@(bind (f20 l20 ndig) @(let* ((str (tostring (expt 5 4 3 2))) (len (length str))) (list [str :..20] [str -20..:] len))) @(bind f20 "62060698786608744707") @(bind l20 "92256259918212890625") @(output) @f20...@l20 ndigits=@ndig @(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 ...
#Ursa
Ursa
import "unbounded_int" decl unbounded_int x x.set ((x.valueof 5).pow ((x.valueof 4).pow ((x.valueof 3).pow 2)))   decl string first last xstr set xstr (string x)   # get the first twenty digits decl int i for (set i 0) (< i 20) (inc i) set first (+ first xstr<i>) end for   # get the last twenty digits for (set i (- (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 ...
#Ursala
Ursala
#import std #import nat #import bcd   #show+   main = <.@ixtPX take/$20; ^|T/~& '...'--@x,'length: '--@h+ %nP+ length@t>@h %vP power=> <5_,4_,3_,2_>
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, ...
#VBA
VBA
Private Function zeckendorf(ByVal n As Integer) As Integer Dim r As Integer: r = 0 Dim c As Integer Dim fib As New Collection fib.Add 1 fib.Add 1 Do While fib(fib.Count) < n fib.Add fib(fib.Count - 1) + fib(fib.Count) Loop For i = fib.Count To 2 Step -1 c = n >= fib(i) ...
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#Eero
Eero
  #import <Foundation/Foundation.h>   int main() square := 1, increment = 3   for int door in 1 .. 100 printf("door #%d", door)   if door == square puts(" is open.") square += increment increment += 2 else puts(" is closed.")   return 0  
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,...
#LabVIEW
LabVIEW
  // Create a new array with length 0 {def myArray1 {A.new}} -> []   // Create an array with 2 members (length is 2) {def myArray2 {A.new Item1 Item2}} -> [Item1,Item2]   // Edit a value in an array {def myArray3 {A.new 1 2 3}} {A.set! 1 hello {myArray3}} -> [1,hello,3]   // Add a value at the head of an array {def my...
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 ...
#Phix
Phix
enum Colour, Nationality, Drink, Smoke, Pet constant Colours = {"red","white","green","yellow","blue"}, Nationalities = {"English","Swede","Dane","Norwegian","German"}, Drinks = {"tea","coffee","milk","beer","water"}, Smokes = {"Pall Mall","Dunhill","Blend","Blue Master","Prince"}, P...
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...
#VBScript
VBScript
  Set objXMLDoc = CreateObject("msxml2.domdocument")   objXMLDoc.load("In.xml")   Set item_nodes = objXMLDoc.selectNodes("//item") i = 1 For Each item In item_nodes If i = 1 Then WScript.StdOut.Write item.xml WScript.StdOut.WriteBlankLines(2) Exit For End If Next   Set price_nodes = objXMLDoc.selectNodes("//pri...
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="heal...
#Visual_Basic_.NET
Visual Basic .NET
Dim first_item = xml.XPathSelectElement("//item") Console.WriteLine(first_item)   For Each price In xml.XPathSelectElements("//price") Console.WriteLine(price.Value) Next   Dim names = (From item In xml.XPathSelectElements("//name") Select item.Value).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.
#Plain_English
Plain English
To run: Start up. Clear the screen to the gray color. Draw the Taijitu symbol 4 inches wide at the screen's center. Put the screen's center into a spot. Move the spot 4 inches right. Draw the Taijitu symbol 2 inches wide at the spot. Refresh the screen. Wait for the escape key. Shut down.   To draw the Taijitu symbol s...
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.
#PL.2FI
PL/I
yinyang: procedure options(main); yinyang: procedure(r); circle: procedure(x, y, c, r) returns(bit); declare (x, y, c, r) fixed; return( r*r >= (x/2) * (x/2) + (y-c) * (y-c) ); end circle;   pixel: procedure(x, y, r) returns(char); declare (x, y, r) fixed;...
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...
#Groovy
Groovy
def Y = { le -> ({ f -> f(f) })({ f -> le { x -> f(f)(x) } }) }   def factorial = Y { fac -> { n -> n <= 2 ? n : n * fac(n - 1) } }   assert 2432902008176640000 == factorial(20G)   def fib = Y { fibStar -> { n -> n <= 1 ? n : fibStar(n - 1) + fibStar(n - 2) } }   assert fib(10) == 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, gi...
#JavaScript
JavaScript
function ZigZagMatrix(n) { this.height = n; this.width = n;   this.mtx = []; for (var i = 0; i < n; i++) this.mtx[i] = [];   var i=1, j=1; for (var e = 0; e < n*n; e++) { this.mtx[i-1][j-1] = e; if ((i + j) % 2 == 0) { // Even stripes if (j < n) j...
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 ...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Console Imports BI = System.Numerics.BigInteger   Module Module1   Dim Implems() As String = {"Built-In", "Recursive", "Iterative"}, powers() As Integer = {5, 4, 3, 2}   Function intPowR(val As BI, exp As BI) As BI If exp = 0 Then Return 1 Dim ne As BI, vs As BI = val * v...
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, ...
#VBScript
VBScript
  Function Zeckendorf(n) num = n Set fibonacci = CreateObject("System.Collections.Arraylist") fibonacci.Add 1 : fibonacci.Add 2 i = 1 Do While fibonacci(i) < num fibonacci.Add fibonacci(i) + fibonacci(i-1) i = i + 1 Loop tmp = "" For j = fibonacci.Count-1 To 0 Step -1 If fibonacci(j) <= num And (tmp = "" ...
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...
#Egel
Egel
  import "prelude.eg"   using System using List   data open, closed   def toggle = [ open N -> closed N | closed N -> open N ]   def doors = [ N -> map [ N -> closed N ] (fromto 1 N) ]   def toggleK = [ K nil -> nil | K (cons (D N) DD) -> let DOOR = if (N%K) == 0 then toggle (D N...
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,...
#Lambdatalk
Lambdatalk
  // Create a new array with length 0 {def myArray1 {A.new}} -> []   // Create an array with 2 members (length is 2) {def myArray2 {A.new Item1 Item2}} -> [Item1,Item2]   // Edit a value in an array {def myArray3 {A.new 1 2 3}} {A.set! 1 hello {myArray3}} -> [1,hello,3]   // Add a value at the head of an array {def my...
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 ...
#Picat
Picat
import cp.   main => Nat = [English, Swede, Dane, German, Norwegian], Color = [Red, Green, White, Yellow, Blue], Smoke = [PallMall, Dunhill, Blend, SBlue, Prince], Pet = [Dog, Bird, Cat, Horse, Zebra], Drink = [Tea, Coffee, Milk, Beer, Water],   Nat  :: 1..5, Col...
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...
#Wren
Wren
import "/pattern" for Pattern   var doc = """ <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.
#PostScript
PostScript
%!PS-Adobe-3.0 %%BoundingBox: 0 0 400 400   /fs 10 def /ed { exch def } def /dist { 3 -1 roll sub dup mul 3 1 roll sub dup mul add sqrt } def /circ { /r exch def [r neg 1 r { /y exch def [ r 2 mul neg 1 r 2 mul { /x ed x 2 div y 0 0 dist r .05 add gt {( )}{ x 2 div y ...
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...
#Haskell
Haskell
newtype Mu a = Roll { unroll :: Mu a -> a }   fix :: (a -> a) -> a fix = g <*> (Roll . g) where g = (. (>>= id) unroll)   - this version is not in tail call position... -- fac :: Integer -> Integer -- fac = -- fix $ \f n -> if n <= 0 then 1 else n * f (n - 1)   -- this version builds a progression from tail c...
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...
#Joy
Joy
  (* From the library. *) DEFINE reverse == [] swap shunt; shunt == [swons] step.   (* Split according to the parameter given. *) DEFINE take-drop == [dup] swap dup [[] cons [take swap] concat concat] dip [] cons concat [drop] concat.   (* Take the first of a list of lists. *)...
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 ...
#Vlang
Vlang
import math.big import math   fn main() {   mut x := u32(math.pow(3,2)) x = u32(math.pow(4,x)) mut y := big.integer_from_int(5) y = y.pow(x) str := y.str() println("5^(4^(3^2)) has $str.len digits: ${str[..20]} ... ${str[str.len-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 ...
#Wren
Wren
import "/fmt" for Fmt import "/big" for BigInt   var p = BigInt.three.pow(BigInt.two) p = BigInt.four.pow(p) p = BigInt.five.pow(p) var s = p.toString Fmt.print("5 ^ 4 ^ 3 ^ 2 has $,d digits.\n", s.count) System.print("The first twenty are  : %(s[0..19])") System.print("and the last twenty are : %(s[-20..-1])")
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, ...
#Vlang
Vlang
fn main() { for i := 0; i <= 20; i++ { println("${i:2} ${zeckendorf(i):7b}") } }   fn zeckendorf(n int) int { // initial arguments of fib0 = 1 and fib1 = 1 will produce // the Fibonacci sequence {1, 2, 3,..} on the stack as successive // values of fib1. _, set := zr(1, 1, n, 0) retur...
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, ...
#Wren
Wren
import "/fmt" for Fmt   var LIMIT = 46 // to stay within range of signed 32 bit integer   var fibonacci = Fn.new { |n| if (n < 2 || n > LIMIT) Fiber.abort("n must be between 2 and %(LIMIT)") var fibs = List.filled(n, 1) for (i in 2...n) fibs[i] = fibs[i - 1] + fibs[i - 2] return fibs }   var fibs = fib...
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...
#EGL
EGL
  program OneHundredDoors   function main()   doors boolean[] = new boolean[100]; n int = 100;   for (i int from 1 to n) for (j int from i to n by i) doors[j] = !doors[j]; end end   for (i int from 1 to n) if (doors[i]) SysLib.writeStdo...
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,...
#lang5
lang5
[] 1 append ['foo 'bar] append 2 reshape 0 remove 2 swap 2 compress collapse .
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 ...
#PicoLisp
PicoLisp
(be match (@House @Person @Drink @Pet @Cigarettes) (permute (red blue green yellow white) @House) (left-of @House white @House green)   (permute (Norwegian English Swede German Dane) @Person) (has @Person English @House red) (equal @Person (Norwegian . @)) (next-to @Person Norwegian @House blue)   ...
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="heal...
#XProc
XProc
<p:pipeline xmlns:p="http://www.w3.org/ns/xproc" name="one-two-three" version="1.0"> <p:identity> <p:input port="source"> <p:inline> <root> <first/> <prices/> <names/> </root> </p:inline> </p:input> </p:identity> <p:insert match="/root/first" p...
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...
#XQuery
XQuery
(: 1. Retrieve the first "item" element Notice the braces around //item. This evaluates first all item elements and then retrieving the first one. Whithout the braces you get the first item for every section. :) let $firstItem := (//item)[1]   (: 2. Perform an action on each "price" element (print it out) :) l...
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.
#POV-Ray
POV-Ray
  // ====== General Scene setup ====== #version 3.7; global_settings { assumed_gamma 2.2 }   camera{ location <0,2.7,4> look_at <0,.1,0> right x*1.6 aperture .2 focal_point <1,0,0> blur_samples 200 variance 1/10000 } light_source{<2,4,8>, 1 spotlight point_at 0 radius 10} sky_sphere {pigment {granite scale <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.
#Prolog
Prolog
ying_yang(N) :- R is N * 100, sformat(Title, 'Yin Yang ~w', [N]), new(W, window(Title)), new(Wh, colour(@default, 255*255, 255*255, 255*255)), new(Bl, colour(@default, 0, 0, 0)), CX is R + 50, CY is R + 50, R1 is R / 2, R2 is R / 8, CY1 is R1 + 50, CY2 is 3 * R1 + 50,   new(E, semi_disk(point(CX, CY), R, w,...
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...
#J
J
Y=. '('':''<@;(1;~":0)<@;<@((":0)&;))'(2 : 0 '') (1 : (m,'u'))(1 : (m,'''u u`:6('',(5!:5<''u''),'')`:6 y'''))(1 :'u u`:6') )  
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, gi...
#jq
jq
# Create an m x n matrix def matrix(m; n; init): if m == 0 then [] elif m == 1 then [range(0;n)] | map(init) elif m > 0 then matrix(1;n;init) as $row | [range(0;m)] | map( $row ) else error("matrix\(m);_;_) invalid") end ;   # Print a matrix neatly, each cell occupying n spaces def neatly(n): ...
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
#Zig
Zig
const std = @import("std"); const bigint = std.math.big.int.Managed;   pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = &gpa.allocator; defer _ = gpa.deinit();   var a = try bigint.initSet(allocator, 5); try a.pow(a.toConst(), try std.math.powi(u32, 4, try 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 ...
#zkl
zkl
var BN=Import("zklBigNum"); n:=BN(5).pow(BN(4).pow(BN(3).pow(2))); s:=n.toString(); "%,d".fmt(s.len()).println(); println(s[0,20],"...",s[-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, ...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations   proc Zeckendorf(N); \Display Zeckendorf number (N <= 20) int N; int Fib, LZ, I; [Fib:= [1, 2, 3, 5, 8, 13]; \Fibonacci sequence LZ:= true; \suppress leading zeros for I:= 5 downto 1 do [if N >= Fib(I) then [N:=...
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, ...
#Yabasic
Yabasic
sub Zeckendorf(n) local i, n$, c   do n$ = bin$(i) if not instr(n$,"11") then print c,":\t",n$ if c = n break c = c + 1 end if i = i + 1 loop end sub   Zeckendorf(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...
#Eiffel
Eiffel
note description: "100 Doors problem" date: "08-JUL-2015" revision: "1.1"   class APPLICATION   create make   feature {NONE} -- Initialization   make -- Main application routine. do initialize_closed_doors toggle_doors output_door_states end   feature -- Access   doors: ARRAYED_LIST [DOOR] -- ...
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#langur
langur
var .a1 = [1, 2, 3, "abc"] val .a2 = series 4..10 val .a3 = .a1 ~ .a2   writeln "initial values ..." writeln ".a1: ", .a1 writeln ".a2: ", .a2 writeln ".a3: ", .a3 writeln()   .a1[4] = .a2[4] writeln "after setting .a1[4] = .a2[4] ..." writeln ".a1: ", .a1 writeln ".a2: ", .a2 writeln ".a3: ", .a3 writeln()   writeln "...
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 ...
#Prolog
Prolog
select([A|As],S):- select(A,S,S1),select(As,S1). select([],_).   next_to(A,B,C):- left_of(A,B,C) ; left_of(B,A,C). left_of(A,B,C):- append(_,[A,B|_],C).   zebra(Owns, HS):- % color,nation,pet,drink,smokes HS = [ h(_,norwegian,_,_,_), _, h(_,_,_,milk,_), _, _], select( [ h(red,englishman,_,_,_), h(_,...
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...
#XSLT
XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" /> <xsl:template match="/">   <!-- 1. first item element --> <xsl:text> The first item element is</xsl:text> <xsl:value-of select="//item[1]" />   <!-- 2. Print each price element --> <xsl:t...
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#Python
Python
import math def yinyang(n=3): radii = [i * n for i in (1, 3, 6)] ranges = [list(range(-r, r+1)) for r in radii] squares = [[ (x,y) for x in rnge for y in rnge] for rnge in ranges] circles = [[ (x,y) for x,y in sqrpoints if math.hypot(x,y) <= radius ] for sqrpoints, radius in zip(squares, radii)]...
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...
#Java_2
Java
import java.util.function.Function;   public interface YCombinator { interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { } public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) { RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x)); retur...
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...
#Julia
Julia
function zigzag_matrix(n::Int) matrix = zeros(Int, n, n) x, y = 1, 1 for i = 0:(n*n-1) matrix[y,x] = i if (x + y) % 2 == 0 # Even stripes if x < n x += 1 y -= (y > 1) else y += 1 end else ...
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, ...
#zkl
zkl
// return powers (0|1) of fib sequence (1,2,3,5,8...) that sum to n fcn zeckendorf(n){ //-->String of 1s & 0s, no consecutive 1's if(n<=0) return("0"); fibs:=fcn(ab){ ab.append(ab.sum()).pop(0) }.fp(L(1,2)); (0).pump(*,List,fibs,'wrap(fib){ if(fib>n)Void.Stop else fib }) .reverse() .pump(String,fcn(f...
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...
#Ela
Ela
open generic   type Door = Open | Closed deriving Show   gate [] _ = [] gate (x::xs) (y::ys) | x == y = Open :: gate xs ys | else = Closed :: gate xs ys   run n = gate [1..n] [& k*k \\ k <- [1..]]
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#Lasso
Lasso
// Create a new empty array local(array1) = array   // Create an array with 2 members (#myarray->size is 2) local(array1) = array('ItemA','ItemB')   // Assign a value to member [2] #array1->get(2) = 5   // Retrieve a value from an array #array1->get(2) + #array1->size // 8   // Merge arrays local( array1 = array(...
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 ...
#Python
Python
  from logpy import * from logpy.core import lall import time   def lefto(q, p, list): # give me q such that q is left of p in list # zip(list, list[1:]) gives a list of 2-tuples of neighboring combinations # which can then be pattern-matched against the query return membero((q,p), zip(list, list[1:]))   def nexto(...
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.
#Quackery
Quackery
[ $ "turtleduck.qky" loadfile ] now!   [ -1 4 turn 2dup -v fly 1 4 turn 4 wide ' [ 0 0 0 ] colour ' [ 0 0 0 ] fill [ 2dup 2 1 v/ 1 2 arc 2dup -2 1 v/ 1 2 arc 2dup -v 1 2 arc ] 2dup -v 1 2 arc 1 4 turn 2dup 2 1 v/ fly ' [ 0 0 0 ] colour 1 wide ' [ 25...
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.
#R
R
plot.yin.yang <- function(x=5, y=5, r=3, s=10, add=F){ suppressMessages(require("plotrix")) if(!add) plot(1:10, type="n", xlim=c(0,s), ylim=c(0,s), xlab="", ylab="", xaxt="n", yaxt="n", bty="n", asp=1) draw.circle(x, y, r, border="white", col= "black") draw.ellipse(x, y, r, r, col="white", angle=0, segment=c(90,270...
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...
#JavaScript
JavaScript
function Y(f) { var g = f((function(h) { return function() { var g = f(h(h)); return g.apply(this, arguments); } })(function(h) { return function() { var g = f(h(h)); return g.apply(this, arguments); } })); return g; }   var...
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...
#Klingphix
Klingphix
include ..\Utilitys.tlhy     %Size 5 !Size 0 ( $Size dup ) dim   %i 1 !i %j 1 !j     $Size 2 power [ 1 - ( $i $j ) set $i $j + 1 band 0 == ( [$j $Size < ( [$j 1 + !j] [$i 2 + !i] ) if $i 1 > [ $i 1 - !i] if ] [$i $Size < ( [$i 1 + !i] [$j 2 + !j] ) if $j 1 > [ $j 1 - !j] if...
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...
#Elena
Elena
import system'routines; import extensions;   public program() { var Doors := Array.allocate(100).populate:(n=>false); for(int i := 0, i < 100, i := i + 1) { for(int j := i, j < 100, j := j + i + 1) { Doors[j] := Doors[j].Inverted } };   for(int i := 0, i < 100, i...
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#Latitude
Latitude
;; Construct an array. foo := [1, 2, 3].   ;; Arrays can also be constructed explicitly. bar := Array clone. bar pushBack (1). bar pushBack (2). bar pushBack (3).   ;; Accessing values. println: foo nth (2). ;; 3   ;; Mutating values. foo nth (1) = 99. println: foo. ;; [1, 99, 3]   ;; Appending to either the front or t...
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 ...
#R
R
    library(combinat)   col <- factor(c("Red","Green","White","Yellow","Blue")) own <- factor(c("English","Swedish","Danish","German","Norwegian")) pet <- factor(c("Dog","Birds","Cats","Horse","Zebra")) drink <- factor(c("Coffee","Tea","Milk","Beer","Water")) smoke <- factor(c("PallMall", "Blend", "Dunhill", "BlueMaste...
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.
#Racket
Racket
  #lang racket (require slideshow/pict)   (define (yin-yang d) (define base (hc-append (inset/clip (circle d) 0 0 (- (/ d 2)) 0) (inset/clip (disk d) (- (/ d 2)) 0 0 0))) (define with-top (ct-superimpose base (cc-superimpose (colorize (disk (/ d 2)) "white") (d...
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.
#Raku
Raku
sub circle ($rad, $cx, $cy, $fill = 'white', $stroke = 'black' ){ say "<circle cx='$cx' cy='$cy' r='$rad' fill='$fill' stroke='$stroke' stroke-width='1'/>"; }   sub yin_yang ($rad, $cx, $cy, :$fill = 'white', :$stroke = 'black', :$angle = 90) { my ($c, $w) = (1, 0); say "<g transform='rotate($angle, $cx, $c...
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...
#Joy
Joy
DEFINE y == [dup cons] swap concat dup cons i;   fac == [ [pop null] [pop succ] [[dup pred] dip i *] ifte ] y.
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...
#Kotlin
Kotlin
// version 1.1.3   typealias Vector = IntArray typealias Matrix = Array<Vector>   fun zigzagMatrix(n: Int): Matrix { val result = Matrix(n) { Vector(n) } var down = false var count = 0 for (col in 0 until n) { if (down) for (row in 0..col) result[row][col - row] = count++ el...