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/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 ...
#BASIC256
BASIC256
subroutine opener (filename$) if exists(filename$) then print filename$; " exists" else print filename$; " does not exists" end if end subroutine   call opener ("input.txt") call opener ("\input.txt") call opener ("docs\nul") call opener ("\docs\nul") call opener ("empty.kbs") call opener ("`Abdu'l-Bahá.t...
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 ...
#Batch_File
Batch File
if exist input.txt echo The following file called input.txt exists. if exist \input.txt echo The following file called \input.txt exists. if exist docs echo The following directory called docs exists. if exist \docs\ echo The following directory called \docs\ exists.
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a ...
#C.2B.2B
C++
  #include <windows.h> #include <ctime> #include <string> #include <iostream>   const int BMP_SIZE = 600;   class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); ...
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.
#Common_Lisp
Common Lisp
  (ql:quickload '(:usocket :simple-actors :bordeaux-threads))   (defpackage :chat-server (:use :common-lisp :usocket :simple-actors :bordeaux-threads) (:export :accept-connections))   (in-package :chat-server)   (defvar *whitespace* '(#\Space #\Tab #\Page #\Vt #\Newline #\Return))   (defun send-message (users from-...
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...
#Julia
Julia
  using AbstractAlgebra # implements arbitrary precision rationals   tanplus(x,y) = (x + y) / (1 - x * y)   function taneval(coef, frac) if coef == 0 return 0 elseif coef < 0 return -taneval(-coef, frac) elseif isodd(coef) return tanplus(frac, taneval(coef - 1, frac)) else ...
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...
#Kotlin
Kotlin
// version 1.1.3   import java.math.BigInteger   val bigZero = BigInteger.ZERO val bigOne = BigInteger.ONE   class BigRational : Comparable<BigRational> {   val num: BigInteger val denom: BigInteger   constructor(n: BigInteger, d: BigInteger) { require(d != bigZero) var nn = n var dd...
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...
#Arturo
Arturo
print to :integer first "a" print to :integer `a` print to :char 97
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#AutoHotkey
AutoHotkey
MsgBox % Chr(97) MsgBox % Asc("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...
#Haskell
Haskell
module Cholesky (Arr, cholesky) where   import Data.Array.IArray import Data.Array.MArray import Data.Array.Unboxed import Data.Array.ST   type Idx = (Int,Int) type Arr = UArray Idx Double   -- Return the (i,j) element of the lower triangular matrix. (We assume the -- lower array bound is (0,0).) get :: Arr -> Arr -> ...
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, ...
#Haskell
Haskell
{-# LANGUAGE OverloadedStrings #-}   import Data.List as L (filter, groupBy, head, length, sortOn) import Data.Map.Strict as M (Map, fromList, keys, lookup) import Data.Text as T (Text, splitOn, words) import Data.Maybe (fromJust) import Data.Ord (comparing) import Data.Function (on) import Data.Tuple (swap) import Dat...
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...
#Phix
Phix
-- demo\rosetta\checkpoint_synchronisation.exw without js -- task_xxx(), get_key() constant NPARTS = 3 integer workers = 0 sequence waiters = {} bool terminate = false procedure checkpoint(integer task_id) if length(waiters)+1=NPARTS or terminate then printf(1,"checkpoint\n") for i=1 to length(wait...
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...
#Java
Java
List arrayList = new ArrayList(); arrayList.add(new Integer(0)); // alternative with primitive autoboxed to an Integer object automatically arrayList.add(0);   //other features of ArrayList //define the type in the arraylist, you can substitute a proprietary class in the "<>" List<Integer> myarrlist = new ArrayList<In...
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 ...
#Octave
Octave
nchoosek([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 ...
#RLaB
RLaB
  if (x==1) { // do something }  
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 ...
#Factor
Factor
USING: math.algebra prettyprint ; { 2 3 2 } { 3 5 7 } chinese-remainder .
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 ...
#Forth
Forth
: egcd ( a b -- a b ) dup 0= IF 2drop 1 0 ELSE dup -rot /mod \ -- b r=a%b q=a/b -rot recurse \ -- q (s,t) = egcd(b, r) >r swap r@ * - r> swap \ -- t (s - q*t) THEN ;   : egcd>gcd ( a b x y -- n ) \ calculate gcd from egcd rot * -rot * +...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[Chowla] Chowla[0 | 1] := 0 Chowla[n_] := DivisorSigma[1, n] - 1 - n Table[{i, Chowla[i]}, {i, 37}] // Grid PrintTemporary[Dynamic[n]]; i = 1; Do[If[Chowla[n] == 0, i++], {n, 3, 100, 2}]; i i = 1; Do[If[Chowla[n] == 0, i++], {n, 3, 1000, 2}]; i i = 1; Do[If[Chowla[n] == 0, i++], {n, 3, 10000, 2}]; i i = 1; Do[I...
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...
#Nim
Nim
import strformat import strutils   func chowla(n: uint64): uint64 = var sum = 0u64 var i = 2u64 var j: uint64 while i * i <= n: if n mod i == 0: j = n div i sum += i if i != j: sum += j inc i sum   for n in 1u64..37: echo &"chowla({n}) = {chowla(n)}"   var count = 0 var pow...
http://rosettacode.org/wiki/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. C...
#Racket
Racket
#lang racket   (define zero (λ (f) (λ (x) x))) (define zero* (const identity)) ; zero renamed   (define one (λ (f) f)) (define one* identity) ; one renamed   (define succ (λ (n) (λ (f) (λ (x) (f ((n f) x)))))) (define succ* (λ (n) (λ (f) (λ (x) ((n f) (f x)))))) ; different impl   (define add (λ (n) (λ (m) (λ (f) (λ (x...
http://rosettacode.org/wiki/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. C...
#Raku
Raku
constant $zero = sub (Code $f) { sub ( $x) { $x }}   constant $succ = sub (Code $n) { sub (Code $f) { sub ( $x) { $f($n($f)($x)) }}}   constant $add = sub (Code $n) { sub (Code $m) { sub (Code $f) { s...
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...
#Icon_and_Unicon
Icon and Unicon
class Example (x) # 'x' is a field in class   # method definition method double () return 2 * x end   # 'initially' block is called on instance construction initially (x) if /x # if x is null (not given), then set field to 0 then self.x := 0 else self.x := x end   procedure main () x1 ...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
nearestPair[data_] := Block[{pos, dist = N[Outer[EuclideanDistance, data, data, 1]]}, pos = Position[dist, Min[DeleteCases[Flatten[dist], 0.]]]; data[[pos[[1]]]]]
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of runnin...
#Rust
Rust
fn main() { let fs: Vec<_> = (0..10).map(|i| {move || i*i} ).collect(); println!("7th val: {}", fs[7]()); }
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of runnin...
#Scala
Scala
val closures=for(i <- 0 to 9) yield (()=>i*i) 0 to 8 foreach (i=> println(closures(i)())) println("---\n"+closures(7)())
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...
#Groovy
Groovy
class Circles { private static class Point { private final double x, y   Point(Double x, Double y) { this.x = x this.y = y }   double distanceFrom(Point other) { double dx = x - other.x double dy = y - other.y return Math.sq...
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...
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import "fmt"   var ( animalString = []string{"Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"} stemYYString = []string{"Yang", "Yin"} elementString = []string{"Wood", "Fire", "Earth", "Metal", "Water"} stemCh = []rune("甲...
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 ...
#BBC_BASIC
BBC BASIC
test% = OPENIN("input.txt") IF test% THEN CLOSE #test% PRINT "File input.txt exists" ENDIF   test% = OPENIN("\input.txt") IF test% THEN CLOSE #test% PRINT "File \input.txt exists" ENDIF   test% = OPENIN("docs\NUL") IF test% THEN CLO...
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 ...
#BQN
BQN
fname ← ⊑args •Out fname∾" Does not exist"‿" Exists"⊑˜•File.exists fname
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 ...
#Common_Lisp
Common Lisp
(defpackage #:chaos (:use #:cl #:opticl))   (in-package #:chaos)   (defparameter *image-size* 600) (defparameter *margin* 50) (defparameter *edge-size* (- *image-size* *margin* *margin*)) (defparameter *iterations* 1000000)   (defun chaos () (let ((image (make-8-bit-rgb-image *image-size* *image-size* :init...
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.
#Erlang
Erlang
  -module(chat).   -export([start/0, start/1]).   -record(client, {name=none, socket=none}).   start() -> start(8080). start(Port) -> register(server, spawn(fun() -> server() end)), {ok, LSocket} = gen_tcp:listen(Port, [binary, {packet, 0}, {active, false}, {reuseaddr, true}]), accept(LSocket).   % main loo...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Tan[ArcTan[1/2] + ArcTan[1/3]] == 1 Tan[2 ArcTan[1/3] + ArcTan[1/7]] == 1 Tan[4 ArcTan[1/5] - ArcTan[1/239]] == 1 Tan[5 ArcTan[1/7] + 2 ArcTan[3/79]] == 1 Tan[5 ArcTan[29/278] + 7 ArcTan[3/79]] == 1 Tan[ArcTan[1/2] + ArcTan[1/5] + ArcTan[1/8]] == 1 Tan[4 ArcTan[1/5] - ArcTan[1/70] + ArcTan[1/99]] == 1 Tan[5 ArcTan[1/7]...
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...
#Maxima
Maxima
trigexpand:true$ is(tan(atan(1/2)+atan(1/3))=1); is(tan(2*atan(1/3)+atan(1/7))=1); is(tan(4*atan(1/5)-atan(1/239))=1); is(tan(5*atan(1/7)+2*atan(3/79))=1); is(tan(5*atan(29/278)+7*atan(3/79))=1); is(tan(atan(1/2)+atan(1/5)+atan(1/8))=1); is(tan(4*atan(1/5)-atan(1/70)+atan(1/99))=1); is(tan(5*atan(1/7)+4*atan(1/53)+2*at...
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...
#AWK
AWK
function ord(c) { return chmap[c] } BEGIN { for(i=0; i < 256; i++) { chmap[sprintf("%c", i)] = i } print ord("a"), ord("b") printf "%c %c\n", 97, 98 s = sprintf("%c%c", 97, 98) print s }
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...
#Icon_and_Unicon
Icon and Unicon
procedure cholesky (array) result := make_square_array (*array) every (i := 1 to *array) do { every (k := 1 to i) do { sum := 0 every (j := 1 to (k-1)) do { sum +:= result[i][j] * result[k][j] } if (i = k) then result[i][k] := sqrt(array[i][i] - sum) else result...
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, ...
#J
J
Dates=: <;._2 noun define 15 May 16 May 19 May 17 June 18 June 14 July 16 July 14 August 15 August 17 August )   getDayMonth=: |:@:(' '&splitstring&>) NB. retrieve lists of days and months from dates keep=: adverb def '] #~ u' NB. apply mask to filter dates   monthsW...
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...
#PicoLisp
PicoLisp
(de checkpoints (Projects Workers) (for P Projects (prinl "Starting project number " P ":") (for (Staff (mapcar '((I) (worker (format I) (rand 2 5))) # Create staff of workers (range 1 Workers) ) Staff # W...
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...
#PureBasic
PureBasic
#MaxWorktime=8000 ; "Workday" in msec   ; Structure that each thread uses Structure MyIO ThreadID.i Semaphore_Joining.i Semaphore_Release.i Semaphore_Deliver.i Semaphore_Leaving.i EndStructure   ; Array of used threads Global Dim Comm.MyIO(0)   ; Master loop synchronizing the threads via semaphores Procedure ...
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...
#JavaScript
JavaScript
var array = []; array.push('abc'); array.push(123); array.push(new MyClass); console.log( array[2] );
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 ...
#OpenEdge.2FProgress
OpenEdge/Progress
  define variable r as integer no-undo extent 3. define variable m as integer no-undo initial 5. define variable n as integer no-undo initial 3. define variable max_n as integer no-undo.   max_n = m - n.   function combinations returns logical (input pos as integer, input val as integer): define variable i as integer...
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 ...
#Ruby
Ruby
' Boolean Evaluations ' ' > Greater Than ' < Less Than ' >= Greater Than Or Equal To ' <= Less Than Or Equal To ' = Equal to   x = 0   if x = 0 then print "Zero"   ' -------------------------- ' if/then/else if x = 0 then print "Zero" else print "Nonzero" end if   ' -------------------------- ' not if x then print "x h...
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 ...
#FreeBASIC
FreeBASIC
  #include "gcd.bas" function mul_inv( a as integer, b as integer ) as integer if b = 1 then return 1 for i as integer = 1 to b if a*i mod b = 1 then return i next i return 0 end function   function chinese_remainder(n() as integer, a() as integer) as integer dim as integer p, i, prod = 1, sum = 0...
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...
#Pascal
Pascal
program Chowla_numbers;   {$IFDEF FPC} {$MODE Delphi} {$ELSE} {$APPTYPE CONSOLE} {$ENDIF}   uses SysUtils {$IFDEF FPC} ,StrUtils{for Numb2USA} {$ENDIF} ;     {$IFNDEF FPC} function Numb2USA(const S: string): string; var I, NA: Integer; begin I := Length(S); Result := S; NA := 0; while (I > 0) do...
http://rosettacode.org/wiki/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. C...
#Ruby
Ruby
def zero(f) return lambda {|x| x} end Zero = lambda { |f| zero(f) }   def succ(n) return lambda { |f| lambda { |x| f.(n.(f).(x)) } } end   Three = succ(succ(succ(Zero)))   def add(n, m) return lambda { |f| lambda { |x| m.(f).(n.(f).(x)) } } end   def mult(n, m) return lambda { |f| lambda { |x| m.(n.(f)).(x) } }...
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...
#J
J
coclass 'exampleClass'   exampleMethod=: monad define 1+exampleInstanceVariable )   create=: monad define 'this is the constructor' )   exampleInstanceVariable=: 0
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...
#MATLAB
MATLAB
function [closest,closestpair] = closestPair(xP,yP)   N = numel(xP);   if(N <= 3)   %Brute force closestpair if(N < 2) closest = +Inf; closestpair = {}; else closest = norm(xP{1}-xP{2}); closestpair = {xP{1},xP{2}};   fo...
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of runnin...
#Scheme
Scheme
;;; Collecting lambdas in a tail-recursive function. (define (build-list-of-functions n i list) (if (< i n) (build-list-of-functions n (+ i 1) (cons (lambda () (* (- n i) (- n i))) list)) list))   (define list-of-functions (build-list-of-functions 10 1 '()))   (map (lambda (f) (f)) list-of-functions)   ((...
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of runnin...
#Sidef
Sidef
var f = ( 10.of {|i| func(j){i * j} } )   9.times { |j| say f[j](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...
#Haskell
Haskell
add (a, b) (x, y) = (a + x, b + y) sub (a, b) (x, y) = (a - x, b - y) magSqr (a, b) = (a ^^ 2) + (b ^^ 2) mag a = sqrt $ magSqr a mul (a, b) c = (a * c, b * c) div2 (a, b) c = (a / c, b / c) perp (a, b) = (negate b, a) norm a = a `div2` mag a   circlePoints :: (Ord a, Floating ...
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...
#Go
Go
package main   import "fmt"   var ( animalString = []string{"Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"} stemYYString = []string{"Yang", "Yin"} elementString = []string{"Wood", "Fire", "Earth", "Metal", "Water"} stemCh = []rune("甲...
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 ...
#C
C
#include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <unistd.h>   /* Check for regular file. */ int check_reg(const char *path) { struct stat sb; return stat(path, &sb) == 0 && S_ISREG(sb.st_mode); }   /* Check for directory. */ int check_dir(const char *path) { struct stat sb; return stat(path...
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a ...
#Delphi
Delphi
  unit main;   interface   uses Winapi.Windows, System.Classes, Vcl.Graphics, Vcl.Forms, Vcl.ExtCtrls, System.Generics.Collections;   type TColoredPoint = record P: TPoint; Index: Integer; constructor Create(PX, PY: Integer; ColorIndex: Integer); end;   TForm1 = class(TForm) procedure FormCrea...
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.
#Go
Go
package main   import ( "bufio" "flag" "fmt" "log" "net" "strings" "time" )   func main() { log.SetPrefix("chat: ") addr := flag.String("addr", "localhost:4000", "listen address") flag.Parse() log.Fatal(ListenAndServe(*addr)) }   // A Server represents a chat server that accepts incoming connections. type Se...
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...
#Nim
Nim
import bignum   type   # Description of a term. Term = object factor: int # Multiplier (may be negative). fract: Rat # Argument of arc tangent.   Expression = seq[Term]   # Rational 1. let One = newRat(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...
#Axe
Axe
Disp 'a'▶Dec,i Disp 97▶Char,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...
#Babel
Babel
'abcdefg' str2ar {%d nl <<} eachar
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...
#Idris
Idris
module Main   import Data.Vect   Matrix : Nat -> Nat -> Type -> Type Matrix m n t = Vect m (Vect n t)     zeros : (m : Nat) -> (n : Nat) -> Matrix m n Double zeros m n = replicate m (replicate n 0.0)     indexM : (Fin m, Fin n) -> Matrix m n t -> t indexM (i, j) a = index j (index i a)     replaceAtM : (Fin m, Fin n) -...
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...
#J
J
mp=: +/ . * NB. matrix product h =: +@|: NB. conjugate transpose   cholesky=: 3 : 0 n=. #A=. y if. 1>:n do. assert. (A=|A)>0=A NB. check for positive definite  %:A else. 'X Y t Z'=. , (;~n$(>.-:n){.1) <;.1 A L0=. cholesky X L1=. cholesky Z-(T=.(h Y) mp %.X) mp Y L0,(T mp L0),.L1 end. )
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, ...
#Java
Java
import java.time.Month; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.stream.Collectors;   public class Main { private static class Birthday { private Month month; private int day;   public Birthday(Month month, int day) { this.month =...
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...
#Python
Python
  """   Based on https://pymotw.com/3/threading/   """   import threading import time import random     def worker(workernum, barrier): # task 1 sleeptime = random.random() print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime)) time.sleep(sleeptime) print('Exiting worker'+str(...
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...
#jq
jq
{"a": 1} == {a: 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 ...
#Oz
Oz
declare fun {Comb M N} proc {CombScript Comb} %% Comb is a subset of [0..N-1] Comb = {FS.var.upperBound {List.number 0 N-1 1}} %% Comb has cardinality M {FS.card Comb M} %% enumerate all possibilities {FS.distribute naive [Comb]} end in %% Collect all s...
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 ...
#Run_BASIC
Run BASIC
' Boolean Evaluations ' ' > Greater Than ' < Less Than ' >= Greater Than Or Equal To ' <= Less Than Or Equal To ' = Equal to   x = 0   if x = 0 then print "Zero"   ' -------------------------- ' if/then/else if x = 0 then print "Zero" else print "Nonzero" end if   ' -------------------------- ' not if x then print "x h...
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 ...
#Frink
Frink
/** arguments: [r, m, d=0] where r and m are arrays of the remainder terms r and the modulus terms m respectively. These must be of the same length. returns x, the unique solution mod N where N is the product of all the M terms where x &gt;= d. */ ChineseRemainder[r, m, d=0] := { 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 ...
#FunL
FunL
import integers.modinv   def crt( congruences ) = N = product( n | (_, n) <- congruences ) sum( a*modinv(N/n, n)*N/n | (a, n) <- congruences ) mod N   println( crt([(2, 3), (3, 5), (2, 7)]) )
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...
#Perl
Perl
use strict; use warnings; use ntheory 'divisor_sum';   sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }   sub chowla { my($n) = @_; $n < 2 ? 0 : divisor_sum($n) - ($n + 1); }   sub prime_cnt { my($n) = @_; my $cnt = 1; for (3..$n) { $cnt++ if $_%2 and chowla($_) == 0 ...
http://rosettacode.org/wiki/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. C...
#Rust
Rust
use std::rc::Rc; use std::ops::{Add, Mul};   #[derive(Clone)] struct Church<'a, T: 'a> { runner: Rc<dyn Fn(Rc<dyn Fn(T) -> T + 'a>) -> Rc<dyn Fn(T) -> T + 'a> + 'a>, }   impl<'a, T> Church<'a, T> { fn zero() -> Self { Church { runner: Rc::new(|_f| { Rc::new(|x| x) ...
http://rosettacode.org/wiki/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. C...
#Standard_ML
Standard ML
  val demo = fn () => let open IntInf   val zero = fn f => fn x => x ; fun succ n = fn f => f o (n f)  ; (* successor *) val rec church = fn 0 => zero | n => succ ( church (n-1) ) ; ...
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...
#Java
Java
public class MyClass{   // instance variable private int variable; // Note: instance variables are usually "private"   /** * The constructor */ public MyClass(){ // creates a new instance }   /** * A method */ public void someMethod(){ this.variable = 1; } }
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...
#JavaScript
JavaScript
//Constructor function. function Car(brand, weight) { this.brand = brand; this.weight = weight || 1000; // Resort to default value (with 'or' notation). } Car.prototype.getPrice = function() { // Method of Car. return this.price; }   function Truck(brand, size) { this.car = Car; this.car(brand, 2000); // Call...
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...
#Microsoft_Small_Basic
Microsoft Small Basic
' Closest Pair Problem s="0.654682,0.925557,0.409382,0.619391,0.891663,0.888594,0.716629,0.996200,0.477721,0.946355,0.925092,0.818220,0.624291,0.142924,0.211332,0.221507,0.293786,0.691701,0.839186,0.728260," i=0 While s<>"" i=i+1 For j=1 To 2 k=Text.GetIndexOf(s,",") ss=Text.GetSubText(s,1,k-1) ...
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of runnin...
#Smalltalk
Smalltalk
funcs := (1 to: 10) collect: [ :i | [ i * i ] ] . (funcs at: 3) value displayNl .
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of runnin...
#Sparkling
Sparkling
var fnlist = {}; for var i = 0; i < 10; i++ { fnlist[i] = function() { return i * i; }; }   print(fnlist[3]()); // prints 9 print(fnlist[5]()); // prints 25
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...
#Icon_and_Unicon
Icon and Unicon
procedure main() A := [ [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.9765, 0.2345, 0.5], [0.1234, 0.9876, 0.1234, 0.9876, 0.0] ] every write(cCenter!!A) end ...
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...
#Groovy
Groovy
class Zodiac { final static String[] animals = ["Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"] final static String[] elements = ["Wood", "Fire", "Earth", "Metal", "Water"] final static String[] animalChars = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申"...
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 ...
#C.23
C#
using System.IO;   Console.WriteLine(File.Exists("input.txt")); Console.WriteLine(File.Exists("/input.txt")); Console.WriteLine(Directory.Exists("docs")); Console.WriteLine(Directory.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 ...
#C.2B.2B
C++
#include "boost/filesystem.hpp" #include <string> #include <iostream>   void testfile(std::string name) { boost::filesystem::path file(name); if (exists(file)) { if (is_directory(file)) std::cout << name << " is a directory.\n"; else std::cout << name << " is a non-directory file.\n"; } el...
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 ...
#EasyLang
EasyLang
color 900 x[] = [ 0 100 50 ] y[] = [ 93 93 7 ] x = randomf * 100 y = randomf * 100 for i range 100000 move x y rect 0.3 0.3 h = random 3 x = (x + x[h]) / 2 y = (y + y[h]) / 2 .
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 ...
#Emacs_Lisp
Emacs Lisp
; Chaos game   (defun make-array (size) "Create an empty array with size*size elements." (setq m-array (make-vector size nil)) (dotimes (i size) (setf (aref m-array i) (make-vector size 0))) m-array)   (defun chaos-next (p) "Return the next coordinates." (let* ((points (list (cons 1 0) (cons -1 0) (cons...
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.
#Groovy
Groovy
class ChatServer implements Runnable { private int port = 0 private List<Client> clientList = new ArrayList<>()   ChatServer(int port) { this.port = port }   @SuppressWarnings("GroovyInfiniteLoopStatement") @Override void run() { try { ServerSocket serverSocket = ...
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...
#OCaml
OCaml
open Num;; (* use exact rationals for results *)   let tadd p q = (p +/ q) // ((Int 1) -/ (p */ q)) in   (* tan(n*arctan(a/b)) *) let rec tan_expr (n,a,b) = if n = 1 then (Int a)//(Int b) else if n = -1 then (Int (-a))//(Int b) else let m = n/2 in let tm = tan_expr (m,a,b) in let m2 = tadd tm tm and k =...
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...
#BASIC
BASIC
charCode = 97 char = "a" PRINT CHR$(charCode) 'prints a PRINT ASC(char) 'prints 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...
#BASIC256
BASIC256
# ASCII char charCode = 97 char$ = "a" print chr(97) #prints a print asc("a") #prints 97   # Unicode char charCode = 960 char$ = "π" print chr(960) #prints π print asc("π") #prints 960
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...
#Java
Java
import java.util.Arrays;   public class Cholesky { public static double[][] chol(double[][] a){ int m = a.length; double[][] l = new double[m][m]; //automatically initialzed to 0's for(int i = 0; i< m;i++){ for(int k = 0; k < (i+1); k++){ double sum = 0; for(int j = 0; j < k; j++){ sum += l[i][j]...
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth, ...
#JavaScript
JavaScript
(() => { 'use strict';   // main :: IO () const main = () => { const month = fst, day = snd; showLog( map(x => Array.from(x), (   // The month with only one remaining day,   // (A's month contains only one remaining day) ...
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...
#Racket
Racket
  #lang racket (define t 5)  ; total number of threads (define count 0) ; number of threads arrived at rendezvous (define mutex (make-semaphore 1)) ; exclusive access to count (define turnstile (make-semaphore 0)) (define turnstile2 (make-semaphore 1)) (define ch (make-channel))   (define (make-producer name s...
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...
#Raku
Raku
my $TotalWorkers = 3; my $BatchToRun = 3; my @TimeTaken = (5..15); # in seconds   my $batch_progress = 0; my @batch_lock = map { Semaphore.new(1) } , ^$TotalWorkers; my $lock = Lock.new;   sub assembly_line ($ID) { my $wait; for ^$BatchToRun -> $j { $wait = @TimeTaken.roll; say "Worker ",$ID," at batc...
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...
#Julia
Julia
    julia> collection = [] 0-element Array{Any,1}   julia> push!(collection, 1,2,4,7) 4-element Array{Any,1}: 1 2 4 7  
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 ...
#PARI.2FGP
PARI/GP
Crv ( k, v, d ) = { if( d == k, print ( vecextract( v , "2..-2" ) ) , for( i = v[ d + 1 ] + 1, #v, v[ d + 2 ] = i; Crv( k, v, d + 1 ) )); }   combRV( n, k ) = Crv ( k, vector( n, X, X-1), 0 );
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#Rust
Rust
// This function will only be compiled if we are compiling on Linux #[cfg(target_os = "linux")] fn running_linux() { println!("This is linux"); } #[cfg(not(target_os = "linux"))] fn running_linux() { println!("This is not linux"); }   // If we are on linux, we must be using glibc #[cfg_attr(target_os = "linux",...
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 ...
#Go
Go
package main   import ( "fmt" "math/big" )   var one = big.NewInt(1)   func crt(a, n []*big.Int) (*big.Int, error) { p := new(big.Int).Set(n[0]) for _, n1 := range n[1:] { p.Mul(p, n1) } var x, q, s, z big.Int for i, n1 := range n { q.Div(p, n1) z.GCD(nil, &s, n1, &q)...
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...
#Phix
Phix
function chowla(atom n) return sum(factors(n)) end function function sieve(integer limit) -- True denotes composite, false denotes prime. -- Only interested in odd numbers >= 3 sequence c = repeat(false,limit) for i=3 to floor(limit/3) by 2 do -- if not c[i] and chowla(i)==0 then if n...
http://rosettacode.org/wiki/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. C...
#Swift
Swift
func succ<A, B, C>(_ n: @escaping (@escaping (A) -> B) -> (C) -> A) -> (@escaping (A) -> B) -> (C) -> B { return {f in return {x in return f(n(f)(x)) } } }   func zero<A, B>(_ a: A) -> (B) -> B { return {b in return b } }   func three<A>(_ f: @escaping (A) -> A) -> (A) -> A { return {x in ...
http://rosettacode.org/wiki/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. C...
#Tailspin
Tailspin
  processor ChurchZero templates apply&{f:} $ ! end apply end ChurchZero   def zero: $ChurchZero;   processor Successor def predecessor: $; templates apply&{f:} $ -> predecessor::apply&{f: f} -> f ! end apply end Successor   templates churchFromInt @: $zero; $ -> # when <=0> do $@! when <1..> ...
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...
#Julia
Julia
abstract type Mammal end habitat(::Mammal) = "planet Earth"   struct Whale <: Mammal mass::Float64 habitat::String end Base.show(io::IO, ::Whale) = print(io, "a whale") habitat(w::Whale) = w.habitat   struct Wolf <: Mammal mass::Float64 end Base.show(io::IO, ::Wolf) = print(io, "a wolf")   arr = [Whale(1000...
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...
#Kotlin
Kotlin
class MyClass(val myInt: Int) { fun treble(): Int = myInt * 3 }   fun main(args: Array<String>) { val mc = MyClass(24) print("${mc.myInt}, ${mc.treble()}") }
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...
#Nim
Nim
import math, algorithm   type   Point = tuple[x, y: float] Pair = tuple[p1, p2: Point] Result = tuple[minDist: float; minPoints: Pair]   #---------------------------------------------------------------------------------------------------   template sqr(x: float): float = x * x   #---------------------------------...
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of runnin...
#Standard_ML
Standard ML
  List.map (fn x => x () ) ( List.tabulate (10,(fn i => (fn ()=> i*i)) ) ) ;  
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of runnin...
#Swift
Swift
var funcs: [() -> Int] = [] for var i = 0; i < 10; i++ { funcs.append({ i * i }) } println(funcs[3]()) // prints 100
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...
#J
J
average =: +/ % #   circles =: verb define"1 'P0 P1 R' =. (j./"1)_2[\y NB. Use complex plane C =. P0 average@:, P1 BAD =: ":@:+. C SEPARATION =. P0 |@- P1 if. 0 = SEPARATION do. if. 0 = R do. 'Degenerate point at ' , BAD else. 'Any center at a distance ' , (":R) , ' from ' , BAD , ' works.' end. elseif. SEP...
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...
#Haskell
Haskell
import Data.Array (Array, listArray, (!))   ------------------- TRADITIONAL STRINGS ------------------ ats :: Array Int (Char, String) ats = listArray (0, 9) $ zip -- 天干 tiangan – 10 heavenly stems "甲乙丙丁戊己庚辛壬癸" (words "jiă yĭ bĭng dīng wù jĭ gēng xīn rén gŭi")   ads :: Array Int (String, String)...