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/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#SNOBOL4
SNOBOL4
A = "true" * "if-then-else" if A "true" :s(goTrue)f(goFalse) goTrue output = "A is TRUE" :(fi) goFalse output = "A is not TRUE" :(fi) fi   * "switch" switch A ("true" | "false") . switch :s($("case" switch))f(default) casetrue output = "A is TRUE" :(esac) casefalse output = "A is FALSE" :(esac) default output = "...
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 ...
#M2000_Interpreter
M2000 Interpreter
  Function ChineseRemainder(n(), a()) { Function mul_inv(a, b) { if b==1 then =1 : exit b0=b x1=1 : x0=0 while a>1 q=a div b t=b : b=a mod b: a=t t=x0: x0=x1-q*x0:x1=t end while if x1<0 then x1+=b0 =x1 } def p, i, prod=1, sum for i=0 to len(n())-1 {prod*=n(i)} for i=0 to len(a())-1 p=pro...
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 ...
#Maple
Maple
> chrem( [2, 3, 2], [3, 5, 7] ); 23  
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The s...
#Vlang
Vlang
fn chowla(n int) int { if n < 1 { panic("argument must be a positive integer") } mut sum := 0 for i := 2; i*i <= n; i++ { if n%i == 0 { j := n / i if i == j { sum += i } else { sum += i + j } } } ...
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The s...
#Wren
Wren
import "./fmt" for Fmt import "./math" for Int, Nums   var chowla = Fn.new { |n| (n > 1) ? Nums.sum(Int.properDivisors(n)) - 1 : 0 }   for (i in 1..37) Fmt.print("chowla($2d) = $d", i, chowla.call(i)) System.print() var count = 1 var limit = 1e7 var c = Int.primeSieve(limit, false) var power = 100 var i = 3 while (i < ...
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, a...
#Object_Pascal
Object Pascal
type MyClass = object variable: integer; constructor init; destructor done; procedure someMethod; end;   constructor MyClass.init; begin variable := 0; end;   procedure MyClass.someMethod; begin variable := 1; end;   var instance: MyClass; { as variab...
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. 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 Provide a function to find the closest two p...
#Prolog
Prolog
  % main predicate, find and print closest point do_find_closest_points(Points) :- points_closest(Points, points(point(X1,Y1),point(X2,Y2),Dist)), format('Point 1 : (~p, ~p)~n', [X1,Y1]), format('Point 1 : (~p, ~p)~n', [X2,Y2]), format('Distance: ~p~n', [Dist]).   % Find the distance between two points distance(poi...
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points
Circles of given radius through two points
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of circles with the point on thei...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Off[Solve::ratnz]; circs::invrad = "The radius is invalid."; circs::equpts = "The given points (`1`, `2`) are equivalent."; circs::dist = "The given points (`1`, `2`) and (`3`, `4`) are too far apart for \ radius `5`."; circs[_, _, 0.] := Message[circs::invrad]; circs[{p1x_, p1y_}, {p1x_, p1y_}, _] := Message[cir...
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo...
#Nim
Nim
import strformat   const ANIMALS: array[12, string] = ["Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", ...
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo...
#Pascal
Pascal
type animalCycle = (rat, ox, tiger, rabbit, dragon, snake, horse, goat, monkey, rooster, dog, pig); elementCycle = (wood, fire, earth, metal, water); aspectCycle = (yang, yin);   zodiac = record animal: animalCycle; element: elementCycle; aspect: aspectCycle; end;   function getZodiac(year: integer): z...
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#Factor
Factor
: print-exists? ( path -- ) [ write ": " write ] [ exists? "exists." "doesn't exist." ? print ] bi ;   { "input.txt" "/input.txt" "docs" "/docs" } [ print-exists? ] each
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#Forth
Forth
: .exists ( str len -- ) 2dup file-status nip 0= if ." exists" else ." does not exist" then type ; s" input.txt" .exists s" /input.txt" .exists s" docs" .exists s" /docs" .exists
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a ...
#JavaScript
JavaScript
<html>   <head>   <meta charset="UTF-8">   <title>Chaos Game</title>   </head>   <body>   <p> <canvas id="sierpinski" width=400 height=346></canvas> </p>   <p> <button onclick="chaosGame()">Click here to see a Sierpiński triangle</button> </p>   <script>   function chaosGame() { var canv = document.getElementById('...
http://rosettacode.org/wiki/Chat_server
Chat server
Task Write a server for a minimal text based chat. People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
#Phix
Phix
-- -- demo\rosetta\ChatServer.exw -- ======================== -- -- translation of (qchat) chatServ.exw -- -- Run this first, then ChatClient.exw, see also IRC_Gateway.exw -- -- Note that I've only got a 32-bit windows eulibnet.dll, but it should not -- be dificult to use a "real" libnet.dll/so, or something a little n...
http://rosettacode.org/wiki/Check_Machin-like_formulas
Check Machin-like formulas
Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing they equal 1: π 4 = ar...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Numerics   Public Class BigRat ' Big Rational Class constructed with BigIntegers Implements IComparable Public nu, de As BigInteger Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One), One = New BigRat(BigInteger.One, BigInteger.One) Sub New(bRat As BigRat) ...
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#Delphi
Delphi
program Project1;   {$APPTYPE CONSOLE}   uses SysUtils; var aChar:Char; aCode:Byte; uChar:WideChar; uCode:Word; begin aChar := Chr(97); Writeln(aChar); aCode := Ord(aChar); Writeln(aCode); uChar := WideChar(97); Writeln(uChar); uCode := Ord(uChar); Writeln(uCode);   Readln; end.
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square r...
#PARI.2FGP
PARI/GP
cholesky(M) = { my (L = matrix(#M,#M));   for (i = 1, #M, for (j = 1, i, s = sum (k = 1, j-1, L[i,k] * L[j,k]); L[i,j] = if (i == j, sqrt(M[i,i] - s), (M[i,j] - s) / L[j,j]) ) ); L }
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth, ...
#Ruby
Ruby
dates = [ ["May", 15], ["May", 16], ["May", 19], ["June", 17], ["June", 18], ["July", 14], ["July", 16], ["August", 14], ["August", 15], ["August", 17], ]   print dates.length, " remaining\n"   # the month cannot have a unique day uniqueMonths = dates.group_by { |m,d| d } ...
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a fe...
#MS_SmallBasic
MS SmallBasic
  ll=LDList.CreateFromValues("") LDList.Add(ll "Cars") LDList.Add(ll "Toys") LDList.Print(ll)  
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 ...
#Pure
Pure
comb m n = comb m (0..n-1) with comb 0 _ = [[]]; comb _ [] = []; comb m (x:xs) = [x:xs | xs = comb (m-1) xs] + comb m xs; end;   comb 3 5;
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#SNUSP
SNUSP
$==?\==zero=====!/==# \==non zero==/
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ChineseRemainder[{2, 3, 2}, {3, 5, 7}] 23
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 ...
#MATLAB_.2F_Octave
MATLAB / Octave
function f = chineseRemainder(r, m) s = prod(m) ./ m; [~, t] = gcd(s, m); f = s .* t * r';
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The s...
#XPL0
XPL0
func Chowla(N); \Return sum of divisors int N, Div, Sum, Quot; [Div:= 2; Sum:= 0; loop [Quot:= N/Div; if Quot < Div then quit; if Quot = Div and rem(0) = 0 then \N is a square [Sum:= Sum+Quot; quit]; if rem(0) = 0 then Sum:= Sum + Div + Quot; Div:= D...
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The s...
#zkl
zkl
fcn chowla(n){ if(n<1) throw(Exception.ValueError("Chowla function argument must be positive")); sum:=0; foreach i in ([2..n.toFloat().sqrt()]){ if(n%i == 0){ j:=n/i; if(i==j) sum+=i; else sum+=i+j; } } sum }   fcn chowlaSieve(limit){ // True denotes composite, false deno...
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, a...
#Objective-C
Objective-C
// There are no class variables, so static variables are used. static int myClassVariable = 0;   @interface MyClass : NSObject { int variable; // instance variable }   - (int)variable; // Typical accessor - you should use the same name as the variable   @end
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. 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 Provide a function to find the closest two p...
#PureBasic
PureBasic
Procedure.d bruteForceClosestPair(Array P.coordinate(1)) Protected N=ArraySize(P()), i, j Protected mindistance.f=Infinity(), t.d Shared a, b If N<2 a=0: b=0 Else For i=0 To N-1 For j=i+1 To N t=Pow(Pow(P(i)\x-P(j)\x,2)+Pow(P(i)\y-P(j)\y,2),0.5) If mindistance>t mindist...
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points
Circles of given radius through two points
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of circles with the point on thei...
#Maxima
Maxima
/* define helper function */ vabs(a):= sqrt(a.a); realp(e):=freeof(%i, e);   /* get a general solution */ sol: block( [p1: [x1, y1], p2: [x2, y2], c: [x0, y0], eq], local(r), eq: [vabs(p1-c) = r, vabs(p2-c) = r], load(to_poly_solve), assume(r>0), args(to_poly_solve(eq, c, use_grobner = true)))$   /* use ge...
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo...
#Perl
Perl
sub zodiac { my $year = shift; my @animals = qw/Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog Pig/; my @elements = qw/Wood Fire Earth Metal Water/; my @terrestrial_han = qw/子 丑 寅 卯 辰 巳 午 未 申 酉 戌 亥/; my @terrestrial_pinyin = qw/zĭ chŏu yín măo chén sì wŭ wèi shēn yŏu xū hài/; my @celestial_h...
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#Fortran
Fortran
LOGICAL :: file_exists INQUIRE(FILE="input.txt", EXIST=file_exists) ! file_exists will be TRUE if the file ! exists and FALSE otherwise INQUIRE(FILE="/input.txt", EXIST=file_exists)
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   ' Enable FileExists() function to be used #include "file.bi"   ' Use Win32 function to check if directory exists on Windows 10 Declare Function GetFileAttributes Lib "kernel32.dll" Alias "GetFileAttributesA" _ (ByVal lpFileName As ZString Ptr) As ULong   Const InvalidFileAttributes As ULong = -1UL C...
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a ...
#Julia
Julia
using Luxor   function chaos() width = 1000 height = 1000 Drawing(width, height, "./chaos.png") t = Turtle(0, 0, true, 0, (0., 0., 0.)) x = rand(1:width) y = rand(1:height)   for l in 1:30_000 v = rand(1:3) if v == 1 x /= 2 y /= 2 elseif v == ...
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a ...
#Kotlin
Kotlin
//Version 1.1.51   import java.awt.* import java.util.Stack import java.util.Random import javax.swing.JPanel import javax.swing.JFrame import javax.swing.Timer import javax.swing.SwingUtilities   class ChaosGame : JPanel() {   class ColoredPoint(x: Int, y: Int, val colorIndex: Int) : Point(x, y)   val stack = ...
http://rosettacode.org/wiki/Chat_server
Chat server
Task Write a server for a minimal text based chat. People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
#PicoLisp
PicoLisp
#!/usr/bin/picolisp /usr/lib/picolisp/lib.l   (de chat Lst (out *Sock (mapc prin Lst) (prinl) ) )   (setq *Port (port 4004))   (loop (setq *Sock (listen *Port)) (NIL (fork) (close *Port)) (close *Sock) )   (out *Sock (prin "Please enter your name: ") (flush) ) (in *Sock (setq *Name (line T...
http://rosettacode.org/wiki/Check_Machin-like_formulas
Check Machin-like formulas
Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing they equal 1: π 4 = ar...
#Wren
Wren
import "/big" for BigRat import "/fmt" for Fmt   /** represents a term of the form: c * atan(n / d) */ class Term { construct new(c, n, d) { _c = c _n = n _d = d }   c { _c } n { _n } d { _d }   toString { var a = "atan(%(n)/%(d))" return ((_c == 1) ? " +...
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#Dyalect
Dyalect
print('a'.Order()) print(Char(97))
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#DWScript
DWScript
PrintLn(Ord('a')); PrintLn(Chr(97));
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square r...
#Pascal
Pascal
program CholeskyApp;   type D2Array = array of array of double;   function cholesky(const A: D2Array): D2Array; var i, j, k: integer; s: double; begin setlength(Result, length(A), length(A)); for i := low(Result) to high(Result) do for j := 0 to i do begin s := 0; for k := 0 to j - 1 do ...
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth, ...
#Rust
Rust
  // This version is based on the Go version on Rosettacode   #[derive(PartialEq, Debug, Copy, Clone)] enum Month { May, June, July, August, }   #[derive(PartialEq, Debug, Copy, Clone)] struct Birthday { month: Month, day: u8, }   impl Birthday { fn month_unique_in(&self, birthdays: &[Birthd...
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth, ...
#Scala
Scala
import java.time.format.DateTimeFormatter import java.time.{LocalDate, Month}   object Cheryl { def main(args: Array[String]): Unit = { val choices = List( LocalDate.of(2019, Month.MAY, 15), LocalDate.of(2019, Month.MAY, 16), LocalDate.of(2019, Month.MAY, 19),   LocalDate.of(2019, Month.JU...
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a fe...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   myVals = [ 'zero', 'one', 'two', 'three', 'four', 'five' ] mySet = Set mySet = HashSet()   loop val over myVals mySet.add(val) end val   loop val over mySet say val end val   return  
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 ...
#PureBasic
PureBasic
Procedure.s Combinations(amount, choose) NewList comb.s() ; all possible combinations with {amount} Bits For a = 0 To 1 << amount count = 0 ; count set bits For x = 0 To amount If (1 << x)&a count + 1 EndIf Next ; if set bits are equal to combination length ; we generat...
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#Sparkling
Sparkling
var odd = 13; if odd % 2 != 0 { print("odd"); }
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 ...
#Modula-2
Modula-2
MODULE CRT; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   PROCEDURE WriteInt(n : INTEGER); VAR buf : ARRAY[0..15] OF CHAR; BEGIN FormatString("%i", buf, n); WriteString(buf) END WriteInt;   PROCEDURE MulInv(a,b : INTEGER) : INTEGER; VAR b0,x0,x1,q,amb,xqx : INTE...
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, a...
#OCaml
OCaml
class my_class = object (self) val mutable variable = 0 method some_method = variable <- 1 end
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, a...
#Oforth
Oforth
Object Class new: MyClass(att) MyClass method: initialize(v) v := att ;
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. 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 Provide a function to find the closest two p...
#Python
Python
""" Compute nearest pair of points using two algorithms   First algorithm is 'brute force' comparison of every possible pair. Second, 'divide and conquer', is based on: www.cs.iupui.edu/~xkzou/teaching/CS580/Divide-and-conquer-closestPair.ppt """   from random import randint, randrange from operator import i...
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points
Circles of given radius through two points
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of circles with the point on thei...
#.D0.9C.D0.9A-61.2F52
МК-61/52
П0 С/П П1 С/П П2 С/П П3 С/П П4 ИП2 ИП0 - x^2 ИП3 ИП1 - x^2 + КвКор П5 ИП0 ИП2 + 2 / П6 ИП1 ИП3 + 2 / П7 ИП4 x^2 ИП5 2 / x^2 - КвКор ИП5 / П8 ИП6 ИП1 ИП3 - ИП8 * П9 + ПA ИП6 ИП9 - ПC ИП7 ИП2 ИП0 - ИП8 * П9 + ПB ИП7 ИП9 - ПD ИП5 x#0 97 8 4 ИНВ С/П ИП4 2 * ИП5 - ПE x#0 97 ИПB ИПA 8 5 ИНВ С/П ИПE x>=0 97 8 3 ИНВ С/П ИПD ИП...
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo...
#Phix
Phix
with javascript_semantics constant animals = {"Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig"}, elements = {"Wood","Fire","Earth","Metal","Water"}, yinyang = {"yang","yin"}, years = {1935,1938,1968,1972,1976,2018} for i=1 to length(years) do in...
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#Frink
Frink
  checkFile[filename] := { file = newJava["java.io.File", [filename]] if file.exists[] and file.isFile[] println["$filename is a file"] else println["$filename is not a file"] }   checkDir[filename] := { file = newJava["java.io.File", [filename]] if file.exists[] and file.isDirectory[] ...
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#Gambas
Gambas
Public Sub Main()   If Exist(User.Home &/ "input.txt") Then Print "'input.txt' does exist in the Home folder" If Not Exist("/input.txt") Then Print "'input.txt' does NOT exist in Root" 'Not messing With my Root files   If Exist(User.home &/ "docs/") Then Print "The folder '~/docs' does exist" If Not Exis...
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a ...
#Logo
Logo
to chaosgame :sidelength :iterations make "width :sidelength make "height (:sidelength/2 * sqrt 3) make "x (random :width) make "y (random :height) repeat :iterations [ make "vertex (random 3) if :vertex = 0 [ make "x (:x / 2) make "y (:y / 2) setp...
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a ...
#Lua
Lua
  math.randomseed( os.time() ) colors, orig = { { 255, 0, 0 }, { 0, 255, 0 }, { 0, 0, 255 } }, {}   function love.load() wid, hei = love.graphics.getWidth(), love.graphics.getHeight()   orig[1] = { wid / 2, 3 } orig[2] = { 3, hei - 3 } orig[3] = { wid - 3, hei - 3 } local w, h = math.random( 10, 40 ...
http://rosettacode.org/wiki/Chat_server
Chat server
Task Write a server for a minimal text based chat. People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
#Prolog
Prolog
:- initialization chat_server(5000).   chat_server(Port) :- tcp_socket(Socket), tcp_bind(Socket, Port), tcp_listen(Socket, 5), tcp_open_socket(Socket, AcceptFd, _), dispatch(AcceptFd).   dispatch(AcceptFd) :- tcp_accept(AcceptFd, Socket, _), thread_create(process_client(Soc...
http://rosettacode.org/wiki/Check_Machin-like_formulas
Check Machin-like formulas
Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing they equal 1: π 4 = ar...
#XPL0
XPL0
code ChOut=8, Text=12; \intrinsic routines int Number(18); \numbers from equations def LF=$0A; \ASCII line feed (end-of-line character)   func Parse(S); \Convert numbers in string S to binary in Number array char S; int I, Neg;   proc GetNum; \Get number from string S i...
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#E
E
? 'a'.asInteger() # value: 97   ? <import:java.lang.makeCharacter>.asChar(97) # value: 'a'
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#EasyLang
EasyLang
print strcode "a" print strchar 97
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square r...
#Perl
Perl
sub cholesky { my $matrix = shift; my $chol = [ map { [(0) x @$matrix ] } @$matrix ]; for my $row (0..@$matrix-1) { for my $col (0..$row) { my $x = $$matrix[$row][$col]; $x -= $$chol[$row][$_]*$$chol[$col][$_] for 0..$col; $$chol[$row][$col] = $row == $col ? sqrt $x : $x/$$chol[$col][...
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth, ...
#Sidef
Sidef
func f(day, month) { Date.parse("#{day} #{month}", "%d %B") }   var dates = [ f(15, "May"), f(16, "May"), f(19, "May"), f(17, "June"), f(18, "June"), f(14, "July"), f(16, "July"), f(14, "August"), f(15, "August"), f(17, "August") ]   var filtered = dates.grep { dates.grep...
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a fe...
#Nim
Nim
var a = [1,2,3,4,5,6,7,8,9] var b: array[128, int] b[9] = 10 b[0..8] = a var c: array['a'..'d', float] = [1.0, 1.1, 1.2, 1.3] c['b'] = 10000
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 ...
#Pyret
Pyret
    fun combos<a>(lst :: List<a>, size :: Number) -> List<List<a>>: # return all subsets of lst of a certain size, # maintaining the original ordering of the list   # Let's handle a bunch of degenerate cases up front # to be defensive... if lst.length() < size: # return an empty list if size is too big ...
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#SQL
SQL
CASE WHEN a THEN b ELSE c END   DECLARE @n INT SET @n=124 print CASE WHEN @n=123 THEN 'equal' ELSE 'not equal' END   --If/ElseIf expression SET @n=5 print CASE WHEN @n=3 THEN 'Three' WHEN @n=4 THEN 'Four' ELSE 'Other' END
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 ...
#Nim
Nim
proc mulInv(a0, b0: int): int = var (a, b, x0) = (a0, b0, 0) result = 1 if b == 1: return while a > 1: let q = a div b a = a mod b swap a, b result = result - q * x0 swap x0, result if result < 0: result += b0   proc chineseRemainder[T](n, a: T): int = var prod = 1 var sum = 0 for x ...
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 ...
#OCaml
OCaml
  exception Modular_inverse let inverse_mod a = function | 1 -> 1 | b -> let rec inner a b x0 x1 = if a <= 1 then x1 else if b = 0 then raise Modular_inverse else inner b (a mod b) (x1 - (a / b) * x0) x0 in let x = inner a b 0 1 in if x < 0 then x + b else x   let...
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, a...
#Ol
Ol
p = .point~new c = .circle~new   p~print c~print   ::class point ::method init expose x y use strict arg x = 0, y = 0 -- defaults to 0 for any non-specified coordinates   ::attribute x ::attribute y   ::method print expose x y say "A point at location ("||x","y")"   ::class circle subclass point ::method init...
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. 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 Provide a function to find the closest two p...
#R
R
closest_pair_brute <-function(x,y,plotxy=F) { xy = cbind(x,y) cp = bruteforce(xy) cat("\n\nShortest path found = \n From:\t\t(",cp[1],',',cp[2],")\n To:\t\t(",cp[3],',',cp[4],")\n Distance:\t",cp[5],"\n\n",sep="") if(plotxy) { plot(x,y,pch=19,col='black',main="Closest Pair", asp=1) poin...
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points
Circles of given radius through two points
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of circles with the point on thei...
#Modula-2
Modula-2
MODULE Circles; FROM EXCEPTIONS IMPORT AllocateSource,ExceptionSource,GetMessage,RAISE; FROM FormatString IMPORT FormatString; FROM LongMath IMPORT sqrt; FROM LongStr IMPORT RealToStr; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   VAR TextWinExSrc : ExceptionSource;   TYPE Point = RECORD x,y : LO...
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo...
#Picat
Picat
  animals({"Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"}).   elements({"Wood", "Fire", "Earth", "Metal", "Water"}).   animal_chars({"子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"}).   element_chars({{"甲", "丙", "戊", "庚", "壬"}, {"乙", "丁", "己", "辛", "癸"}}).   years...
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#GAP
GAP
IsExistingFile("input.txt"); IsDirectoryPath("docs"); IsExistingFile("/input.txt"); IsDirectoryPath("/docs");
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#Genie
Genie
[indent=4] /* Check file exists, in Genie valac --pkg=gio-2.0 checkFile.gs */   init Intl.setlocale()   files:array of string[] = {"input.txt", "docs", Path.DIR_SEPARATOR_S + "input.txt", Path.DIR_SEPARATOR_S + "docs", "`Abdu'l-Bahá.txt"} for f:string in files var file = File.new_for_path(...
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a ...
#Maple
Maple
chaosGame := proc(numPoints) local points, i; randomize(); use geometry in RegularPolygon(triSideways, 3, point(cent, [0, 0]), 1); rotation(tri, triSideways, Pi/2, counterclockwise); randpoint(currentP, -1/2*sqrt(3)..1/2*sqrt(3), -1/2..1/2); points := [coordinates(currentP)]; for i to numPoints do midpoint(mi...
http://rosettacode.org/wiki/Chat_server
Chat server
Task Write a server for a minimal text based chat. People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
#Python
Python
#!/usr/bin/env python   import socket import thread import time   HOST = "" PORT = 4004   def accept(conn): """ Call the inner func in a thread so as not to block. Wait for a name to be entered from the given connection. Once a name is entered, set the connection to non-blocking and add the user to ...
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#Eiffel
Eiffel
  class APPLICATION inherit ARGUMENTS create make   feature {NONE} -- Initialization   make -- Run application. local c8: CHARACTER_8 c32: CHARACTER_32 do c8 := '%/97/' -- using code value notation c8 := '%/0x61/' -- same as above, but using hexadecimal literal print(c8.natural_32_code) --...
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square r...
#Phix
Phix
with javascript_semantics function cholesky(sequence matrix) integer l = length(matrix) sequence chol = repeat(repeat(0,l),l) for row=1 to l do for col=1 to row do atom x = matrix[row][col] for i=1 to col do x -= chol[row][i] * chol[col][i] end for...
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth, ...
#Swift
Swift
struct MonthDay: CustomStringConvertible { static let months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]   var month: Int var day: Int   var description: String { "\(MonthDay.months[month - 1]) \(day)" }   private fun...
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth, ...
#VBA
VBA
Private Sub exclude_unique_days(w As Collection) Dim number_of_dates(31) As Integer Dim months_to_exclude As New Collection For Each v In w number_of_dates(v(1)) = number_of_dates(v(1)) + 1 Next v For i = w.Count To 1 Step -1 If number_of_dates(w(i)(1)) = 1 Then months_to...
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a fe...
#Objeck
Objeck
  values := IntVector->New(); values->AddBack(7); values->AddBack(3); values->AddBack(10);  
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 ...
#Python
Python
>>> from itertools import combinations >>> list(combinations(range(5),3)) [(0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 2, 3), (0, 2, 4), (0, 3, 4), (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#SSEM
SSEM
01010000000000100000000000000000 -10 to c 00000000000000110000000000000000 Test 01110000000000000000000000000000 14 to CI
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#Stata
Stata
clear set obs 4 gen a = cond(mod(_n, 2)==1, "A", "B") list, noobs noheader   +---+ | A | | B | | A | | B | +---+
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 ...
#PARI.2FGP
PARI/GP
chivec(residues, moduli)={ my(m=Mod(0,1)); for(i=1,#residues, m=chinese(Mod(residues[i],moduli[i]),m) ); lift(m) }; chivec([2,3,2], [3,5,7])
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 ...
#Pascal
Pascal
  // Rosetta Code task "Chinese remainder theorem". program ChineseRemThm; uses SysUtils; type TIntArray = array of integer;   // Defining EXTRA adds optional explanatory code {$DEFINE EXTRA}   // Return (if possible) a residue res_out that satifies // res_out = res1 modulo mod1, res_out = res2 modulo mod2. // Retur...
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, a...
#ooRexx
ooRexx
p = .point~new c = .circle~new   p~print c~print   ::class point ::method init expose x y use strict arg x = 0, y = 0 -- defaults to 0 for any non-specified coordinates   ::attribute x ::attribute y   ::method print expose x y say "A point at location ("||x","y")"   ::class circle subclass point ::method init...
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, a...
#OxygenBasic
OxygenBasic
    Class MyObject   static int count 'statics are private   int a,b,c bstring s   method constructor(int pa,pb,pc) s="constructed" a=pa : b=pb : c=pc count++ end method   method destructor() del s end method   method sum() as int return a+b+c end method   end class   new MyObject v(2,4,6)   print "Sum: " v.s...
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. 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 Provide a function to find the closest two p...
#Racket
Racket
  #lang racket (define (dist z0 z1) (magnitude (- z1 z0))) (define (dist* zs) (apply dist zs))   (define (closest-pair zs) (if (< (length zs) 2) -inf.0 (first (sort (for/list ([z0 zs]) (list z0 (argmin (λ(z) (if (= z z0) +inf.0 (dist z z0))) zs))) < #:key dist*))))   (d...
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points
Circles of given radius through two points
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of circles with the point on thei...
#Nim
Nim
import math   type Point = tuple[x, y: float] Circle = tuple[x, y, r: float]   proc circles(p1, p2: Point, r: float): tuple[c1, c2: Circle] = if r == 0: raise newException(ValueError, "radius of zero") if p1 == p2: raise newException(ValueError, "coincident points gives infinite number of Circles")   ...
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo...
#PowerShell
PowerShell
  function Get-ChineseZodiac { [CmdletBinding()] [OutputType([PSCustomObject])] Param ( [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [ValidateRange(1,9999)] [int]...
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#Go
Go
package main   import ( "fmt" "os" )   func printStat(p string) { switch i, err := os.Stat(p); { case err != nil: fmt.Println(err) case i.IsDir(): fmt.Println(p, "is a directory") default: fmt.Println(p, "is a file") } }   func main() { printStat("input.txt") ...
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#Groovy
Groovy
println new File('input.txt').exists() println new File('/input.txt').exists() println new File('docs').exists() println new File('/docs').exists()
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
points = 5000; a = {0, 0}; b = {1, 0}; c = {0.5, 1}; d = {.7, .3}; S = {}; For[i = 1, i < points, i++, t = RandomInteger[2]; If[t == 0, d = Mean[{a, d}], If[t == 1, d = Mean[{b, d}], d = Mean[{c, d}]]]; AppendTo[S, d]] Graphics[Point[S]]
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a ...
#Nim
Nim
import random   import rapid/gfx   var window = initRWindow() .title("Rosetta Code - Chaos Game") .open() surface = window.openGfx() sierpinski = window.newRCanvas() points: array[3, Vec2[float]]   for i in 0..<3: points[i] = vec2(cos(PI * 2 / 3 * i.float), sin(PI * 2 / 3 * i.float)) * 300   var point...
http://rosettacode.org/wiki/Chat_server
Chat server
Task Write a server for a minimal text based chat. People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
#R
R
  chat_loop <- function(server, sockets, delay = 0.5) { repeat { Sys.sleep(delay) # Saves CPU resources   ## Exhausts queue each iteration while (in_queue(server)) sockets <- new_socket_entry(server, sockets)   ## Update which sockets have sent messages sockets <-...
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#Elena
Elena
import extensions;   public program() { var ch := $97;   console.printLine:ch; console.printLine(ch.toInt()) }
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square r...
#PicoLisp
PicoLisp
(scl 9) (load "@lib/math.l")   (de cholesky (A) (let L (mapcar '(() (need (length A) 0)) A) (for (I . R) A (for J I (let S (get R J) (for K (inc J) (dec 'S (*/ (get L I K) (get L J K) 1.0)) ) (set (nth L I J) (if (= I J) ...
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth, ...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Structure MonDay Dim month As String Dim day As Integer   Sub New(m As String, d As Integer) month = m day = d End Sub   Public Overrides Function ToString() As String Return String.Format("({0}, {1})", month, day) ...
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a fe...
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   void show_collection(id coll) { for ( id el in coll ) { if ( [coll isKindOfClass: [NSCountedSet class]] ) { NSLog(@"%@ appears %lu times", el, [coll countForObject: el]); } else if ( [coll isKindOfClass: [NSDictionary class]] ) { NSLog(@"%@ -> %@", el, coll[el...
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 ...
#Quackery
Quackery
[ 0 swap [ dup 0 != while dup 1 & if [ dip 1+ ] 1 >> again ] drop ] is bits ( n --> n )   [ [] unrot bit times [ i bits over = if [ dip [ i join ] ] ] drop ] is combnums ( n n --> [ )   [ [] 0...
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#Swahili
Swahili
kama (kweli) { andika("statement") } au (kweli /* condition */) { andika("statement") } au (kweli /* condition */) { andika("statement") } sivyo { andika("statement") }
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 ...
#Perl
Perl
use ntheory qw/chinese/; say chinese([2,3], [3,5], [2,7]);
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 ...
#Phix
Phix
function mul_inv(integer a, n) if n<0 then n = -n end if if a<0 then a = n - mod(-a,n) end if integer t = 0, nt = 1, r = n, nr = a; while nr!=0 do integer q = floor(r/nr) {t, nt} = {nt, t-q*nt} {r, nr} = {nr, r-q*nr} end while if r>1 then return "a is not...