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/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...
#Oz
Oz
declare class Something feat name %% immutable, public attribute (called a "feature") attr count %% mutable, private attribute   %% public method which is used as an initializer meth init(N) self.name = N count := 0 end   %% public method meth increas...
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...
#Raku
Raku
sub MAIN ($N = 5000) { my @points = (^$N).map: { [rand × 20 - 10, rand × 20 - 10] } printf "%.8f between (%.5f, %.5f), (%.5f, %.5f)\n", $_[2], @($_[1]), @($_[0]) for closest-pair(@points), closest-pair-simple(@points) }   sub dist-squared(@a, @b) { (@a[0] - @b[0])² + (@a[1] - @b[1])² }   sub closest-pai...
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...
#OCaml
OCaml
  (* Task : Circles of given radius through two points *)   (* Types to make code even more readable *) type point = float * float type radius = float type circle = Circle of radius * point type circ_output = NoSolution | OneSolution of circle | TwoSolutions of circle * circle | InfiniteSolutions ;;   ...
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...
#Prolog
Prolog
  :- initialization(main).   animals(['Rat', 'Ox', 'Tiger', 'Rabbit', 'Dragon', 'Snake', 'Horse', 'Goat', 'Monkey', 'Rooster', 'Dog', 'Pig']).   elements(['Wood', 'Fire', 'Earth', 'Metal', 'Water']).   animal_chars(['子','丑','寅','卯','辰','巳','午','未','申','酉','戌','亥']).   element_chars([['甲', '丙', '戊', '庚', '壬'], ['乙', '丁'...
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 ...
#Haskell
Haskell
import System.Directory (doesFileExist, doesDirectoryExist)   check :: (FilePath -> IO Bool) -> FilePath -> IO () check p s = do result <- p s putStrLn $ s ++ if result then " does exist" else " does not exist"   main :: IO () main = do check doesFileExist "input.txt" check doesDirectoryExis...
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 ...
#PARI.2FGP
PARI/GP
  \\ Chaos Game (Sierpinski triangle) 2/15/17 aev pChaosGameS3(size,lim)={ my(sz1=size\2,sz2=sz1*sqrt(3),M=matrix(size,size),x,y,xf,yf,v); x=random(size); y=random(sz2); for(i=1,lim, v=random(3); if(v==0, x/=2; y/=2;); if(v==1, x=sz1+(sz1-x)/2; y=sz2-(sz2-y)/2;); if(v==2, x=size-(size-x)/2; y/=2;); xf=floor(x)...
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.
#Racket
Racket
  #lang racket   (define outs (list (current-output-port))) (define ((tell-all who o) line) (for ([c outs] #:unless (eq? o c)) (displayln (~a who ": " line) c)))   (define ((client i o)) (define nick (begin (display "Nick: " o) (read-line i))) (define tell (tell-all nick o)) (let loop ([line "(joined)"]) (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...
#Elixir
Elixir
iex(1)> code = ?a 97 iex(2)> to_string([code]) "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...
#Emacs_Lisp
Emacs Lisp
(string-to-char "a") ;=> 97 (format "%c" 97) ;=> "a"
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...
#PL.2FI
PL/I
(subscriptrange): decompose: procedure options (main); /* 31 October 2013 */ declare a(*,*) float controlled;   allocate a(3,3) initial (25, 15, -5, 15, 18, 0, -5, 0, 11); put skip list ('Original matrix:'); put edit (a) (skip, 3 f(4));   cal...
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, ...
#Vlang
Vlang
import time   struct Birthday { month int day int }   fn (b Birthday) str() string { return "${time.long_months[b.month-1]} $b.day" }   fn (b Birthday) month_uniquie_in(bds []Birthday) bool { mut count := 0 for bd in bds { if bd.month == b.month { count++ } } if count ...
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, ...
#Wren
Wren
var Months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]   class Birthday { construct new(month, day) { _month = month _day = day }   month { _month } day { _day }   toString { "%(Months[_month...
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...
#OCaml
OCaml
[1; 2; 3; 4; 5]
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 ...
#R
R
print(combn(0:4, 3))
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 ...
#Tailspin
Tailspin
  templates foo when <=0> do 'zero' -> !OUT::write when <..0> do 'negative ' -> !OUT::write -$ -> # when <?($ mod 2 <=0>)> do 'even' -> !OUT::write otherwise 'odd' -> !OUT::write end foo  
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 ...
#Tcl
Tcl
if {$foo == 3} { puts "foo is three" } elseif {$foo == 4} { puts "foo is four" } else { puts "foo is neither three nor four" }
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 ...
#PicoLisp
PicoLisp
(de modinv (A B) (let (B0 B X0 0 X1 1 Q 0 T1 0) (while (< 1 A) (setq Q (/ A B) T1 B B (% A B) A T1 T1 X0 X0 (- X1 (* Q X0)) X1 T1 ) ) (if (lt0 X1) (+ X1 B0) X1) ) )   (de chinrem (N A) (let P (apply * N) ...
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 ...
#Prolog
Prolog
  product(A, B, C) :- C is A*B.   pair(X, Y, X-Y).   egcd(_, 0, 1, 0) :- !. egcd(A, B, X, Y) :- divmod(A, B, Q, R), egcd(B, R, S, X), Y is S - Q*X.   modinv(A, B, X) :- egcd(A, B, X, Y), A*X + B*Y =:= 1.   crt_fold(A, M, P, R0, R1) :- % system of equations of (x = a) (mod m); p = M/m modinv(P, M...
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...
#Pascal
Pascal
{ # a class is a package (i.e. a namespace) with methods in it package MyClass;   # a constructor is a function that returns a blessed reference sub new { my $class = shift; bless {variable => 0}, $class; # the instance object is a hashref in disguise. # (it can be a ...
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...
#Perl
Perl
{ # a class is a package (i.e. a namespace) with methods in it package MyClass;   # a constructor is a function that returns a blessed reference sub new { my $class = shift; bless {variable => 0}, $class; # the instance object is a hashref in disguise. # (it can be a ...
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...
#REXX
REXX
/*REXX program solves the closest pair of points problem (in two dimensions). */ parse arg N LO HI seed . /*obtain optional arguments from the CL*/ if N=='' | N=="," then N= 100 /*Not specified? Then use the default.*/ if LO=='' | LO=="," then LO= 0 ...
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...
#Oforth
Oforth
: circleCenter(x1, y1, x2, y2, r) | d xmid ymid r1 md | x2 x1 - sq y2 y1 - sq + sqrt -> d x1 x2 + 2 / -> xmid y1 y2 + 2 / -> ymid 2 r * -> r1   d 0.0 == ifTrue: [ "Infinite number of circles" . return ] d r1 == ifTrue: [ System.Out "One circle: (" << xmid << ", " << ymid << ")" << cr return ] ...
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...
#PureBasic
PureBasic
EnableExplicit #BASE=4 #SPC=Chr(32)   Procedure.s ChineseZodiac(n.i) Define cycle_year.i=n-#BASE, stem_number.i = cycle_year%10+1, element_number.i = Round(stem_number/2,#PB_Round_Nearest), branch_number.i = cycle_year%12+1, aspect_number.i = cycle_year%2+1, index.i ...
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 ...
#hexiscript
hexiscript
println "File \"input.txt\"? " + (exists "input.txt") println "Dir \"docs\"? " + (exists "docs/") println "File \"/input.txt\"? " + (exists "/input.txt") println "Dir \"/docs\"? " + (exists "/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 ...
#HicEst
HicEst
OPEN(FIle= 'input.txt', OLD, IOStat=ios, ERror=99) OPEN(FIle='C:\input.txt', OLD, IOStat=ios, ERror=99) ! ... 99 WRITE(Messagebox='!') 'File does not exist. Error message ', ios
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 ...
#Pascal
Pascal
  program ChaosGame;   // FPC 3.0.2 uses Graph, windows, math;   // Return a point on a circle defined by angle and the circles radius // Angle 0 = Radius points to the left // Angle 90 = Radius points upwards Function PointOfCircle(Angle: SmallInt; Radius: integer): TPoint; var Ia: Double; begin Ia:=DegToRad(-Angl...
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.
#Raku
Raku
react { my %connections;   whenever IO::Socket::Async.listen('localhost', 4004) -> $conn { my $name;   $conn.print: "Please enter your name: ";   whenever $conn.Supply.lines -> $message { if !$name { if %connections{$message} { $conn.print:...
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...
#Erlang
Erlang
1> F = fun([X]) -> X end. #Fun<erl_eval.6.13229925> 2> F("a"). 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...
#Euphoria
Euphoria
printf(1,"%d\n", 'a') -- prints "97" printf(1,"%s\n", 97) -- prints "a"
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...
#PowerShell
PowerShell
  function cholesky ($a) { $l = @() if ($a) { $n = $a.count $end = $n - 1 $l = 1..$n | foreach {$row = @(0) * $n; ,$row} foreach ($k in 0..$end) { $m = $k - 1 $sum = 0 if(0 -lt $k) { foreach ($j in 0..$m) {$sum += $l[$k][$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, ...
#zkl
zkl
dates:=T(T("May", 15), T("May", 16), T("May", 19), T("June", 17), T("June", 18), T("July", 14), T("July", 16), T("August",14), T("August",15), T("August",17) ); mDs:=dates.pump(Dictionary().appendKV); // "June":(15,16,19), ... dMs:=dates.pump(Dictionary().appendKV,"reverse"); // 15:"May", 16:"Ma...
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...
#Oforth
Oforth
Buffer A collection of bytes Mem A mutable collection of bytes Interval A first value, a last value and a step. Pair A collection of 2 elements (with key/value features). List A collection of n elements ListBuffer A mutable collection of n elements that can grow ...
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 ...
#Racket
Racket
  (define sublists (match-lambda** [(0 _) '(())] [(_ '()) '()] [(m (cons x xs)) (append (map (curry cons x) (sublists (- m 1) xs)) (sublists m xs))]))   (define (combinations n m) (sublists n (range m)))  
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 ...
#Tern
Tern
if(a > b) println(a);
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 ...
#PureBasic
PureBasic
EnableExplicit DisableDebugger DataSection LBL_n1: Data.i 3,5,7 LBL_a1: Data.i 2,3,2 LBL_n2: Data.i 11,12,13 LBL_a2: Data.i 10,4,12 LBL_n3: Data.i 10,4,9 LBL_a3: Data.i 11,22,19 EndDataSection   Procedure ErrorHdl() Print(ErrorMessage()) Input() EndProcedure   Macro PrintData(n,a) ...
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...
#Phix
Phix
without js -- (else cffi namespaces error, classes not supported by pwa/p2js anyway) requires ("1.0.2") -- (free up the temp used in the v.show() call) class five nullable private integer n = 3 function get_n() return n end function procedure set_n(integer n) this.n = n end procedur...
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...
#Ring
Ring
  decimals(10) x = list(10) y = list(10) x[1] = 0.654682 y[1] = 0.925557 x[2] = 0.409382 y[2] = 0.619391 x[3] = 0.891663 y[3] = 0.888594 x[4] = 0.716629 y[4] = 0.996200 x[5] = 0.477721 y[5] = 0.946355 x[6] = 0.925092 y[6] = 0.818220 x[7] = 0.624291 y[7] = 0.142924 x[8] = 0.211332 y[8] = 0.221507 x[9] = 0.293786 y[9] = ...
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...
#ooRexx
ooRexx
/*REXX pgm finds 2 circles with a specific radius given two (X,Y) points*/ a.='' a.1=0.1234 0.9876 0.8765 0.2345 2 a.2=0.0000 2.0000 0.0000 0.0000 1 a.3=0.1234 0.9876 0.1234 0.9876 2 a.4=0.1234 0.9876 0.8765 0.2345 0.5 a.5=0.1234 0.9876 0.1234 0.9876 0   Say ' x1 y1 x2 y2 radius cir1...
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...
#Python
Python
  # coding: utf-8   from __future__ import print_function from datetime import datetime   pinyin = { '甲': 'jiă', '乙': 'yĭ', '丙': 'bĭng', '丁': 'dīng', '戊': 'wù', '己': 'jĭ', '庚': 'gēng', '辛': 'xīn', '壬': 'rén', '癸': 'gŭi',   '子': 'zĭ', '丑': 'chŏu', '寅': 'yín', '卯': 'măo', '辰': 'chén', '巳':...
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 ...
#HolyC
HolyC
U0 FileExists(U8 *f) { if (FileFind(f) && !IsDir(f)) { Print("'%s' file exists.\n", f); } else { Print("'%s' file does not exist.\n", f); } }   U0 DirExists(U8 *d) { if (IsDir(d)) { Print("'%s' directory exists.\n", d); } else { Print("'%s' directory does not exist.\n", d); } }   FileExists(...
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 ...
#i
i
concept exists(path) { open(path) errors { if error.DoesNotExist() print(path, " does not exist!") end return } print(path, " exists!") }   software { exists("input.txt") exists("/input.txt") exists("docs") exists("/docs") exists("docs/Abdu'l-Bahá.txt") }
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 ...
#Perl
Perl
use Imager;   my $width = 1000; my $height = 1000;   my @points = ( [ $width/2, 0], [ 0, $height-1], [$height-1, $height-1], );   my $img = Imager->new( xsize => $width, ysize => $height, channels => 3, ...
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.
#Ruby
Ruby
require 'gserver'   class ChatServer < GServer def initialize *args super   #Keep a list for broadcasting messages @chatters = []   #We'll need this for thread safety @mutex = Mutex.new end   #Send message out to everyone but sender def broadcast message, sender = nil #Need to use \r\n ...
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...
#F.23
F#
let c = 'A' let n = 65 printfn "%d" (int c) printfn "%c" (char n)
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...
#Factor
Factor
CHAR: katakana-letter-a . "ア" first .   12450 1string print
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...
#Python
Python
from __future__ import print_function   from pprint import pprint from math import sqrt     def cholesky(A): L = [[0.0] * len(A) for _ in xrange(len(A))] for i in xrange(len(A)): for j in xrange(i+1): s = sum(L[i][k] * L[j][k] for k in xrange(j)) L[i][j] = sqrt(A[i][i] - s) if (i...
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...
#ooRexx
ooRexx
  a = .array~new(4) -- creates an array of 4 items, with all slots empty say a~size a~items -- size is 4, but there are 0 items a[1] = "Fred" -- assigns a value to the first item a[5] = "Mike" -- assigns a value to the fifth slot, expanding the size say a~size a~items -- size is now 5, with 2 items  
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 ...
#Raku
Raku
.say for combinations(5,3);
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 ...
#TI-83_BASIC
TI-83 BASIC
If condition 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 ...
#Python
Python
# Python 2.7 def chinese_remainder(n, a): sum = 0 prod = reduce(lambda a, b: a*b, n)   for n_i, a_i in zip(n, a): p = prod / n_i sum += a_i * mul_inv(p, n_i) * p return sum % prod     def mul_inv(a, b): b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a /...
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...
#PHL
PHL
module classes;   extern printf;   class @MyClass { field @Integer myField { get:get_myField, set:set_myField };   new [ this.set_myField(2); ]   @Void method [ this.set_myField(this::get_myField + 1); ] };   @Integer main [ var obj = new @MyClass; printf("obj.myField: %i\n", obj::get_myField); obj::method;...
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...
#PHP
PHP
class MyClass { public static $classVar; public $instanceVar; // can also initialize it here function __construct() { $this->instanceVar = 0; } function someMethod() { $this->instanceVar = 1; self::$classVar = 3; } } $myObj = new MyClass();
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...
#Ruby
Ruby
Point = Struct.new(:x, :y)   def distance(p1, p2) Math.hypot(p1.x - p2.x, p1.y - p2.y) end   def closest_bruteforce(points) mindist, minpts = Float::MAX, [] points.combination(2) do |pi,pj| dist = distance(pi, pj) if dist < mindist mindist = dist minpts = [pi, pj] end end [mindist, min...
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...
#PARI.2FGP
PARI/GP
circ(a, b, r)={ if(a==b, return("impossible")); my(h=(b-a)/2,t=sqrt(r^2-abs(h)^2)/abs(h)*h); [a+h+t*I,a+h-t*I] }; circ(0.1234 + 0.9876*I, 0.8765 + 0.2345*I, 2) circ(0.0000 + 2.0000*I, 0.0000 + 0.0000*I, 1) circ(0.1234 + 0.9876*I, 0.1234 + 0.9876*I, 2) circ(0.1234 + 0.9876*I, 0.8765 + 0.2345*I, .5) circ(0.1234 + 0...
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...
#Racket
Racket
#lang racket   (require racket/date)   ; Any CE Year that was the first of a 60-year cycle (define base-year 1984)   (define celestial-stems '("甲" "乙" "丙" "丁" "戊" "己" "庚" "辛" "壬" "癸"))   (define terrestrial-branches '("子" "丑" "寅" "卯" "辰" "巳" "午" "未" "申" "酉" "戌" "亥"))   (define zodiac-animals '("Rat" "Ox" "Tiger" "Rab...
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...
#Raku
Raku
sub Chinese-zodiac ( Int $year ) { my @heaven = <甲 jiă 乙 yĭ 丙 bĭng 丁 dīng 戊 wù 己 jĭ 庚 gēng 辛 xīn 壬 rén 癸 gŭi>.pairup; my @earth = <子 zĭ 丑 chŏu 寅 yín 卯 măo 辰 chén 巳 sì 午 wŭ 未 wèi 申 shēn 酉 yŏu 戌 xū 亥 hài>.pairup; my @animal = <Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog Pig>; my @el...
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 ...
#Icon_and_Unicon
Icon and Unicon
every dir := !["./","/"] do { write("file ", f := dir || "input.txt", if stat(f) then " exists." else " doesn't exist.") write("directory ", f := dir || "docs", if stat(f) then " exists." else " doesn't exist.") }
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 ...
#Phix
Phix
-- -- demo\rosetta\Chaos_game.exw -- =========================== -- with javascript_semantics include pGUI.e Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas enum TRI,SQ1,SQ2,SQ3,PENT sequence descs = {"Sierpinsky Triangle", "Square 1", "Square 2", "Square 3", ...
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.
#Rust
Rust
  use std::collections::HashMap; use std::io; use std::io::prelude::*; use std::io::BufReader; use std::net::{TcpListener, TcpStream}; use std::sync::{Arc, RwLock}; use std::thread;   type Username = String;   /// Sends a message to all clients except the sending client. fn broadcast_message( user: &str, client...
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...
#FALSE
FALSE
'A." "65,
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...
#Fantom
Fantom
fansh> 97.toChar a fansh> 'a'.toInt 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...
#q
q
solve:{[A;B] $[0h>type A;B%A;inv[A] mmu B]} ak:{[m;k] (),/:m[;k]til k:k-1} akk:{[m;k] m[k;k:k-1]} transpose:{$[0h=type x;flip x;enlist each x]} mult:{[A;B]$[0h=type A;A mmu B;A*B]} cholesky:{[A] {[A;L;n] l_k:solve[L;ak[A;n]]; l_kk:first over sqrt[akk[A;n] - mult[transpose l_k;l_k]]; ({$[0h<type x;enlist x;x]}L...
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...
#Oz
Oz
declare %% Lists (immutable, recursive) Xs = [1 2 3 4] %% Add element at the front (cons) Xs0 = 0|Xs {Show {Length Xs}} %% output: 4   %% Records (immutable maps with a label) Rec = label(1:2 symbol:3) {Show Rec} %% output: label(2 symbol:3) {Show Rec.1} %% output: 2 %% create a new record with an...
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 ...
#REXX
REXX
/*REXX program displays combination sets for X things taken Y at a time. */ parse arg x y $ . /*get optional arguments from the C.L. */ if x=='' | x=="," then x= 5 /*No X specified? Then use default.*/ if y=='' | y=="," then y= 3; oy= y; y= abs(y...
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 ...
#Toka
Toka
100 100 = [ ." True\n" ] ifTrue 100 200 = [ ." True\n" ] ifTrue
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 ...
#R
R
mul_inv <- function(a, b) { b0 <- b x0 <- 0L x1 <- 1L   if (b == 1) return(1L) while(a > 1){ q <- as.integer(a/b)   t <- b b <- a %% b a <- t   t <- x0 x0 <- x1 - q*x0 x1 <- t }   if (x1 < 0) x1 <- x1 + b0 return(x1) }   chinese_remainder <- function(n, a) { len <- length(n...
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...
#PicoLisp
PicoLisp
(class +Rectangle) # dx dy   (dm area> () # Define a a method that calculates the rectangle's area (* (: dx) (: dy)) )   (println # Create a rectangle, and print its area (area> (new '(+Rectangle) 'dx 3 'dy 4)) )
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...
#Pop11
Pop11
uses objectclass; define :class MyClass; slot value = 1; enddefine;
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...
#Run_BASIC
Run BASIC
n =10 ' 10 data points input dim x(n) dim y(n)   pt1 = 0 ' 1st point pt2 = 0 ' 2nd point   for i =1 to n ' read in data read x(i) read y(i) next i   minDist = 1000000   for i =1 to n -1 for j =i +1...
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...
#Perl
Perl
use strict;   sub circles { my ($x1, $y1, $x2, $y2, $r) = @_;   return "Radius is zero" if $r == 0; return "Coincident points gives infinite number of circles" if $x1 == $x2 and $y1 == $y2;   # delta x, delta y between points my ($dx, $dy) = ($x2 - $x1, $y2 - $y1); my $q = sqrt($dx**2 + $dy**2);...
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...
#Ring
Ring
  yinyang = ["yang", "yin"] elements = ["Wood", "Fire", "Earth", "Metal", "Water"] animals = ["Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"] years = [1801, 1861, 1984, 2020, 2186, 76543] output = ""   for year in years yy = year % 2 + 1...
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...
#Ruby
Ruby
# encoding: utf-8 pinyin = { '甲' => 'jiă', '乙' => 'yĭ', '丙' => 'bĭng', '丁' => 'dīng', '戊' => 'wù', '己' => 'jĭ', '庚' => 'gēng', '辛' => 'xīn', '壬' => 'rén', '癸' => 'gŭi',   '子' => 'zĭ', '丑' => 'chŏu', '寅' => 'yín', '卯' => 'măo', '辰' => 'chén', '巳' => 'sì', '午' => 'wŭ', '未' => 'wèi', ...
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 ...
#IDL
IDL
  print, FILE_TEST('input.txt') print, FILE_TEST(PATH_SEP()+'input.txt') print, FILE_TEST('docs', /DIRECTORY) print, FILE_TEST(PATH_SEP()+'docs', /DIRECTORY)    
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 ...
#J
J
require 'files' fexist 'input.txt' fexist '/input.txt' direxist=: 2 = ftype direxist 'docs' direxist '/docs'
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 ...
#Plain_English
Plain English
To run: Start up. Initialize our reference points. Clear the screen to the lightest gray color. Play the chaos game. Refresh the screen. Wait for the escape key. Shut down.   To play the chaos game: Pick a spot within 2 inches of the screen's center. Loop. Draw the spot. If a counter is past 20000, exit. Pick a referen...
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 ...
#Processing
Processing
size(300, 260);   background(#ffffff); // white   int x = floor(random(width)); int y = floor(random(height));   int colour = #ffffff;   for (int i=0; i<30000; i++) { int v = floor(random(3)); switch (v) { case 0: x = x / 2; y = y / 2; colour = #00ff00; // green break; case 1: x = width/2 + ...
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.
#Tcl
Tcl
package require Tcl 8.6   # Write a message to everyone except the sender of the message proc writeEveryoneElse {sender message} { dict for {who ch} $::cmap { if {$who ne $sender} { puts $ch $message } } }   # How to read a line (up to 256 chars long) in a coroutine proc cgets {ch var} { upvar 1 $var...
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...
#Forth
Forth
char a dup . \ 97 emit \ 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...
#Fortran
Fortran
WRITE(*,*) ACHAR(97), IACHAR("a") WRITE(*,*) CHAR(97), ICHAR("a")
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...
#R
R
t(chol(matrix(c(25, 15, -5, 15, 18, 0, -5, 0, 11), nrow=3, ncol=3))) # [,1] [,2] [,3] # [1,] 5 0 0 # [2,] 3 3 0 # [3,] -1 1 3   t(chol(matrix(c(18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106), nrow=4, ncol=4))) # [,1] [,2] [,3] [,4] # [1,] 4.2426...
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...
#Racket
Racket
  #lang racket (require math)   (define (cholesky A) (define mref matrix-ref) (define n (matrix-num-rows A)) (define L (for/vector ([_ n]) (for/vector ([_ n]) 0))) (define (set L i j x) (vector-set! (vector-ref L i) j x)) (define (ref L i j) (vector-ref (vector-ref L i) j)) (for* ([i n] [k n]) (set L i ...
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...
#PARI.2FGP
PARI/GP
v = vector(0); v = []; cv = vectorv(0); cv = []~; m = matrix(1,1); s = Set(v); l = List(v); vs = vectorsmall(0); M = Map()
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 ...
#Ring
Ring
  # Project : Combinations   n = 5 k = 3 temp = [] comb = [] num = com(n, k) while true temp = [] for n = 1 to 3 tm = random(4) + 1 add(temp, tm) next bool1 = (temp[1] = temp[2]) and (temp[1] = temp[3]) and (temp[2] = temp[3]) bool2 = (temp[1]...
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 ...
#TorqueScript
TorqueScript
// numbers and objects if(%num == 1) { foo(); } else if(%obj == MyObject.getID()) { bar(); } else { deusEx(); }   // strings if(%str $= "Hello World") { foo(); } else if(%str $= "Bye World") { bar(); } else { deusEx(); }
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 ...
#Racket
Racket
#lang racket (require (only-in math/number-theory solve-chinese)) (define as '(2 3 2)) (define ns '(3 5 7)) (solve-chinese as ns)
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 ...
#Raku
Raku
# returns x where (a * x) % b == 1 sub mul-inv($a is copy, $b is copy) { return 1 if $b == 1; my ($b0, @x) = $b, 0, 1; ($a, $b, @x) = ( $b, $a % $b, @x[1] - ($a div $b)*@x[0], @x[0] ) while $a > 1; @x[1] += $b0 if @x[1] < 0; return @x[1]; }   sub chinese-remainder(*@n) { my \N = [*] @n; ...
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...
#Portugol
Portugol
  programa { inclua biblioteca Objetos --> obj   // "constructor" returns address of object funcao inteiro my_class_new(inteiro value) { inteiro this = obj.criar_objeto() obj.atribuir_propriedade(this, "variable", value) // add property to object retorne this }   // "method" ...
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...
#PowerShell
PowerShell
  Add-Type -Language CSharp -TypeDefinition @' public class MyClass { public MyClass() { } public void SomeMethod() { } private int _variable; public int Variable { get { return _variable; } set { _variable = value; } } public static void Main() { ...
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...
#Rust
Rust
  //! We interpret complex numbers as points in the Cartesian plane, here. We also use the //! [sweepline/plane sweep closest pairs algorithm][algorithm] instead of the divide-and-conquer //! algorithm, since it's (arguably) easier to implement, and an efficient implementation does not //! require use of unsafe. //! //...
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...
#Phix
Phix
with javascript_semantics constant tests = {{0.1234, 0.9876, 0.8765, 0.2345, 2.0}, {0.0000, 2.0000, 0.0000, 0.0000, 1.0}, {0.1234, 0.9876, 0.1234, 0.9876, 2.0}, {0.1234, 0.9876, 0.8765, 0.2345, 0.5}, {0.1234, 0.9876, 0.1234, 0.9876, 0.0}} for i=1 t...
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...
#Rust
Rust
fn chinese_zodiac(year: usize) -> String { static ANIMALS: [&str; 12] = [ "Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig", ]; static ASPECTS: [&str; 2] = ["Yang", "Yin"]; static ELEMENTS: [&str; 5] = ["Wood", "Fire", "Earth", "Metal",...
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...
#Scala
Scala
object Zodiac extends App { val years = Seq(1935, 1938, 1968, 1972, 1976, 1984, 1985, 2017, 2018)   private def animals = Seq("Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig")   private def a...
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 ...
#Java
Java
import java.io.File; public class FileExistsTest { public static boolean isFileExists(String filename) { boolean exists = new File(filename).exists(); return exists; } public static void test(String type, String filename) { System.out.println("The following " + type + " called " + filename...
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 ...
#Python
Python
  import argparse import random import shapely.geometry as geometry import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation     def main(args): # Styles plt.style.use("ggplot")   # Creating figure fig = plt.figure() line, = plt.plot([], [], ".")   # Limit axes...
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.
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Net.Sockets Imports System.Text Imports System.Threading   Module Module1   Class State Private ReadOnly client As TcpClient Private ReadOnly sb As New StringBuilder   Public Sub New(name As String, client As TcpClient) Me.Name = name Me.client = client...
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...
#Free_Pascal
Free Pascal
  ' FreeBASIC v1.05.0 win64 Print "a - > "; Asc("a") Print "98 -> "; Chr(98) Print Print "Press any key to exit the program" Sleep End  
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...
#FreeBASIC
FreeBASIC
  ' FreeBASIC v1.05.0 win64 Print "a - > "; Asc("a") Print "98 -> "; Chr(98) Print Print "Press any key to exit the program" Sleep 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...
#Raku
Raku
sub cholesky(@A) { my @L = @A »*» 0; for ^@A -> $i { for 0..$i -> $j { @L[$i][$j] = ($i == $j ?? &sqrt !! 1/@L[$j][$j] * * )( @A[$i][$j] - [+] (@L[$i;*] Z* @L[$j;*])[^$j] ); } } return @L; } .say for cholesky [ [25], [15, 18], [-5, 0, 11], ];   .say for cholesky [ [18, 22,...
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...
#Pascal
Pascal
var MyArray: array[1..5] of real; begin MyArray[1] := 4.35; end;
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 ...
#Ruby
Ruby
def comb(m, n) (0...n).to_a.combination(m).to_a end   comb(3, 5) # => [[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]]