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/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...
#C1R
C1R
100_doors
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,...
#Euphoria
Euphoria
  --Arrays task for Rosetta Code wiki --User:Lnettnay   atom dummy --Arrays are sequences -- single dimensioned array of 10 elements sequence xarray = repeat(0,10) xarray[5] = 5 dummy = xarray[5] ? dummy   --2 dimensional array --5 sequences of 10 elements each sequence xyarray = repeat(repeat(0,10),5) xyarray[3][6] = ...
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...
#PostScript
PostScript
  %Adding two complex numbers /addcomp{ /x exch def /y exch def /z [0 0] def z 0 x 0 get y 0 get add put z 1 x 1 get y 1 get add put z pstack }def   %Subtracting one complex number from another /subcomp{ /x exch def /y exch def /z [0 0] def z 0 x 0 get y 0 get sub put z 1 x 1 get y 1 get sub put z pstack }def   %Mul...
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...
#PowerShell
PowerShell
  class Complex { [Double]$x [Double]$y Complex() { $this.x = 0 $this.y = 0 } Complex([Double]$x, [Double]$y) { $this.x = $x $this.y = $y } [Double]abs2() {return $this.x*$this.x + $this.y*$this.y} [Double]abs() {return [math]::sqrt($this.abs2())} static [Complex]add([Complex]$...
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...
#Rust
Rust
use std::cmp::Ordering; use std::ops::{Add, AddAssign, Sub, SubAssign, Mul, MulAssign, Div, DivAssign, Neg};   fn gcd(a: i64, b: i64) -> i64 { match b { 0 => a, _ => gcd(b, a % b), } }   fn lcm(a: i64, b: i64) -> i64 { a / gcd(a, b) * b }   #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, O...
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geomet...
#VBScript
VBScript
  Function agm(a,g) Do Until a = tmp_a tmp_a = a a = (a + g)/2 g = Sqr(tmp_a * g) Loop agm = a End Function   WScript.Echo agm(1,1/Sqr(2))  
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geomet...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Math Imports System.Console   Module Module1   Function CalcAGM(ByVal a As Double, ByVal b As Double) As Double Dim c As Double, d As Double = 0, ld As Double = 1 While ld <> d : c = a : a = (a + b) / 2 : b = Sqrt(c * b) ld = d : d = a - b : End While : Return b End Fu...
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, ...
#JavaScript
JavaScript
> Math.pow(0, 0); 1
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time, ...
#jq
jq
def power(y): y as $y | if $y == 0 then 1 elif . == 0 then 0 else log * $y | exp end;
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time, ...
#Jsish
Jsish
puts(Math.pow(0,0));
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.
#11l
11l
F yinyang(n = 3) V radii = [1, 3, 6].map(i -> i * @n) V ranges = radii.map(r -> Array(-r .. r)) V squares = ranges.map(rnge -> multiloop(rnge, rnge, (x, y) -> (x, y))) V circles = zip(squares, radii).map((sqrpoints, radius) -> sqrpoints.filter((x, y) -> x*x + y*y <= @radius^2)) V m = Dict(squares.last, (...
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...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program Ycombi64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64...
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...
#AppleScript
AppleScript
set n to 5 -- Size of zig-zag matrix (n^2 cells).   -- Create an empty matrix. set m to {} repeat with i from 1 to n set R to {} repeat with j from 1 to n set end of R to 0 end repeat set end of m to R end repeat   -- Populate the matrix in a zig-zag manner. set {x, y, v, d} to {1, 1, 0, 1} repeat while v < (n ^ ...
http://rosettacode.org/wiki/Yellowstone_sequence
Yellowstone sequence
The Yellowstone sequence, also called the Yellowstone permutation, is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence is a permutation of the natural n...
#Factor
Factor
USING: accessors assocs colors.constants combinators.short-circuit io kernel math prettyprint sequences sets ui ui.gadgets ui.gadgets.charts ui.gadgets.charts.lines ;   : yellowstone? ( n hs seq -- ? ) { [ drop in? not ] [ nip last gcd nip 1 = ] [ nip dup length 2 - swap nth gcd nip 1 > ] ...
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...
#Forth
Forth
: array create cells allot ; : th cells + ; \ some helper words   30 constant #yellow \ number of yellowstones   #yellow array y \ create array ( n1 n2 -- n3) : gcd dup if tuck mod recurse exit then drop ; : init 3 ...
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.
#C.23
C#
using System; using System.Net; using System.Text.RegularExpressions; using System.Collections.Generic;   class YahooSearch { private string query; private string content; private int page;   const string yahoo = "http://search.yahoo.com/search?";   public YahooSearch(string query) : this(query, 0) ...
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The ...
#Scheme
Scheme
  (import (scheme base) (scheme char) (scheme cxr) (scheme write) (srfi 1 lists))   ;; convert a string into a list of tokens (define (string->tokens str) (define (next-token chars) (cond ((member (car chars) (list #\+ #\- #\* #\/) char=?) (values (cdr chars) ...
http://rosettacode.org/wiki/Zeckendorf_arithmetic
Zeckendorf arithmetic
This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation. The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions. Addition Like bin...
#Racket
Racket
#lang racket (require math)   (define sqrt5 (sqrt 5)) (define phi (* 0.5 (+ 1 sqrt5)))   ;; What is the nth fibonnaci number, shifted by 2 so that ;; F(0) = 1, F(1) = 2, ...? ;; (define (F n) (fibonacci (+ n 2)))   ;; What is the largest n such that F(n) <= m? ;; (define (F* m) (let ([n (- (inexact->exact (round (/...
http://rosettacode.org/wiki/Zeckendorf_arithmetic
Zeckendorf arithmetic
This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation. The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions. Addition Like bin...
#Raku
Raku
addition: +z subtraction: -z multiplication: *z division: /z (more of a divmod really) post increment: ++z post decrement: --z
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 ...
#Phix
Phix
function isPartSum(sequence f, integer l, t) if t=0 then return true end if if l=0 then return false end if integer last = f[l] return (t>=last and isPartSum(f, l-1, t-last)) or isPartSum(f, l-1, t) end function function isZumkeller(integer n) sequence f = factors(n,1) integer t = sum(...
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 ...
#Erlang
Erlang
  -module(arbitrary). -compile([export_all]).   pow(B,E) when E > 0 -> pow(B,E,1).   pow(_,0,_) -> 0; pow(B,1,Acc) -> Acc * B; pow(B,P,Acc) when P rem 2 == 0 -> pow(B*B,P div 2, Acc); pow(B,P,Acc) -> pow(B,P-1,Acc*B).   test() -> I = pow(5,pow(4,pow(3,2))), S = integer_to_list(I), L = 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: ################# ############# ################## ################ #################...
#Phix
Phix
with javascript_semantics constant n = {{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1},{-1,0}}; function AB(sequence text, integer y, x, step) integer wtb = 0, bn = 0 integer prev = '#', next string p2468 = "" for i=1 to length(n) do next = text[y+n[i][1]][x+n[i][2]] wtb += (prev='.' and ne...
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, ...
#FreeBASIC
FreeBASIC
' version 17-10-2016 ' compile with: fbc -s console   #Define max 92 ' max for Fibonacci number   Dim Shared As ULongInt fib(max)   fib(0) = 1 fib(1) = 1   For x As Integer = 2 To max fib(x) = fib(x-1) + fib(x-2) Next   Function num2zeck(n As Integer) As String   If n < 0 Then Print "Error: no negative numbers allo...
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...
#Cach.C3.A9_ObjectScript
Caché ObjectScript
  for i=1:1:100 { set doors(i) = 0 } for i=1:1:100 { for door=i:i:100 { Set doors(door)='doors(door) } } for i = 1:1:100 { if doors(i)=1 write i_": 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,...
#Explore
Explore
> Array.create 6 'A';; val it : char [] = [|'A'; 'A'; 'A'; 'A'; 'A'; 'A'|] > Array.init 8 (fun i -> i * 10) ;; val it : int [] = [|0; 10; 20; 30; 40; 50; 60; 70|] > let arr = [|0; 1; 2; 3; 4; 5; 6 |] ;; val arr : int [] = [|0; 1; 2; 3; 4; 5; 6|] > arr.[4];; val it : int = 4 > arr.[4] <- 65 ;; val it : unit = () > arr;;...
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...
#PureBasic
PureBasic
Structure Complex real.d imag.d EndStructure   Procedure Add_Complex(*A.Complex, *B.Complex) Protected *R.Complex=AllocateMemory(SizeOf(Complex)) If *R *R\real=*A\real+*B\real *R\imag=*A\imag+*B\imag EndIf ProcedureReturn *R EndProcedure   Procedure Inv_Complex(*A.Complex) Protected *R.Complex=Al...
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...
#Scala
Scala
class Rational(n: Long, d:Long) extends Ordered[Rational] { require(d!=0) private val g:Long = gcd(n, d) val numerator:Long = n/g val denominator:Long = d/g   def this(n:Long)=this(n,1)   def +(that:Rational):Rational=new Rational( numerator*that.denominator + that.numerator*denominator, d...
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geomet...
#Vlang
Vlang
import math   const ep = 1e-14   fn agm(aa f64, gg f64) f64 { mut a, mut g := aa, gg for math.abs(a-g) > math.abs(a)*ep { t := a a, g = (a+g)*.5, math.sqrt(t*g) } return a }   fn main() { println(agm(1.0, 1.0/math.sqrt2)) }
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geomet...
#Wren
Wren
var eps = 1e-14   var agm = Fn.new { |a, g| while ((a-g).abs > a.abs * eps) { var t = a a = (a+g)/2 g = (t*g).sqrt } return a }   System.print(agm.call(1, 1/2.sqrt))
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, ...
#Julia
Julia
using Printf   const types = (Complex, Float64, Rational, Int, Bool)   for Tb in types, Te in types zb, ze = zero(Tb), zero(Te) r = zb ^ ze @printf("%10s ^ %-10s = %7s ^ %-7s = %-12s (%s)\n", Tb, Te, zb, ze, r, typeof(r)) end
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time, ...
#K
K
  0^0 1.0  
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time, ...
#Klingphix
Klingphix
:mypower dup not ( [ drop sign dup 0 equal [ drop 1 ] if ] [ power ] ) if ;   0 0 mypower print nl   "End " input
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.
#68000_Assembly
68000 Assembly
pushall: MOVEM.L D0-D7/A0-A6,-(SP) popall: MOVEM.L (SP)+,D0-D7/A0-A6 pushWord: MOVE.W <argument>,-(SP) popWord: MOVE.W (SP)+,<argument>
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.
#Action.21
Action!
INCLUDE "H6:REALMATH.ACT" INCLUDE "D2:CIRCLE.ACT" ;from the Action! Tool Kit   PROC YinYang(INT x BYTE y BYTE r) INT i,a,b,rr,r2,rr2,r5,rr5,y1,y2 REAL tmp1,tmp2   Circle(x,y,r,1)   rr=r*r r2=r/2 rr2=rr/4 Color=1 FOR i=0 TO r DO a=rr-i*i IntToReal(a,tmp1) Sqrt(tmp1,tmp2) a=RealToInt(tmp2)...
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...
#ALGOL_68
ALGOL 68
BEGIN MODE F = PROC(INT)INT; MODE Y = PROC(Y)F;   # compare python Y = lambda f: (lambda x: x(x)) (lambda y: f( lambda *args: y(y)(*args)))# PROC y = (PROC(F)F f)F: ( (Y x)F: x(x)) ( (Y z)F: f((INT arg )INT: z(z)( arg )));   PROC fib = (F f)F: (INT n)INT: CASE n IN n,n OUT f(n-1) + f(n-2) ESAC;   FOR i...
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...
#Applesoft_BASIC
Applesoft BASIC
100 S = 5 110 S2 = S ^ 2 : REM SQUARED 120 H = S2 / 2 : REM HALFWAY 130 S2 = S2 - 1 140 DX = 1 : REM INITIAL 150 DY = 0 : REM DIRECTION 160 N = S - 1 170 DIM A%(N, N)   200 FOR I = 0 TO H 210 A%(X, Y) = I 220 A%(N - X, N - Y) = S2 - I 230 X = X + DX 240 Y = Y + DY 250 IF Y = 0 THEN DY = DY + 1 : IF ...
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...
#FreeBASIC
FreeBASIC
function gcd(a as uinteger, b as uinteger) as uinteger if b = 0 then return a return gcd( b, a mod b ) end function   dim as uinteger i, j, k, Y(1 to 100)   Y(1) = 1 : Y(2) = 2: Y(3) = 3   for i = 4 to 100 k = 3 print i do k += 1 if gcd( k, Y(i-2) ) = 1 orelse gcd( k, Y(i-1) ) > 1 then continu...
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...
#Go
Go
package main   import ( "fmt" "log" "os/exec" )   func gcd(x, y int) int { for y != 0 { x, y = y, x%y } return x }   func yellowstone(n int) []int { m := make(map[int]bool) a := make([]int, n+1) for i := 1; i < 4; i++ { a[i] = i m[i] = true } min := 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.
#D
D
import std.stdio, std.exception, std.regex, std.algorithm, std.string, std.net.curl;   struct YahooResult { string url, title, content;   string toString() const { return "\nTitle: %s\nLink:  %s\nText:  %s" .format(title, url, content); } }   struct YahooSearch { private st...
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The ...
#Sidef
Sidef
func evalArithmeticExp(s) {   func evalExp(s) {   func operate(s, op) { s.split(op).map{|c| Number(c) }.reduce(op) }   func add(s) { operate(s.sub(/^\+/,'').sub(/\++/,'+'), '+') }   func subtract(s) { s.gsub!(/(\+-|-\+)/,'-')   i...
http://rosettacode.org/wiki/Zeckendorf_arithmetic
Zeckendorf arithmetic
This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation. The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions. Addition Like bin...
#Scala
Scala
  import scala.collection.mutable.ListBuffer   object ZeckendorfArithmetic extends App {     val elapsed: (=> Unit) => Long = f => { val s = System.currentTimeMillis   f   (System.currentTimeMillis - s) / 1000 } val add: (Z, Z) => Z = (z1, z2) => z1 + z2 val subtract: (Z, Z) => Z = (z1, z2) => z1 - ...
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 ...
#PicoLisp
PicoLisp
(de propdiv (N) (make (for I N (and (=0 (% N I)) (link I)) ) ) ) (de sum? (G L) (cond ((=0 G) T) ((= (car L) G) T) ((cdr L) (if (> (car L) G) (sum? G (cdr L)) (or (sum? (- G (car L)) (cdr L)) (sum? G (cdr L)) ) ) ) ) )...
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 ...
#Python
Python
from sympy import divisors   from sympy.combinatorics.subsets import Subset   def isZumkeller(n): d = divisors(n) s = sum(d) if not s % 2 and max(d) <= s/2: for x in range(1, 2**len(d)): if sum(Subset.unrank_binary(x, d).subset) == s/2: return True   return False     ...
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 ...
#F.23
F#
let () = let answer = 5I **(int (4I ** (int (3I ** 2)))) let sans = answer.ToString() printfn "Length = %d, digits %s ... %s" sans.Length (sans.Substring(0,20)) (sans.Substring(sans.Length-20)) ;; Length = 183231, 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 ...
#Factor
Factor
USING: formatting kernel math.functions math.parser sequences ; IN: rosettacode.bignums   : test-bignums ( -- ) 5 4 3 2 ^ ^ ^ number>string [ 20 head ] [ 20 tail* ] [ length ] tri "5^4^3^2 is %s...%s and has %d digits\n" printf ;
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: ################# ############# ################## ################ #################...
#PL.2FI
PL/I
zhang: procedure options (main); /* 8 July 2014 */   declare pic(10) bit(32) initial ( '00000000000000000000000000000000'b, '01111111110000000111111110000000'b, '01110001111000001111001111000000'b, '01110000111000001110000111000000'b, '01110001111000001110000000000000'b, '0...
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: ################# ############# ################## ################ #################...
#Python
Python
# -*- coding: utf-8 -*-   # Example from [http://nayefreza.wordpress.com/2013/05/11/zhang-suen-thinning-algorithm-java-implementation/ this blog post]. beforeTxt = '''\ 1100111 1100111 1100111 1100111 1100110 1100110 1100110 1100110 1100110 1100110 1100110 1100110 1111110 0000000\ '''   # Thanks to [http://www.network-...
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, ...
#Go
Go
package main   import "fmt"   func main() { for i := 0; i <= 20; i++ { fmt.Printf("%2d %7b\n", i, zeckendorf(i)) } }   func 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. ...
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...
#Ceylon
Ceylon
shared void run() { print("Open doors (naive): ``naive()`` Open doors (optimized): ``optimized()``");   }   shared {Integer*} naive(Integer count = 100) { variable value doors = [ for (_ in 1..count) closed ]; for (step in 1..count) { doors = [for (i->door in doors.indexed) let (index...
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,...
#F.23
F#
> Array.create 6 'A';; val it : char [] = [|'A'; 'A'; 'A'; 'A'; 'A'; 'A'|] > Array.init 8 (fun i -> i * 10) ;; val it : int [] = [|0; 10; 20; 30; 40; 50; 60; 70|] > let arr = [|0; 1; 2; 3; 4; 5; 6 |] ;; val arr : int [] = [|0; 1; 2; 3; 4; 5; 6|] > arr.[4];; val it : int = 4 > arr.[4] <- 65 ;; val it : unit = () > arr;;...
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...
#Python
Python
>>> z1 = 1.5 + 3j >>> z2 = 1.5 + 1.5j >>> z1 + z2 (3+4.5j) >>> z1 - z2 1.5j >>> z1 * z2 (-2.25+6.75j) >>> z1 / z2 (1.5+0.5j) >>> - z1 (-1.5-3j) >>> z1.conjugate() (1.5-3j) >>> abs(z1) 3.3541019662496847 >>> z1 ** z2 (-1.1024829553277784-0.38306415117199333j) >>> z1.real 1.5 >>> z1.imag 3.0 >>>
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...
#Scheme
Scheme
; simply prints all the perfect numbers (do ((candidate 2 (+ candidate 1))) ((>= candidate (expt 2 19))) (let ((sum (/ 1 candidate))) (do ((factor 2 (+ factor 1))) ((>= factor (sqrt candidate))) (if (= 0 (modulo candidate factor)) (set! sum (+ sum (/ 1 factor) (/ factor candidate))))) (if (= 1...
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geomet...
#XPL0
XPL0
include c:\cxpl\codesi; real A, A1, G; [Format(0, 16); A:= 1.0; G:= 1.0/sqrt(2.0); repeat A1:= (A+G)/2.0; G:= sqrt(A*G); A:= A1; RlOut(0, A); RlOut(0, G); RlOut(0, A-G); CrLf(0); until A=G; ]
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geomet...
#zkl
zkl
a:=1.0; g:=1.0/(2.0).sqrt(); while(not a.closeTo(g,1.0e-15)){ a1:=(a+g)/2.0; g=(a*g).sqrt(); a=a1; println(a," ",g," ",a-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, ...
#Kotlin
Kotlin
// version 1.0.6   fun main(args: Array<String>) { println("0 ^ 0 = ${Math.pow(0.0, 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, ...
#Lambdatalk
Lambdatalk
  {pow 0 0} -> 1 {exp 0 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 ...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; procedure Zebra is type Content is (Beer, Coffee, Milk, Tea, Water, Danish, English, German, Norwegian, Swedish, Blue, Green, Red, White, Yellow, Blend, BlueMaster, Dunhill, PallMall, Prince, Bird, Cat, Dog, Horse, Zebra); type Test is (Drink, Person, 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...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program xpathXml64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM...
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.
#Ada
Ada
with Glib; use Glib; with Cairo; use Cairo; with Cairo.Png; use Cairo.Png; with Cairo.Image_Surface; use Cairo.Image_Surface;   procedure YinYang is subtype Dub is Glib.Gdouble;   procedure Draw (C : Cairo_Context; x : Dub; y : Dub; r : Dub) is begin Arc (C, x, y, r + 1.0, 1.571, 7.854); Set_Source_Rg...
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...
#AppleScript
AppleScript
-- Y COMBINATOR ---------------------------------------------------------------   on |Y|(f) script on |λ|(y) script on |λ|(x) y's |λ|(y)'s |λ|(x) end |λ| end script   f's |λ|(result) end |λ| end script   ...
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...
#Arturo
Arturo
zigzag: function [n][ result: map 1..n 'x -> map 1..n => 0   x: 1, y: 1, v: 0, d: 1   while [v < n^2][ if? all? @[1 =< x x =< n 1 =< y y =< n][ set get result (y-1) (x-1) v x: x + d, y: y - d, v: v + 1 ] else[if? x > n [x: n, y: y + 2, d: neg d] el...
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...
#Haskell
Haskell
import Data.List (unfoldr)   yellowstone :: [Integer] yellowstone = 1 : 2 : 3 : unfoldr (Just . f) (2, 3, [4 ..]) where f :: (Integer, Integer, [Integer]) -> (Integer, (Integer, Integer, [Integer])) f (p2, p1, rest) = (next, (p1, next, rest_)) where (next, rest_) = select rest ...
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.
#Gambas
Gambas
Public Sub Form_Open() Dim hWebView As WebView   Me.Arrangement = Arrange.Fill Me.Maximized = True Me.Title = "Yahoo! search interface"   hWebView = New WebView(Me) hWebView.Expand = True hWebView.URL = "https://www.yahoo.com"   End
http://rosettacode.org/wiki/Yahoo!_search_interface
Yahoo! search interface
Create a class for searching Yahoo! results. It must implement a Next Page method, and read URL, Title and Content from results.
#Go
Go
package main   import ( "fmt" "golang.org/x/net/html" "io/ioutil" "net/http" "regexp" "strings" )   var ( expr = `<h3 class="title"><a class=.*?href="(.*?)".*?>(.*?)</a></h3>` + `.*?<div class="compText aAbs" ><p class=.*?>(.*?)</p></div>` rx = regexp.MustCompile(expr) )   type Y...
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The ...
#Standard_ML
Standard ML
(* AST *) datatype expression = Con of int (* constant *) | Add of expression * expression (* addition *) | Mul of expression * expression (* multiplication *) | Sub of expression * expression (* subtraction *) | Div of expression * expression (* division *)   (* Evaluator *) fun eval (Con x) = x | eva...
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The ...
#Tailspin
Tailspin
  def ops: ['+','-','*','/'];   data binaryExpression <{left: <node>, op: <?($ops <[<=$::raw>]>)>, right: <node>}> data node <binaryExpression|"1">   composer parseArithmetic (<WS>?) <addition|multiplication|term> (<WS>?) rule addition: {left:<addition|multiplication|term> (<WS>?) op:<'[+-]'> (<WS>?) right:<multipl...
http://rosettacode.org/wiki/Zeckendorf_arithmetic
Zeckendorf arithmetic
This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation. The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions. Addition Like bin...
#Tcl
Tcl
namespace eval zeckendorf { # Want to use alternate symbols? Change these variable zero "0" variable one "1"   # Base operations: increment and decrement proc zincr var { upvar 1 $var a namespace upvar [namespace current] zero 0 one 1 if {![regsub "$0$" $a $1$0 a]} {append a $1} while {[regsub "...
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 ...
#Racket
Racket
#lang racket   (require math/number-theory)   (define (zum? n) (let* ((set (divisors n)) (sum (apply + set))) (cond [(odd? sum) #f] [(odd? n) ; if n is odd use 'abundant odd number' optimization (let ((abundance (- sum (* n 2)))) (and (positive? abundance) (even? abundance)))] [e...
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 ...
#Raku
Raku
use ntheory:from<Perl5> <factor is_prime>;   sub zumkeller ($range) { $range.grep: -> $maybe { next if $maybe < 3 or $maybe.&is_prime; my @divisors = $maybe.&factor.combinations».reduce( &[×] ).unique.reverse; next unless [and] @divisors > 2, @divisors %% 2, (my $sum = @divisors.sum) %% 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 ...
#Forth
Forth
388c388 < CREATE big_string 256 CHARS ALLOT --- > CREATE big_string 500000 CHARS ALLOT 394c394 < big_string 256 CHARS + bighld ! ; \ Haydon p 67 --- > big_string 500000 CHARS + bighld ! ; \ Haydon p 67 403c403 < big_string 256 CHARS + \ One past end of string --- > big_string 500000 CHARS + \ One past en...
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 ...
#Fortran
Fortran
program bignum use fmzm implicit none type(im) :: a integer :: n   call fm_set(50) a = to_im(5)**(to_im(4)**(to_im(3)**to_im(2))) n = to_int(floor(log10(to_fm(a)))) call im_print(a / to_im(10)**(n - 19)) call im_print(mod(a, to_im(10)**20)) end program
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: ################# ############# ################## ################ #################...
#Racket
Racket
#lang racket (define (img-01string->vector str) (define lines (regexp-split "\n" str)) (define h (length lines)) (define w (if (zero? h) 0 (string-length (car lines)))) (define v (for*/vector #:length (* w h) ((l (in-list lines)) (p (in-string l))) (match p (#\0 0) (#\1 1) (#\# 1) (#...
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: ################# ############# ################## ################ #################...
#Raku
Raku
my $source = qq:to/EOD/; ................................ .#########.......########....... .###...####.....####..####...... .###....###.....###....###...... .###...####.....###............. .#########......###............. .###.####.......###....###...... .###..####..###.####..####.###.. .###...####.###..########..###....
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, ...
#Haskell
Haskell
import Data.Bits import Numeric   zeckendorf = map b $ filter ones [0..] where ones :: Int -> Bool ones x = 0 == x .&. (x `shiftR` 1) b x = showIntAtBase 2 ("01"!!) x ""   main = mapM_ putStrLn $ take 21 zeckendorf
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#Clarion
Clarion
  program   map end   MAX_DOOR_NUMBER equate(100) CRLF equate('<13,10>')   Doors byte,dim(MAX_DOOR_NUMBER) Pass byte DoorNumber byte DisplayString cstring(2000)   ResultWindow window('Result'),at(,,133,291),cen...
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,...
#Factor
Factor
{ 1 2 3 } { [ "The initial array: " write . ] [ [ 42 1 ] dip set-nth ] [ "Modified array: " write . ] [ "The element we modified: " write [ 1 ] dip nth . ] } cleave
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...
#R
R
z1 <- 1.5 + 3i z2 <- 1.5 + 1.5i print(z1 + z2) # 3+4.5i print(z1 - z2) # 0+1.5i print(z1 * z2) # -2.25+6.75i print(z1 / z2) # 1.5+0.5i print(-z1) # -1.5-3i print(Conj(z1)) # 1.5-3i print(abs(z1)) # 3.354102 ...
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...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "rational.s7i";   const func boolean: isPerfect (in integer: candidate) is func result var boolean: isPerfect is FALSE; local var integer: divisor is 0; var rational: sum is rational.value; begin sum := 1 / candidate; for divisor range 2 to sqrt(candidate) d...
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geomet...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 LET a=1: LET g=1/SQR 2 20 LET ta=a 30 LET a=(a+g)/2 40 LET g=SQR (ta*g) 50 IF a<ta THEN GO TO 20 60 PRINT a  
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, ...
#Liberty_BASIC
Liberty BASIC
  '******** print 0^0 '********  
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time, ...
#Locomotive_Basic
Locomotive Basic
print 0🠅0
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives ...
#ALGOL_68
ALGOL 68
BEGIN # attempt to solve Einstein's Riddle - the Zebra puzzle # INT unknown = 0, same = -1; INT english = 1, swede = 2, dane = 3, norwegian = 4, german = 5; INT dog = 1, birds = 2, cats = 3, horse = 4, zebra = 5; INT red = 1, green = 2, 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...
#AppleScript
AppleScript
set theXMLdata 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>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.
#ALGOL_68
ALGOL 68
INT scale x=2, scale y=1; CHAR black="#", white=".", clear=" ";   PROC print yin yang = (REAL radius)VOID:(   PROC in circle = (REAL centre x, centre y, radius, x, y)BOOL: (x-centre x)**2+(y-centre y)**2 <= radius**2;   PROC (REAL, REAL)BOOL in big circle = in circle(0, 0, radius, , ), in white semi cir...
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...
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program Ycombi.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */   /* Constantes */ .equ STDOUT, 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...
#ATS
ATS
  (* ****** ****** *) // #include "share/atspre_define.hats" // defines some names #include "share/atspre_staload.hats" // for targeting C #include "share/HATS/atspre_staload_libats_ML.hats" // for ... // (* ****** ****** *) // extern fun Zig_zag_matrix(n: int): void // (* ****** ****** *)   fun max(a: int, b: int): in...
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...
#J
J
  Until=: 2 :'u^:(0-:v)^:_' assert 44 -: >:Until(>&43) 32 NB. increment until exceeding 43 gcd=: +. coprime=: 1 = gcd prepare=:1 2 3"_ NB. start with the vector 1 2 3 condition=: 0 1 -: (coprime _2&{.) NB. trial coprime most recent 2, nay and yay append=: , NB. concatenate novel=: -.@e. NB. x is not a memb...
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...
#Java
Java
  import java.util.ArrayList; import java.util.List;   public class YellowstoneSequence {   public static void main(String[] args) { System.out.printf("First 30 values in the yellowstone sequence:%n%s%n", yellowstoneSequence(30)); }   private static List<Integer> yellowstoneSequence(int sequenceCou...
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.
#GUISS
GUISS
Start,Programs,Applications,Mozilla Firefox,Inputbox:address bar>www.yahoo.co.uk, Button:Go,Area:browser window,Inputbox:searchbox>elephants,Button:Search
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.
#Haskell
Haskell
import Network.HTTP import Text.Parsec   data YahooSearchItem = YahooSearchItem { itemUrl, itemTitle, itemContent :: String }   data YahooSearch = YahooSearch { searchQuery :: String, searchPage :: Int, searchItems :: [YahooSearchItem] }   -- URL for Yahoo! searches, without giving a page number yahooUr...
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The ...
#Tcl
Tcl
namespace import tcl::mathop::*   proc ast str { # produce abstract syntax tree for an expression regsub -all {[-+*/()]} $str { & } str ;# "tokenizer" s $str } proc s {args} { # parse "(a + b) * c + d" to "+ [* [+ a b] c] d" if {[llength $args] == 1} {set args [lindex $args 0]} if [regexp {[()]}...
http://rosettacode.org/wiki/Zeckendorf_arithmetic
Zeckendorf arithmetic
This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation. The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions. Addition Like bin...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Text   Module Module1   Class Zeckendorf Implements IComparable(Of Zeckendorf)   Private Shared ReadOnly dig As String() = {"00", "01", "10"} Private Shared ReadOnly dig1 As String() = {"", "1", "10"}   Private dVal As Integer = 0 Private dLen As Integer = 0   ...
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 ...
#REXX
REXX
/*REXX pgm finds & shows Zumkeller numbers: 1st N; 1st odd M; 1st odd V not ending in 5.*/ parse arg n m v . /*obtain optional arguments from the CL*/ if n=='' | n=="," then n= 220 /*Not specified? Then use the default.*/ if m=='' | m=="," then m= 40 ...
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 ...
#FreeBASIC
FreeBASIC
#Include once "gmp.bi" Dim Shared As Zstring * 100000000 outtext   Function Power(number As String,n As Uinteger) As String'automate precision #define dp 3321921 Dim As __mpf_struct _number,FloatAnswer Dim As Ulongint ln=Len(number)*(n)*4 If ln>dp Then ln=dp mpf_init2(@FloatAnswer,ln) mpf_init2...
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: ################# ############# ################## ################ #################...
#REXX
REXX
/*REXX program thins a NxM character grid using the Zhang-Suen thinning algorithm.*/ parse arg iFID .; if iFID=='' then iFID='ZHANG_SUEN.DAT' white=' '; @.=white /* [↓] read the input character grid. */ do row=1 while lines(iFID)\==0; _=linein(iFID) _=transl...
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, ...
#J
J
  fib=: 3 : 0 " 0 mp=. +/ .* {.{: mp/ mp~^:(I.|.#:y) 2 2$0 1 1 1x )   phi=: -:1+%:5   fi =: 3 : 'n - y<fib n=. 0>.(1=y)-~>.(phi^.%:5)+phi^.y'   fsum=: 3 : 0 z=. 0$r=. y while. 3<r do. m=. fib fi r z=. z,m r=. r-m end. z,r$~(*r)+.0=y )   Filter=: (#~`)(`:6)   ' '&~:Filter@:":@:#:@:#.@:((|. fib 2+i.8) e. fsum...
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...
#Clio
Clio
fn visit-doors doors step: if step > 100: doors else: [1:100] -> * fn index: if index % step: doors[(index - 1)] else: not doors[(index - 1)] -> visit-doors (step + 1)   [1:100] -> * n: false -> visit-doors 1 => doors [1:100] -> * (@eager) fn i: doors[(i - 1)] -> if = t...
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,...
#FBSL
FBSL
create MyArray 1 , 2 , 3 , 4 , 5 , 5 cells allot here constant MyArrayEnd   30 MyArray 7 cells + ! MyArray 7 cells + @ . \ 30   : .array MyArrayEnd MyArray do I @ . cell +loop ;
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...
#Racket
Racket
  #lang racket   (define a 3+4i) (define b 8+0i)   (+ a b)  ; addition (- a b)  ; subtraction (/ a b)  ; division (* a b)  ; multiplication (- a)  ; negation (/ 1 a)  ; reciprocal (conjugate a) ; conjugation  
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...
#Raku
Raku
my $a = 1 + i; my $b = pi + 1.25i;   .say for $a + $b, $a * $b, -$a, 1 / $a, $a.conj; .say for $a.abs, $a.sqrt, $a.re, $a.im;