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/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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
CholeskyDecomposition[{{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}]
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, ...
#Perl
Perl
sub filter { my($test,@dates) = @_; my(%M,%D,@filtered);   # analysis of potential birthdays, keyed by month and by day for my $date (@dates) { my($mon,$day) = split '-', $date; $M{$mon}{cnt}++; $D{$day}{cnt}++; push @{$M{$mon}{day}}, $day; push @{$D{$day}{mon}},...
http://rosettacode.org/wiki/Checkpoint_synchronization
Checkpoint synchronization
The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before st...
#zkl
zkl
const NUM_PARTS=5; // number of parts used to make the product var requested=Atomic.Int(-1); // the id of the part the consumer needs var pipe=Thread.Pipe(); // "conveyor belt" of parts to consumer   fcn producer(id,pipe){ while(True){ // make part forever requested.waitFor(id); // wait for consumer 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...
#Lua
Lua
collection = {0, '1'} print(collection[1]) -- prints 0   collection = {["foo"] = 0, ["bar"] = '1'} -- a collection of key/value pairs print(collection["foo"]) -- prints 0 print(collection.foo) -- syntactic sugar, also prints 0   collection = {0, '1', ["foo"] = 0, ["bar"] = '1'}
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 ...
#PHP
PHP
  <?php   $a=array(1,2,3,4,5); $k=3; $n=5; $c=array_splice($a, $k); $b=array_splice($a, 0, $k); $j=$k-1; print_r($b);   while (1) {   $m=array_search($b[$j]+1,$c); if ($m!==false) { $c[$m]-=1; $b[$j]=$b[$j]+1; print_r($b); } if ($b[...
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 ...
#Seed7
Seed7
if condition then statement end if;   if condition then statement1 else statement2; end if;   if condition1 then statement1 elsif condition2 then statement2; end if;   if condition1 then statement1 elsif condition2 then statement2; else statement3; end if;
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 ...
#JavaScript
JavaScript
  function crt(num, rem) { let sum = 0; const prod = num.reduce((a, c) => a * c, 1);   for (let i = 0; i < num.length; i++) { const [ni, ri] = [num[i], rem[i]]; const p = Math.floor(prod / ni); sum += ri * p * mulInv(p, ni); } return sum % prod; }   function mulInv(a, b) { const b0 = b; let [x...
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...
#REXX
REXX
/*REXX program computes/displays chowla numbers (and may count primes & perfect numbers.*/ parse arg LO HI . /*obtain optional arguments from the CL*/ if LO=='' | LO=="," then LO= 1 /*Not specified? Then use the default.*/ perf= LO<0; LO= abs(LO) ...
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...
#MiniScript
MiniScript
// MiniScript is prototype based Weapon = { "name": "Sword", "damage": 3 } Weapon.slice = function() print "Did " + self.damage + " damage with " + self.name end function   wep = new Weapon // Same as: wep = { "__isa": Weapon }   wep.name = "Lance"   wep.slice
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...
#Pascal
Pascal
program closestPoints; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} const PointCnt = 10000;//31623; type TdblPoint = Record ptX, ptY : double; end; tPtLst = array of TdblPoint;   tMinDIstIdx = record md1, md2 : NativeInt; ...
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...
#Kotlin
Kotlin
// version 1.1.51   typealias IAE = IllegalArgumentException   class Point(val x: Double, val y: Double) { fun distanceFrom(other: Point): Double { val dx = x - other.x val dy = y - other.y return Math.sqrt(dx * dx + dy * dy ) }   override fun equals(other: Any?): Boolean { i...
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...
#Kotlin
Kotlin
// version 1.1.2   class ChineseZodiac(val year: Int) { val stem : Char val branch : Char val sName : String val bName : String val element: String val animal : String val aspect : String val cycle : Int   private companion object { val animals = listOf("Rat", "Ox", "Ti...
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 ...
#E
E
for file in [<file:input.txt>, <file:///input.txt>] { require(file.exists(), fn { `$file is missing!` }) require(!file.isDirectory(), fn { `$file is a directory!` }) }   for file in [<file:docs>, <file:///docs>] { require(file.exists(), fn { `$file is missing!` }) require(fi...
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 ...
#Gnuplot
Gnuplot
  ## Chaos Game (Sierpinski triangle) 2/16/17 aev reset fn="ChGS3Gnu1"; clr='"red"'; ttl="Chaos Game (Sierpinski triangle)" sz=600; sz1=sz/2; sz2=sz1*sqrt(3); x=y=xf=yf=v=0; dfn=fn.".dat"; ofn=fn.".png"; set terminal png font arial 12 size 640,640 set print dfn append set output ofn unset border; unset xtics; unset y...
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.
#Kotlin
Kotlin
import java.io.BufferedReader import java.io.IOException import java.io.InputStreamReader import java.io.OutputStreamWriter import java.io.Writer import java.net.ServerSocket import java.net.Socket import java.util.ArrayList import java.util.Collections   class ChatServer private constructor(private val port: Int) : Ru...
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...
#R
R
  #lang R library(Rmpfr) prec <- 1000 # precision in bits `%:%` <- function(e1, e2) '/'(mpfr(e1, prec), mpfr(e2, prec)) # operator %:% for high precision division # function for checking identity of tan of expression and 1, making use of high precision division operator %:% tanident_1 <- function(x) identical(round(tan...
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...
#Clojure
Clojure
(print (int \a)) ; prints "97" (print (char 97)) ; prints \a   ; Unicode is also available, as Clojure uses the underlying java Strings & chars (print (int \π)) ; prints 960 (print (char 960)) ; prints \π   ; use String because char in Java can't represent characters outside Basic Multilingual Plane (print (.codePoint...
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...
#MATLAB_.2F_Octave
MATLAB / Octave
A = [ 25 15 -5 15 18 0 -5 0 11 ];   B = [ 18 22 54 42 22 70 86 62 54 86 174 134 42 62 134 106 ];   [L] = chol(A,'lower') [L] = chol(B,'lower')  
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, ...
#Phix
Phix
-- demo\rosetta\Cheryls_Birthday.exw with javascript_semantics sequence choices = {{5, 15}, {5, 16}, {5, 19}, {6, 17}, {6, 18}, {7, 14}, {7, 16}, {8, 14}, {8, 15}, {8, 17}} sequence mwud = repeat(false,12) -- months with unique days for step=1 to 4 do sequence {months,days} = columnize(ch...
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...
#M2000_Interpreter
M2000 Interpreter
  Module Arr { \\ array as tuple A=(1,2,3,4,5) Print Array(A,0)=1 Print A \\ add two arrays A=Cons(A, (6,)) Print Len(A)=6 Print A \\ arrays may have arrays, inventories, stacks as items A=((1,2,3),(4,5,6)) Print Array(Array(A, 0),2)=3 } Arr  
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 ...
#Picat
Picat
go =>  % Integers 1..K N = 3, K = 5, printf("comb1(3,5): %w\n", comb1(N,K)), nl.   % Recursive (numbers) comb1(M,N) = comb1_(M, 1..N). comb1_(0, _X) = [[]]. comb1_(_M, []) = []. comb1_(M, [X|Xs]) = [ [X] ++ Xs2 : Xs2 in comb1_(M-1, Xs) ] ++ comb1_(M, Xs).
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 ...
#SIMPOL
SIMPOL
if x == 1 foo() else if x == 2 bar() else foobar() end if
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 ...
#jq
jq
# mul_inv(a;b) returns x where (a * x) % b == 1, or else null def mul_inv(a; b):   # state: [a, b, x0, x1] def iterate: .[0] as $a | .[1] as $b | if $a > 1 then if $b == 0 then null else ($a / $b | floor) as $q | [$b, ($a % $b), (.[3] - ($q * .[2])), .[2]] | iterate 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 ...
#Julia
Julia
function chineseremainder(n::Array, a::Array) Π = prod(n) mod(sum(ai * invmod(Π ÷ ni, ni) * (Π ÷ ni) for (ni, ai) in zip(n, a)), Π) end   @show chineseremainder([3, 5, 7], [2, 3, 2])
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...
#Ruby
Ruby
def chowla(n) sum = 0 i = 2 while i * i <= n do if n % i == 0 then sum = sum + i j = n / i if i != j then sum = sum + j end end i = i + 1 end return sum end   def main for n in 1 .. 37 do puts "chowla...
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...
#MiniZinc
MiniZinc
% define a Rectangle "class" var int: Rectangle(var int: width, var int: height) = let { var int: this; constraint Type(this) = Rectangle; %define the "type" of the instance  %define some "instance methods" constraint area(this) = width*height; constraint width(this) = width; constraint height(...
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...
#Nanoquery
Nanoquery
class MyClass declare name   // constructors are methods with the same name as the class def MyClass(name) this.name = name end   def getName() return name end end   // instantiate a new MyClass object inst = new(MyClass, "name string goes here")   // display the name value println inst.getName()
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...
#Perl
Perl
use strict; use warnings; use POSIX qw(ceil);   sub dist { my ($a, $b) = @_; return sqrt(($a->[0] - $b->[0])**2 + ($a->[1] - $b->[1])**2) }   sub closest_pair_simple { my @points = @{ shift @_ }; my ($a, $b, $d) = ( $points[0], $points[1], dist($points[0], $points[1]) ); while( @points ...
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...
#Lambdatalk
Lambdatalk
  input: OP1=(x1,y1), OP2=(x2,y2), r output: OC = OH + HC where OH = (OP1+OP2)/2 and HC = j*|HC| where j is the unit vector rotated -90° from P1P2 and |HC| = √(r^2 - (|P1P2|/2)^2) if exists   {def circleby2points {lambda {:x1 :y1 :x2 :y2 :r} {if {= :r 0} then radius is zero else {if {and {= ...
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...
#Lua
Lua
local ANIMALS = {"Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig"} local ELEMENTS = {"Wood","Fire","Earth","Metal","Water"}   function element(year) local idx = math.floor(((year - 4) % 10) / 2) return ELEMENTS[idx + 1] end   function animal(year) local idx = (year ...
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 ...
#Elena
Elena
import system'io; import extensions;   extension op { validatePath() = self.Available.iif("exists","not found"); }   public program() { console.printLine("input.txt file ",File.assign("input.txt").validatePath());   console.printLine("\input.txt file ",File.assign("\input.txt").validatePath()); ...
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 ...
#Elixir
Elixir
File.regular?("input.txt") File.dir?("docs") File.regular?("/input.txt") File.dir?("/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 ...
#Go
Go
package main   import ( "fmt" "image" "image/color" "image/draw" "image/gif" "log" "math" "math/rand" "os" "time" )   var bwPalette = color.Palette{ color.Transparent, color.White, color.RGBA{R: 0xff, A: 0xff}, color.RGBA{G: 0xff, A: 0xff}, color.RGBA{B: 0xff, A: 0xff}, }   func main() { const ( width...
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.
#Nim
Nim
import asyncnet, asyncdispatch   type Client = tuple socket: AsyncSocket name: string connected: bool   var clients {.threadvar.}: seq[Client]   proc sendOthers(client: Client, line: string) {.async.} = for c in clients: if c != client and c.connected: await c.socket.send(line & "\c\L")   proc...
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...
#Racket
Racket
  #lang racket (define (reduce e) (match e [(? number? a) a] [(list '+ (? number? a) (? number? b)) (+ a b)] [(list '- (? number? a) (? number? b)) (- a b)] [(list '- (? number? a)) (- a)] [(list '* (? number? a) (? number? b)) (* a b)] [(list '/ (? number...
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...
#Raku
Raku
sub taneval ($coef, $f) { return 0 if $coef == 0; return $f if $coef == 1; return -taneval(-$coef, $f) if $coef < 0;   my $a = taneval($coef+>1, $f); my $b = taneval($coef - $coef+>1, $f); ($a+$b)/(1-$a*$b); }   sub tans (@xs) { return taneval(@xs[0;0], @xs[0;1].FatRat) if @xs == 1;   my $a = tans(@xs[0...
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...
#CLU
CLU
start_up = proc () po: stream := stream$primary_output()    % To turn a character code into an integer, use char$c2i  % (but then to print it, it needs to be turned into a string first  % with int$unparse) stream$putl(po, int$unparse( char$c2i( 'a' ) ) ) % prints '97'    % To turn an integer into 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...
#COBOL
COBOL
identification division. program-id. character-codes. remarks. COBOL is an ordinal language, first is 1. remarks. 42nd ASCII code is ")" not, "*". procedure division. display function char(42) display function ord('*') goback. end program character-codes.
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...
#Maxima
Maxima
/* Cholesky decomposition is built-in */   a: hilbert_matrix(4)$   b: cholesky(a); /* matrix([1, 0, 0, 0 ], [1/2, 1/(2*sqrt(3)), 0, 0 ], [1/3, 1/(2*sqrt(3)), 1/(6*sqrt(5)), 0 ], [1/4, 3^(3/2)/20, 1/(4*sqrt(5)), 1/...
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...
#Nim
Nim
import math, strutils, strformat   type Matrix[N: static int, T: SomeFloat] = array[N, array[N, T]]   proc cholesky[Matrix](a: Matrix): Matrix = for i in 0 ..< a[0].len: for j in 0 .. i: var s = 0.0 for k in 0 ..< j: s += result[i][k] * result[j][k] result[i][j] = if i == j: sqrt(a[i][i]...
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, ...
#Python
Python
'''Cheryl's Birthday'''   from itertools import groupby from re import split     # main :: IO () def main(): '''Derivation of the date.'''   month, day = 0, 1 print( # (3 :: A "Then I also know") # (A's month contains only one remaining day) uniquePairing(month)( # (2 :: ...
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...
#Maple
Maple
  L1 := [3, 4, 5, 6]; L1 := [3, 4, 5, 6]   L2 := [7, 8, 9]; L2 := [7, 8, 9]  
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 ...
#PicoLisp
PicoLisp
(de comb (M Lst) (cond ((=0 M) '(NIL)) ((not Lst)) (T (conc (mapcar '((Y) (cons (car Lst) Y)) (comb (dec M) (cdr Lst)) ) (comb M (cdr Lst)) ) ) ) )   (comb 3 (1 2 3 4 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 ...
#Simula
Simula
statement::= if conditional_expression then statement else statement if X=Y then K:=I else K:=J statement::= if conditional_expression then statement if X=Y then K:=I
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 ...
#Kotlin
Kotlin
// version 1.1.2   /* returns x where (a * x) % b == 1 */ fun multInv(a: Int, b: Int): Int { if (b == 1) return 1 var aa = a var bb = b var x0 = 0 var x1 = 1 while (aa > 1) { val q = aa / bb var t = bb bb = aa % bb aa = t t = x0 x0 = x1 - q * x0 ...
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...
#Scala
Scala
object ChowlaNumbers { def main(args: Array[String]): Unit = { println("Chowla Numbers...") for(n <- 1 to 37){println(s"$n: ${chowlaNum(n)}")} println("\nPrime Counts...") for(i <- (2 to 7).map(math.pow(10, _).toInt)){println(f"$i%,d: ${primesPar(i).size}%,d")} println("\nPerfect Numbers...") ...
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...
#Nemerle
Nemerle
public class MyClass { public this() { } // the constructor in Nemerle is always named 'this'   public MyVariable : int { get; set; }   public MyMethod() : void { }   }   def myInstance = MyClass(); // no 'new' keyword needed myInsta...
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...
#NetRexx
NetRexx
class ClassExample   properties private -- class scope foo = int   properties public -- publicly visible bar = boolean   properties indirect -- generates bean patterns baz = String()   method main(args=String[]) static -- main method clsex = ClassExample() -- instantiate clsex.foo = 42 clse...
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...
#Phix
Phix
with javascript_semantics function bruteForceClosestPair(sequence s) atom {x1,y1} = s[1], {x2,y2} = s[2], dx = x1-x2, dy = y1-y2, mind = dx*dx+dy*dy sequence minp = s[1..2] for i=1 to length(s)-1 do {x1,y1} = s[i] for j=i+1 to length(s) do {x2,y2} = s[j] ...
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...
#Liberty_BASIC
Liberty BASIC
  '[RC] Circles of given radius through two points for i = 1 to 5 read x1, y1, x2, y2,r print i;") ";x1, y1, x2, y2,r call twoCircles x1, y1, x2, y2,r next end   'p1 p2 r data 0.1234, 0.9876, 0.8765, 0.2345, 2.0 data 0.0000, 2.0000, 0.0000, 0.0000, 1.0 data 0.1234, 0.987...
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...
#Maple
Maple
  zodiac:=proc(year::integer) local year60,yinyang,animal,element; year60:= (year-3) mod 60; yinyang:=["Yin","Yang"]; animal:=["Pig","Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog"]; element:=["Water","Wood","Wood","Fire","Fire","Earth","Earth","Metal","Metal","Water"]...
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 ...
#Emacs_Lisp
Emacs Lisp
(file-exists-p "input.txt") (file-directory-p "docs") (file-exists-p "/input.txt") (file-directory-p "/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 ...
#Groovy
Groovy
import javafx.animation.AnimationTimer import javafx.application.Application import javafx.scene.Scene import javafx.scene.layout.Pane import javafx.scene.paint.Color import javafx.scene.shape.Circle import javafx.stage.Stage   class ChaosGame extends Application {   final randomNumberGenerator = new Random()   ...
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.
#Objeck
Objeck
  use System.IO.Net; use System.Concurrency; use Collection;   bundle Default { class ChatServer { @clients : StringMap; @clients_mutex : ThreadMutex;   New() { @clients := StringMap->New(); @clients_mutex := ThreadMutex->New("clients_mutex"); }   method : ValidLogin(login_name : Strin...
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...
#REXX
REXX
/*REXX program evaluates some Machin─like formulas and verifies their veracity. */ @.=; pi= pi(); numeric digits( length(pi) ) - length(.); numeric fuzz 3 say center(' computing with ' digits() " decimal digits ", 110, '═') @.1 = 'pi/4 = atan(1/2) + atan(1/3)' @.2 = 'pi/4 = 2*atan(1/3)...
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...
#CoffeeScript
CoffeeScript
console.log 'a'.charCodeAt 0 # 97 console.log String.fromCharCode 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...
#Objeck
Objeck
  class Cholesky { function : Main(args : String[]) ~ Nil { n := 3; m1 := [25.0, 15.0, -5.0, 15.0, 18.0, 0.0, -5.0, 0.0, 11.0]; c1 := Cholesky(m1, n); ShowMatrix(c1, n);   IO.Console->PrintLine();   n := 4; m2 := [18.0, 22.0, 54.0, 42.0, 22.0, 70.0, 86.0, 62.0, 54.0, 86.0, 174.0, 1...
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, ...
#R
R
options <- dplyr::tibble(mon = rep(c("May", "June", "July", "August"),times = c(3,2,2,3)), day = c(15, 16, 19, 17, 18, 14, 16, 14, 15, 17))   okMonths <- c() # Albert's first clue - it is a month with no unique day for (i in unique(options$mon)){ if(all(options$day[options$mon == i] %in% opt...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Lst = {3, 4, 5, 6} ->{3, 4, 5, 6}   PrependTo[ Lst, 2] ->{2, 3, 4, 5, 6} PrependTo[ Lst, 1] ->{1, 2, 3, 4, 5, 6}   Lst ->{1, 2, 3, 4, 5, 6}   Insert[ Lst, X, 4] ->{1, 2, 3, X, 4, 5, 6}
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 ...
#Pop11
Pop11
define comb(n, m); lvars ress = []; define do_combs(l, m, el_lst); lvars i; if m = 0 then cons(rev(el_lst), ress) -> ress; else for i from l to n - m do do_combs(i + 1, m - 1, cons(i, el_lst)); endfor; endif; enddefine; ...
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 ...
#Slate
Slate
"Conditionals in Slate are really messages sent to Boolean objects. Like Smalltalk. (But the compiler might optimize some cases)" balance > 0 ifTrue: [inform: 'still sitting pretty!'.] ifFalse: [inform: 'No money till payday!'.].
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 ...
#Lobster
Lobster
import std   def extended_gcd(a, b): var s = 0 var old_s = 1 var t = 1 var old_t = 0 var r = b var old_r = a   while r != 0: let quotient = old_r / r old_r, r = r, old_r - quotient * r old_s, s = s, old_s - quotient * s old_t, t = t, old_t - quotient * t   ...
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...
#Swift
Swift
import Foundation   @inlinable public func chowla<T: BinaryInteger>(n: T) -> T { stride(from: 2, to: T(Double(n).squareRoot()+1), by: 1) .lazy .filter({ n % $0 == 0 }) .reduce(0, {(s: T, m: T) in m*m == n ? s + m : s + m + (n / m) }) }   extension Dictionary where Key == ClosedRange<Int> { sub...
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...
#Visual_Basic
Visual Basic
Option Explicit   Private Declare Function AllocConsole Lib "kernel32.dll" () As Long Private Declare Function FreeConsole Lib "kernel32.dll" () As Long Dim mStdOut As Scripting.TextStream   Function chowla(ByVal n As Long) As Long Dim j As Long, i As Long i = 2 Do While i * i <= n j = n \ i If n Mod i = 0 ...
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...
#Nim
Nim
type MyClass = object name: int   proc initMyClass(): MyClass = result.name = 2   proc someMethod(m: var MyClass) = m.name = 1   var mc = initMyClass() mc.someMethod()   type Gender = enum male, female, other   MyOtherClass = object name: string gender: Gender age: Natural   proc initMyOtherClass(...
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...
#PicoLisp
PicoLisp
(de closestPairBF (Lst) (let Min T (use (Pt1 Pt2) (for P Lst (for Q Lst (or (== P Q) (>= (setq N (let (A (- (car P) (car Q)) B (- (cdr P) (cdr Q))) (+ (* A A) (* B B)...
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...
#Lua
Lua
function distance(p1, p2) local dx = (p1.x-p2.x) local dy = (p1.y-p2.y) return math.sqrt(dx*dx + dy*dy) end   function findCircles(p1, p2, radius) local seperation = distance(p1, p2) if seperation == 0.0 then if radius == 0.0 then print("No circles can be drawn through ("..p1.x.....
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
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", "申" -> "shēn", "酉" -> "yŏu", "戌" -> "x...
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 ...
#Erlang
Erlang
#!/usr/bin/escript existence( true ) ->"exists"; existence( false ) ->"does not exist".   print_result(Type, Name, Flag) -> io:fwrite( "~s ~s ~s~n", [Type, Name, existence(Flag)] ).     main(_) -> print_result( "File", "input.txt", filelib:is_regular("input.txt") ), print_result( "Directory", "docs", fi...
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 ...
#Haskell
Haskell
import Control.Monad (replicateM) import Control.Monad.Random (fromList)   type Point = (Float,Float) type Transformations = [(Point -> Point, Float)] -- weighted transformations   -- realization of the game for given transformations gameOfChaos :: MonadRandom m => Int -> Transformations -> Point -> m [Point] gameOfCha...
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.
#Ol
Ol
  (define (timestamp) (syscall 201 "%c"))   (fork-server 'chat-room (lambda () (let this ((visitors #empty)) (let* ((envelope (wait-mail)) (sender msg envelope)) (case msg (['join who name] (let ((visitors (put visitors who name))) (for-each (lambda (who) (print-to...
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...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "bigint.s7i"; include "bigrat.s7i";   const type: mTerms is array array bigInteger;   const array mTerms: testCases is [] ( [] ([] ( 1_, 1_, 2_), [] ( 1_, 1_, 3_)), [] ([] ( 2_, 1_, 3_), [] ( 1_, 1_, 7_)), [] ([] ( 4_, 1_, 5_), [] (-1_, 1_, 239_)), [] ([] ...
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...
#Sidef
Sidef
var equationtext = <<'EOT' pi/4 = arctan(1/2) + arctan(1/3) pi/4 = 2*arctan(1/3) + arctan(1/7) pi/4 = 4*arctan(1/5) - arctan(1/239) pi/4 = 5*arctan(1/7) + 2*arctan(3/79) pi/4 = 5*arctan(29/278) + 7*arctan(3/79) pi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8) pi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/9...
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...
#Common_Lisp
Common Lisp
(princ (char-code #\a)) ; prints "97" (princ (code-char 97)) ; prints "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...
#Component_Pascal
Component Pascal
PROCEDURE CharCodes*; VAR c : CHAR; BEGIN c := 'A'; StdLog.Char(c);StdLog.String(":> ");StdLog.Int(ORD(c));StdLog.Ln; c := CHR(3A9H); StdLog.Char(c);StdLog.String(":> ");StdLog.Int(ORD(c));StdLog.Ln END CharCodes;
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...
#OCaml
OCaml
let cholesky inp = let n = Array.length inp in let res = Array.make_matrix n n 0.0 in let factor i k = let rec sum j = if j = k then 0.0 else res.(i).(j) *. res.(k).(j) +. sum (j+1) in inp.(i).(k) -. sum 0 in for col = 0 to n-1 do res.(col).(col) <- sqrt (factor col 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, ...
#Racket
Racket
#lang racket   (define ((is x #:key [key identity]) y) (equal? (key x) (key y)))   (define albert first) (define bernard second)   (define (((unique who) chs) date) (= 1 (count (is date #:key who) chs)))   (define (((unique-fix who-fix who) chs) date) (ormap (conjoin (is date #:key who-fix) ((unique who) chs)) chs)) ...
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, ...
#Raku
Raku
my @dates = { :15day, :5month }, { :16day, :5month }, { :19day, :5month }, { :17day, :6month }, { :18day, :6month }, { :14day, :7month }, { :16day, :7month }, { :14day, :8month }, { :15day, :8month }, { :17day, :8month } ;   # Month can't have a unique day my @filtered = @dates.g...
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...
#MATLAB_.2F_Octave
MATLAB / Octave
>> A = {2,'TPS Report'} %Declare cell-array and initialize   A =   [2] 'TPS Report'   >> A{2} = struct('make','honda','year',2003)   A =   [2] [1x1 struct]   >> A{3} = {3,'HOVA'} %Create and assign A{3}   A =   [2] [1x1 struct] {1x2 cell}   >> A{2} %Get A{2}   ans =   make: 'honda' y...
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 ...
#PowerShell
PowerShell
  $source = @' using System; using System.Collections.Generic;   namespace Powershell { public class CSharp { public static IEnumerable<int[]> Combinations(int m, int n) { int[] result = new int[m]; Stack<int> stack = new Stack<int>...
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 ...
#Smalltalk
Smalltalk
  balance > 0 ifTrue: [Transcript cr; show: 'still sitting pretty!'.] ifFalse: [Transcript cr; show: 'No money till payday!'.].   balance < 10 ifTrue:[ self goGetSomeMoney ].   balance > 1000 ifTrue:[ self beHappy ].   (balance < 10) ifFalse:[ self gotoHappyHour ] ifTrue:[ self noDrinksToday ].  
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 ...
#Lua
Lua
-- Taken from https://www.rosettacode.org/wiki/Sum_and_product_of_an_array#Lua function prodf(a, ...) return a and a * prodf(...) or 1 end function prodt(t) return prodf(unpack(t)) end   function mulInv(a, b) local b0 = b local x0 = 0 local x1 = 1   if b == 1 then return 1 end   while a ...
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...
#Visual_Basic_.NET
Visual Basic .NET
Imports System   Module Program Function chowla(ByVal n As Integer) As Integer chowla = 0 : Dim j As Integer, i As Integer = 2 While i * i <= n j = n / i : If n Mod i = 0 Then chowla += i + (If(i = j, 0, j)) i += 1 End While End Function   Function sieve(ByVal...
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...
#Oberon-2
Oberon-2
MODULE M;   TYPE T = POINTER TO TDesc; TDesc = RECORD x: INTEGER END;   PROCEDURE New*(): T; VAR t: T; BEGIN NEW(t); t.x := 0; RETURN t END New;     PROCEDURE (t: T) Increment*; BEGIN INC(t.x) END Increment;   END 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...
#Objeck
Objeck
bundle Default { class MyClass { @var : Int;   New() { }   method : public : SomeMethod() ~ Nil { @var := 1; }   method : public : SetVar(var : Int) ~ Nil { @var := var; }   method : public : GetVar() ~ Int { return @var; } }   class Test { function : 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...
#PL.2FI
PL/I
  /* Closest Pair Problem */ closest: procedure options (main); declare n fixed binary;   get list (n); begin; declare 1 P(n), 2 x float, 2 y float; declare (i, ii, j, jj) fixed binary; declare (distance, min_distance initial (0) ) float;   get list (P); ...
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...
#Maple
Maple
drawCircles := proc(x1, y1, x2, y2, r, $) local c1, c2, p1, p2; use geometry in if x1 = x2 and y1 = y2 then if r = 0 then printf("The circle is a point at [%a, %a].\n", x1, y1); else printf("The two points are the same. Infinite circles can be drawn.\n"); end if; elif evalf(distance(point(A, x1, ...
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...
#Modula-2
Modula-2
MODULE ChineseZodiac; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,ReadChar;   TYPE Str = ARRAY[0..7] OF CHAR;   TYPE AA = ARRAY[0..11] OF Str; CONST ANIMALS = AA{"Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig"};   TYPE EA = ARRAY[0..4] OF Str; CONST...
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 ...
#Euphoria
Euphoria
include file.e   procedure ensure_exists(sequence name) object x sequence s x = dir(name) if sequence(x) then if find('d',x[1][D_ATTRIBUTES]) then s = "directory" else s = "file" end if printf(1,"%s %s exists.\n",{name,s}) else printf(1...
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 ...
#F.23
F#
open System.IO File.Exists("input.txt") Directory.Exists("docs") File.Exists("/input.txt") Directory.Exists(@"\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 ...
#J
J
  Note 'plan, Working in complex plane' Make an equilateral triangle. Make a list of N targets Starting with a random point near the triangle, iteratively generate new points. plot the new points.   j has a particularly rich notation for numbers.   1ad_90 specifies a complex number with radius 1 a...
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 ...
#Java
Java
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.Timer;   public class ChaosGame extends JPanel { static class ColoredPoint extends Point { int colorIndex;   ColoredPoint(int x, int y, int idx) { super(x, y); colorIndex ...
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.
#Perl
Perl
use 5.010; use strict; use warnings;   use threads; use threads::shared;   use IO::Socket::INET; use Time::HiRes qw(sleep ualarm);   my $HOST = "localhost"; my $PORT = 4004;   my @open; my %users : shared;   sub broadcast { my ($id, $message) = @_; print "$message\n"; foreach my $i (keys %users) { i...
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...
#Tcl
Tcl
package require Tcl 8.5   # Compute tan(atan(p)+atan(q)) using rationals proc tadd {p q} { lassign $p pp pq lassign $q qp qq set topp [expr {$pp*$qq + $qp*$pq}] set topq [expr {$pq*$qq}] set prodp [expr {$pp*$qp}] set prodq [expr {$pq*$qq}] set lowp [expr {$prodq - $prodp}] set resultp [...
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...
#D
D
void main() { import std.stdio, std.utf;   string test = "a"; size_t index = 0;   // Get four-byte utf32 value for index 0. writefln("%d", test.decode(index));   // 'index' has moved to next character input position. assert(index == 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...
#Dc
Dc
97P
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...
#ooRexx
ooRexx
/*REXX program performs the Cholesky decomposition on a square matrix. */ niner = '25 15 -5' , /*define a 3x3 matrix. */ '15 18 0' , '-5 0 11' call Cholesky niner hexer = 18 22 54 42, /*define a ...
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, ...
#REXX
REXX
/*REXX pgm finds Cheryl's birth date based on a person knowing the birth month, another */ /*──────────────────────── person knowing the birth day, given a list of possible dates.*/ $= 'May-15 May-16 May-19 June-17 June-18 July-14 July-16 August-14 August-15 August-17' call delDays unique('day') $= unique('day') $= uni...
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...
#MiniScript
MiniScript
seq = [0, "foo", pi] seq.push 42 seq = seq + [1, 2, 3] print seq
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 ...
#Prolog
Prolog
:- use_module(library(clpfd)).   comb_clpfd(L, M, N) :- length(L, M), L ins 1..N, chain(L, #<), label(L).