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_output_device_is_a_terminal
Check output device is a terminal
Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
#zkl
zkl
const S_IFCHR=0x2000; fcn S_ISCHR(f){ f.info()[4].bitAnd(S_IFCHR).toBool() } S_ISCHR(File.stdout).println();
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 ...
#8086_Assembly
8086 Assembly
cpu 8086 bits 16 vmode: equ 0Fh ; Get current video mode time: equ 2Ch ; Get current system time CGALO: equ 4 ; Low-res (4-color) CGA mode MDA: equ 7 ; MDA text mode section .text org 100h mov ah,vmode ; Get current video mode int 10h cmp al,MDA ; If MDA mode, no CGA supported, so stop jne gr_ok ret gr_ok:...
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.
#C
C
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/select.h> #include <netinet/in.h> #include <netinet/ip.h>   int tsocket; struct sockaddr_in tsockinfo; fd_set status, current; void ClientText(int handle, char *buf, int buf_len);   struct client { char buffer[4096]; int pos; char ...
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...
#Factor
Factor
USING: combinators formatting kernel locals math sequences ; IN: rosetta-code.machin   : tan+ ( x y -- z ) [ + ] [ * 1 swap - / ] 2bi ;   :: tan-eval ( coef frac -- x ) { { [ coef zero? ] [ 0 ] } { [ coef neg? ] [ coef neg frac tan-eval neg ] } { [ coef odd? ] [ frac coef 1 - frac tan-eval t...
http://rosettacode.org/wiki/Check_Machin-like_formulas
Check Machin-like formulas
Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing they equal 1: π 4 = ar...
#FreeBASIC
FreeBASIC
' version 07-04-2018 ' compile with: fbc -s console   #Include "gmp.bi"   #Define _a(Q) (@(Q)->_mp_num) 'a #Define _b(Q) (@(Q)->_mp_den) 'b   Data "[1, 1, 2] [1, 1, 3]" Data "[2, 1, 3] [1, 1, 7]" Data "[4, 1, 5] [-1, 1, 239]" Data "[5, 1, 7] [2, 3, 79]" Data "[1, 1, 2] [1, 1, 5] [1, 1, 8]" Data "[4, 1, 5] [-1, 1, 70]...
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...
#ActionScript
ActionScript
trace(String.fromCharCode(97)); //prints 'a' trace("a".charCodeAt(0));//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...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Char_Code is begin Put_Line (Character'Val (97) & " =" & Integer'Image (Character'Pos ('a'))); end Char_Code;
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square r...
#Fantom
Fantom
** ** Cholesky decomposition **   class Main { // create an array of Floats, initialised to 0.0 Float[][] makeArray (Int i, Int j) { Float[][] result := [,] i.times { result.add ([,]) } i.times |Int x| { j.times { result[x].add(0f) } } return result }   // pe...
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...
#Fortran
Fortran
Program Cholesky_decomp ! *************************************************! ! LBH @ ULPGC 06/03/2014 ! Compute the Cholesky decomposition for a matrix A ! after the attached ! http://rosettacode.org/wiki/Cholesky_decomposition ! note that the matrix A is complex since there might ! be values, where the sqrt has compl...
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, ...
#D
D
import std.algorithm.iteration : filter, joiner, map; import std.algorithm.searching : canFind; import std.algorithm.sorting : sort; import std.array : array; import std.datetime.date : Date, Month; import std.stdio : writeln;   void main() { auto choices = [ // Month.jan Date(2019, Month.may, 15), ...
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...
#Java
Java
import java.util.Scanner; import java.util.Random;   public class CheckpointSync{ public static void main(String[] args){ System.out.print("Enter number of workers to use: "); Scanner in = new Scanner(System.in); Worker.nWorkers = in.nextInt(); System.out.print("Enter number of tasks to complete:"); runTasks...
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...
#Groovy
Groovy
def emptyList = [] assert emptyList.isEmpty() : "These are not the items you're looking for" assert emptyList.size() == 0 : "Empty list has size 0" assert ! emptyList : "Empty list evaluates as boolean 'false'"   def initializedList = [ 1, "b", java.awt.Color.BLUE ] assert initializedList.size() == 3 assert initialized...
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 ...
#Maxima
Maxima
next_comb(n, p, a) := block( [a: copylist(a), i: p], if a[1] + p = n + 1 then return(und), while a[i] - i >= n - p do i: i - 1, a[i]: a[i] + 1, for j from i + 1 thru p do a[j]: a[j - 1] + 1, a )$   combinations(n, p) := block( [a: makelist(i, i, 1, p), v: [ ]], while a # 'und do (v: endcons(a, v...
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 ...
#Retro
Retro
condition [ true statements ] if condition [ false statements ] -if condition [ true statements ] [ false statements ] choose
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 ...
#Delphi
Delphi
  program ChineseRemainderTheorem;   uses System.SysUtils, Velthuis.BigIntegers;   function mulInv(a, b: BigInteger): BigInteger; var b0, x0, x1, q, amb, xqx: BigInteger; begin b0 := b; x0 := 0; x1 := 1;   if (b = 1) then exit(1);   while (a > 1) do begin q := a div b; amb := a mod b; 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...
#jq
jq
def add(stream): reduce stream as $x (0; . + $x);   # input should be an integer def commatize: def digits: tostring | explode | reverse; if . == null then "" elif . < 0 then "-" + ((- .) | commatize) else [foreach digits[] as $d (-1; .+1; # "," is 44 (select(. > 0 and . % 3 == 0)|44), $d)...
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The s...
#Julia
Julia
using Primes, Formatting   function chowla(n) if n < 1 throw("Chowla function argument must be positive") elseif n < 4 return zero(n) else f = [one(n)] for (p,e) in factor(n) f = reduce(vcat, [f*p^j for j in 1:e], init=f) end return sum(f) - one(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...
#Prolog
Prolog
church_zero(z).   church_successor(Z, c(Z)).   church_add(z, Z, Z). church_add(c(X), Y, c(Z)) :- church_add(X, Y, Z).   church_multiply(z, _, z). church_multiply(c(X), Y, R) :- church_add(Y, S, R), church_multiply(X, Y, S).   % N ^ M church_power(z, z, z). church_power(N, c(z), N). church_power(N, c(c(Z)), ...
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...
#GLSL
GLSL
  struct Rectangle{ float width; float height; };   Rectangle new(float width,float height){ Rectangle self; self.width = width; self.height = height; return self; }   float area(Rectangle self){ return self.width*self.height; }   float perimeter(Rectangle self){ return (self.width+self....
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...
#Julia
Julia
function closestpair(P::Vector{Vector{T}}) where T <: Number N = length(P) if N < 2 return (Inf, ()) end mindst = norm(P[1] - P[2]) minpts = (P[1], P[2]) for i in 1:N-1, j in i+1:N tmpdst = norm(P[i] - P[j]) if tmpdst < mindst mindst = tmpdst minpts = (P[i], P...
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...
#R
R
  # assign 's' a list of ten functions s <- sapply (1:10, # integers 1..10 become argument 'x' below function (x) { x # force evaluation of promise x function (i=x) i*i # this *function* is the return value })   s[[5]]() # call the fifth function in the list of returned functions [1] 25 # re...
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...
#Racket
Racket
  #lang racket (define functions (for/list ([i 10]) (λ() (* i i)))) (map (λ(f) (f)) functions)  
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...
#Factor
Factor
USING: accessors combinators combinators.short-circuit formatting io kernel literals locals math math.distances math.functions prettyprint sequences strings ; IN: rosetta-code.circles DEFER: find-circles   ! === Input ====================================================   TUPLE: input p1 p2 r ;   CONSTANT: test-cases {...
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...
#Delphi
Delphi
  program Chinese_zodiac;   {$APPTYPE CONSOLE}   uses Winapi.Windows, System.SysUtils, System.Math;   type TElements = array of array of char;   TChineseZodiac = record Year: Integer; Yyear: string; Animal: string; Element: string; AnimalChar: char; ElementChar: char; procedure Ass...
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 ...
#Arturo
Arturo
checkIfExists: function [fpath][ (or? exists? fpath exists? .directory fpath)? -> print [fpath "exists"] -> print [fpath "doesn't exist"] ]   checkIfExists "input.txt" checkIfExists "docs"   checkIfExists "/input.txt" checkIfExists "/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 ...
#AutoHotkey
AutoHotkey
; FileExist() function examples ShowFileExist("input.txt") ShowFileExist("\input.txt") ShowFolderExist("docs") ShowFolderExist("\docs")   ; IfExist/IfNotExist command examples (from documentation) IfExist, D:\ MsgBox, The drive exists. IfExist, D:\Docs\*.txt MsgBox, At least one .txt file exists. IfNotExist, C:\Tem...
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 ...
#Action.21
Action!
PROC Main() INT x,w=[220],h=[190] BYTE y,i,CH=$02FC,COLOR1=$02C5,COLOR2=$02C6   Graphics(8+16) Color=1 COLOR1=$0C COLOR2=$02   x=Rand(w) y=Rand(h) DO i=Rand(3) IF i=0 THEN x==/2 y==/2 ELSEIF i=1 THEN x=w/2+(w/2-x)/2 y=h-(h-y)/2 ELSE x=w-(w-x)/2 y=y/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 ...
#Amazing_Hopper
Amazing Hopper
  /* Chaos game - JAMBO hopper */   #include <jambo.h>   #define LIMITE 50000   Main ancho = 700, alto = 150 x=0,y=0,color=0 vertice=0, c=0, Let( c := Utf8(Chr(219))) Let(x := Int(Rand(ancho))) Let(y := Int(Rand(alto)))   mid ancho=0, Let( mid ancho:= Div(ancho,2))   i=LIMITE Void(pixeles) Loop ...
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.
#C.23
C#
using System; using System.Collections.Generic; using System.Net.Sockets; using System.Text; using System.Threading;   namespace ChatServer { class State { private TcpClient client; private StringBuilder sb = new StringBuilder();   public string Name { get; }   public State(string na...
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...
#GAP
GAP
TanPlus := function(a, b) return (a + b) / (1 - a * b); end;   TanTimes := function(n, a) local x; x := 0; while n > 0 do if IsOddInt(n) then x := TanPlus(x, a); fi; a := TanPlus(a, a); n := QuoInt(n, 2); od; return x; end;   Check := function(a) l...
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...
#Go
Go
package main   import ( "fmt" "math/big" )   type mTerm struct { a, n, d int64 }   var testCases = [][]mTerm{ {{1, 1, 2}, {1, 1, 3}}, {{2, 1, 3}, {1, 1, 7}}, {{4, 1, 5}, {-1, 1, 239}}, {{5, 1, 7}, {2, 3, 79}}, {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}}, {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}}, ...
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...
#Aime
Aime
# prints "97" o_integer('a'); o_byte('\n'); # prints "a" o_byte(97); o_byte('\n');
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#ALGOL_68
ALGOL 68
main:( printf(($gl$, ABS "a")); # for ASCII this prints "+97" EBCDIC prints "+129" # printf(($gl$, REPR 97)) # for ASCII this prints "a"; EBCDIC prints "/" # )
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...
#FreeBASIC
FreeBASIC
' version 18-01-2017 ' compile with: fbc -s console   Sub Cholesky_decomp(array() As Double)   Dim As Integer i, j, k Dim As Double s, l(UBound(array), UBound(array, 2))   For i = 0 To UBound(array) For j = 0 To i s = 0 For k = 0 To j -1 s += l(i, k) * l(j, k)...
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, ...
#F.23
F#
  //Find Cheryl's Birthday. Nigel Galloway: October 23rd., 2018 type Month = |May |June |July |August let fN n= n |> List.filter(fun (_,n)->(List.length n) < 2) |> List.unzip let dates = [(May,15);(May,16);(May,19);(June,17);(June,18);(July,14);(July,16);(August,14);(August,15);(August,17)] let _,n = dates |> List.grou...
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...
#Julia
Julia
  function runsim(numworkers, runs) for count in 1:runs @sync begin for worker in 1:numworkers @async begin tasktime = rand() sleep(tasktime) println("Worker $worker finished after $tasktime seconds") end...
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...
#Kotlin
Kotlin
// Version 1.2.41   import java.util.Random   val rgen = Random() var nWorkers = 0 var nTasks = 0   class Worker(private val threadID: Int) : Runnable {   @Synchronized override fun run() { try { val workTime = rgen.nextInt(900) + 100L // 100..999 msec. println("Worker $threadID...
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...
#Haskell
Haskell
[1, 2, 3, 4, 5]
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 ...
#Modula-2
Modula-2
  MODULE Combinations; FROM STextIO IMPORT WriteString, WriteLn; FROM SWholeIO IMPORT WriteInt;   CONST MMax = 3; NMax = 5;   VAR Combination: ARRAY [0 .. MMax] OF CARDINAL;   PROCEDURE Generate(M: CARDINAL); VAR N, I: CARDINAL; BEGIN IF (M > MMax) THEN FOR I := 1 TO MMax DO WriteInt(Combination...
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 ...
#REXX
REXX
if y then @=6 /* Y must be either 0 or 1 */   if t**2>u then x=y /*simple IF with THEN & ELSE. */ else x=-y   if t**2>u then do j=1 for 10; say prime(j); end /*THEN DO loop.*/ else x=-y /*simple ELSE....
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 ...
#EasyLang
EasyLang
func mul_inv a b . x1 . b0 = b x1 = 1 if b <> 1 while a > 1 q = a div b t = b b = a mod b a = t t = x0 x0 = x1 - q * x0 x1 = t . if x1 < 0 x1 += b0 . . . func remainder . n[] a[] r . prod = 1 sum = 0 for i range len n[] prod *= n[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 ...
#EchoLisp
EchoLisp
  (lib 'math) math.lib v1.10 ® EchoLisp Lib: math.lib loaded.   (crt-solve '(2 3 2) '(3 5 7)) → 23 (crt-solve '(2 3 2) '(7 1005 15)) 💥 error: mod[i] must be co-primes : assertion failed : 1005  
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...
#Kotlin
Kotlin
// Version 1.3.21   fun chowla(n: Int): Int { if (n < 1) throw RuntimeException("argument must be a positive integer") var sum = 0 var i = 2 while (i * i <= n) { if (n % i == 0) { val j = n / i sum += if (i == j) i else i + j } i++ } return sum }  ...
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...
#Python
Python
'''Church numerals'''   from itertools import repeat from functools import reduce     # ----- CHURCH ENCODINGS OF NUMERALS AND OPERATIONS ------   def churchZero(): '''The identity function. No applications of any supplied f to its argument. ''' return lambda f: identity     def churchSucc(cn)...
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...
#Go
Go
package main   import "fmt"   // a basic "class." // In quotes because Go does not use that term or have that exact concept. // Go simply has types that can have methods. type picnicBasket struct { nServings int // "instance variables" corkscrew bool }   // a method (yes, Go uses the word method!) func (b *picn...
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...
#Kotlin
Kotlin
// version 1.1.2   typealias Point = Pair<Double, Double>   fun distance(p1: Point, p2: Point) = Math.hypot(p1.first- p2.first, p1.second - p2.second)   fun bruteForceClosestPair(p: List<Point>): Pair<Double, Pair<Point, Point>> { val n = p.size if (n < 2) throw IllegalArgumentException("Must be at least two po...
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...
#Raku
Raku
my @c = gather for ^10 -> $i { take { $i * $i } }   .().say for @c.pick(*); # call them in random order
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...
#Red
Red
  funs: collect [repeat i 10 [keep func [] reduce [i ** 2]]]   >> funs/7 == 49  
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...
#Fortran
Fortran
  ! Implemented by Anant Dixit (Nov. 2014) ! Transpose elements in find_center to obtain correct results. R.N. McLean (Dec 2017) program circles implicit none double precision :: P1(2), P2(2), R   P1 = (/0.1234d0, 0.9876d0/) P2 = (/0.8765d0,0.2345d0/) R = 2.0d0 call print_centers(P1,P2,R)   P1 = (/0.0d0, 2.0d0/) P2 = (...
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...
#Excel
Excel
CNZODIAC =LAMBDA(y, APPENDCOLS( APPENDCOLS( APPENDCOLS( CNYEARNAME(y) )( CNYEARELEMENT(y) ) )( CNYEARANIMAL(y) ) )( CNYEARYINYANG(y) ) )     CNYEARANIMAL =LAMBDA(y, LET( shengxiao, { ...
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 ...
#AWK
AWK
@load "filefuncs"   function exists(name ,fd) { if ( stat(name, fd) == -1) print name " doesn't exist" else print name " exists" } BEGIN { exists("input.txt") exists("/input.txt") exists("docs") exists("/docs") }
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#Axe
Axe
If GetCalc("appvINPUT") Disp "EXISTS",i Else Disp "DOES NOT EXIST",i End
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 ...
#BASIC
BASIC
10 SCREEN 1 20 X = INT(RND(0) * 200) 30 Y = INT(RND(0) * 173) 40 FOR I=1 TO 20000 50 V = INT(RND(0) * 3) + 1 60 ON V GOTO 70,100,130 70 X = X/2 80 Y = Y/2 90 GOTO 150 100 X = 100 + (100-X)/2 110 Y = 173 - (173-Y)/2 120 GOTO 150 130 X = 200 - (200-X)/2 140 Y = Y/2 150 PSET X,Y,V 160 NEXT I
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
C
  #include<graphics.h> #include<stdlib.h> #include<stdio.h> #include<math.h> #include<time.h>   #define pi M_PI   int main(){   time_t t; double side, vertices[3][3],seedX,seedY,windowSide; int i,iter,choice;   printf("Enter triangle side length : "); scanf("%lf",&side);   printf("Enter number of iterations : ");...
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.
#CoffeeScript
CoffeeScript
  net = require("net") sys = require("sys") EventEmitter = require("events").EventEmitter   isNicknameLegal = (nickname) -> return false unless nickname.replace(/[A-Za-z0-9]*/, "") is "" for used_nick of @chatters return false if used_nick is nickname true   class ChatServer constructor: -> @chatters = ...
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...
#Haskell
Haskell
import Data.Ratio import Data.List (foldl')   tanPlus :: Fractional a => a -> a -> a tanPlus a b = (a + b) / (1 - a * b)   tanEval :: (Integral a, Fractional b) => (a, b) -> b tanEval (0,_) = 0 tanEval (coef,f) | coef < 0 = -tanEval (-coef, f) | odd coef = tanPlus f $ tanEval (coef - 1, f) | otherwise = tanPlus a 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...
#ALGOL_W
ALGOL W
begin  % display the character code of "a" (97 in ASCII)  % write( decode( "a" ) );  % display the character corresponding to 97 ("a" in ASCII)  % write( code( 97 ) ); end.
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#APL
APL
⎕UCS 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...
#Go
Go
package main   import ( "fmt" "math" )   // symmetric and lower use a packed representation that stores only // the lower triangle.   type symmetric struct { order int ele []float64 }   type lower struct { order int ele []float64 }   // symmetric.print prints a square matrix from the packed ...
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, ...
#Factor
Factor
USING: assocs calendar.english fry io kernel prettyprint sequences sets.extras ;   : unique-by ( seq quot -- newseq ) 2dup map non-repeating '[ @ _ member? ] filter ; inline   ALIAS: day first ALIAS: month second   { { 15 5 } { 16 5 } { 19 5 } { 17 6 } { 18 6 } { 14 7 } { 16 7 } { 14 8 } { 15 8 } { 17 8 } }...
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, ...
#Go
Go
package main   import ( "fmt" "time" )   type birthday struct{ month, day int }   func (b birthday) String() string { return fmt.Sprintf("%s %d", time.Month(b.month), b.day) }   func (b birthday) monthUniqueIn(bds []birthday) bool { count := 0 for _, bd := range bds { if bd.month == b.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...
#Logtalk
Logtalk
  :- object(checkpoint).   :- threaded.   :- public(run/3). :- mode(run(+integer,+integer,+float), one). :- info(run/3, [ comment is 'Assemble items using a team of workers with a maximum time per item assembly.', arguments is ['Workers'-'Number of workers', 'Items'-'Number of items to a...
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...
#Icon_and_Unicon
Icon and Unicon
# Creation of collections: s := "abccd" # string, an ordered collection of characters, immutable c := 'abcd' # cset, an unordered collection of characters, immutable S := set() # set, an unordered collection of...
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 ...
#Nim
Nim
iterator comb(m, n: int): seq[int] = var c = newSeq[int](n) for i in 0 ..< n: c[i] = i   block outer: while true: yield c   var i = n - 1 inc c[i] if c[i] <= m - 1: continue   while c[i] >= m - n + i: dec i if i < 0: break outer inc c[i] while i < n-1:...
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#Rhope
Rhope
If[cond] |: Do Something[] :||: Do Something Else[] :|
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 ...
#Elixir
Elixir
defmodule Chinese do def remainder(mods, remainders) do max = Enum.reduce(mods, fn x,acc -> x*acc end) Enum.zip(mods, remainders) |> Enum.map(fn {m,r} -> Enum.take_every(r..max, m) |> MapSet.new end) |> Enum.reduce(fn set,acc -> MapSet.intersection(set, acc) end) |> MapSet.to_list end end   IO.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 ...
#Erlang
Erlang
-module(crt). -import(lists, [zip/2, unzip/1, foldl/3, sum/1]). -export([egcd/2, mod/2, mod_inv/2, chinese_remainder/1]).   egcd(_, 0) -> {1, 0}; egcd(A, B) -> {S, T} = egcd(B, A rem B), {T, S - (A div B)*T}.   mod_inv(A, B) -> {X, Y} = egcd(A, B), if A*X + B*Y =:= 1 -> X; true -> undefi...
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...
#Lua
Lua
function chowla(n) local sum = 0 local i = 2 local j = 0 while i * i <= n do if n % i == 0 then j = math.floor(n / i) sum = sum + i if i ~= j then sum = sum + j end end i = i + 1 end return sum end   function...
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...
#Quackery
Quackery
[ this nested ] is zero ( --> cn )   [ this nested join ] is succ ( cn --> cn )   [ zero [ 2dup = if done succ rot succ unrot recurse ] 2drop ] is add ( cn cn --> cn )   [ zero unrot zero [ 2dup = if done succ 2swap tuck...
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...
#Groovy
Groovy
/** Ye olde classe declaration */ class Stuff { /** Heare bee anne instance variable declared */ def guts   /** This constructor converts bits into Stuff */ Stuff(injectedGuts) { guts = injectedGuts }   /** Brethren and sistren, let us flangulate with this fine flangulating method */ ...
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...
#Liberty_BASIC
Liberty BASIC
  N =10   dim x( N), y( N)   firstPt =0 secondPt =0   for i =1 to N read f: x( i) =f read f: y( i) =f next i   minDistance =1E6   for i =1 to N -1 for j =i +1 to N dxSq =( x( i) -x( j))^2 dySq =( y( i) -y( j))^2 D =abs( ( dxSq +dySq)^0.5) if D <minDistance then minDistan...
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...
#REXX
REXX
/*REXX program has a list of ten functions, each returns its invocation (index) squared.*/ parse arg seed base $ /*obtain optional arguments from the CL*/ if datatype(seed, 'W') then call random ,,seed /*Not given? Use random start seed. */ if base=='' | base="," then base=0 ...
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points
Circles of given radius through two points
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of circles with the point on thei...
#FreeBASIC
FreeBASIC
Type Point As Double x,y Declare Property length As Double End Type   Property point.length As Double Return Sqr(x*x+y*y) End Property   Sub circles(p1 As Point,p2 As Point,radius As Double) Print "Points ";"("&p1.x;","&p1.y;"),("&p2.x;","&p2.y;")";", Rad ";radius Var ctr=Type<Point>((p1.x+p2.x)/2,(p1.y...
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.23
F#
  open System   let animals = ["Rat";"Ox";"Tiger";"Rabbit";"Dragon";"Snake";"Horse";"Goat";"Monkey";"Rooster";"Dog";"Pig"] let elements = ["Wood";"Fire";"Earth";"Metal";"Water"] let years = [1935;1938;1968;1972;1976;1984;1985;2017]   let getZodiac(year: int) = let animal = animals.Item((year-4)%12) let element...
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 ...
#BASIC
BASIC
  ON ERROR GOTO ohNo f$ = "input.txt" GOSUB opener f$ = "\input.txt" GOSUB opener   'can't directly check for directories, 'but can check for the NUL device in the desired dir f$ = "docs\nul" GOSUB opener f$ = "\docs\nul" GOSUB opener END   opener: e$ = " found" OPEN f$ FOR INPUT AS 1 PRINT f$; e$ CLOSE...
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.23
C#
using System.Diagnostics; using System.Drawing;   namespace RosettaChaosGame { class Program { static void Main(string[] args) { var bm = new Bitmap(600, 600);   var referencePoints = new Point[] { new Point(0, 600), new Point(600, 600), ...
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.
#D
D
  import std.getopt; import std.socket; import std.stdio; import std.string;   struct client { int pos; char[] name; char[] buffer; Socket socket; }   void broadcast(client[] connections, size_t self, const char[] message) { writeln(message); for (size_t i = 0; i < connections.length; 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...
#J
J
machin =: 1r4p1 = [: +/ ({. * _3 o. %/@:}.)"1@:x:
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...
#Java
Java
  import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern;   public class CheckMachinFormula {   private static String FIL...
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...
#AppleScript
AppleScript
log(id of "a") log(id of "aA")
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...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program character.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall /* Initialized data */ .data szMessCodeChar: .ascii "The code of character is :" sZoneconv: .fill 12,1,' ' szCarriageRet...
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...
#Groovy
Groovy
def decompose = { a -> assert a.size > 0 && a[0].size == a.size def m = a.size def l = [].withEagerDefault { [].withEagerDefault { 0 } } (0..<m).each { i -> (0..i).each { k -> Number s = (0..<k).sum { j -> l[i][j] * l[k][j] } ?: 0 l[i][k] = (i == k) ...
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, ...
#Groovy
Groovy
import java.time.Month   class Main { private static class Birthday { private Month month private int day   Birthday(Month month, int day) { this.month = month this.day = day }   Month getMonth() { return month }   int getDa...
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...
#Nim
Nim
import locks import os import random import strformat   const NWorkers = 3 # Number of workers. NTasks = 4 # Number of tasks. StopOrder = 0 # Order 0 is the request to stop.   var randLock: Lock # Lock to access random number generator. orders: array[1..NWorkers, Channel...
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...
#Oforth
Oforth
: task(n, jobs, myChannel) while(true) [ System.Out "TASK " << n << " : Beginning my work..." << cr System sleep(1000 rand) System.Out "TASK " << n << " : Finish, sendind done and waiting for others..." << cr jobs send($jobDone) drop myChannel receive drop ] ;   : checkPoint(n, jo...
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...
#Perl
Perl
#!/usr/bin/perl use warnings; use strict; use v5.10;   use Socket;   my $nr_items = 3;   sub short_sleep($) { (my $seconds) = @_; select undef, undef, undef, $seconds; }   # This is run in a worker thread. It repeatedly waits for a character from # the main thread, and sends a value back to the main thread. A...
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...
#J
J
c =: 0 10 20 30 40 NB. A collection   c, 50 NB. Append 50 to the collection 0 10 20 30 40 50 _20 _10 , c NB. Prepend _20 _10 to the collection _20 _10 0 10 20 30 40   ,~ c NB. Self-append 0 10 20 30 40 0 10 20 30 40 ,:~ c NB. Duplicate 0 10 20 30 40 0...
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 ...
#OCaml
OCaml
let combinations m n = let rec c = function | (0,_) -> [[]] | (_,0) -> [] | (p,q) -> List.append (List.map (List.cons (n-q)) (c (p-1, q-1))) (c (p , q-1)) in c (m , n)     let () = let rec print_list = function | [] -> print_newline () | hd :: tl -> print_int hd ;...
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 ...
#Ring
Ring
If x == 1 SomeFunc1() But x == 2 SomeFunc2() Else SomeFunc() Ok
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 ...
#F.23
F#
let rec sieve cs x N = match cs with | [] -> Some(x) | (a,n)::rest -> let arrProgress = Seq.unfold (fun x -> Some(x, x+N)) x let firstXmodNequalA = Seq.tryFind (fun x -> a = x % n) match firstXmodNequalA (Seq.take n arrProgress) with | None -> None | Some(x) -> sieve ...
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...
#MAD
MAD
NORMAL MODE IS INTEGER   INTERNAL FUNCTION(N) ENTRY TO CHOWLA. SUM = 0 THROUGH LOOP, FOR I=2, 1, I*I.G.N J = N/I WHENEVER J*I.E.N SUM = SUM + I WHENEVER I.NE.J, SUM = SUM + J END OF CONDITIONA...
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...
#Maple
Maple
ChowlaFunction := n -> NumberTheory:-SumOfDivisors(n) - n - 1;   PrintChowla := proc(n::posint) local i; printf("Integer : Chowla Number\n"); for i to n do printf("%d  :  %d\n", i, ChowlaFunction(i)); end do; end proc:   countPrimes := n -> nops([ListTools[SearchAll](0, map(ChowlaFunction, [seq(1 .. n)]))]);   fin...
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...
#R
R
zero <- function(f) {function(x) x} succ <- function(n) {function(f) {function(x) f(n(f)(x))}} add <- function(n) {function(m) {function(f) {function(x) m(f)(n(f)(x))}}} mult <- function(n) {function(m) {function(f) m(n(f))}} expt <- function(n) {function(m) m(n)} natToChurch <- function(n) {if(n == 0) zero else succ(n...
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, a...
#Haskell
Haskell
class Shape a where perimeter :: a -> Double area :: a -> Double {- A type class Shape. Types belonging to Shape must support two methods, perimeter and area. -}   data Rectangle = Rectangle Double Double {- A new type with a single constructor. In the case of data types which have only one constructor, we...
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...
#Maple
Maple
ClosestPair := module()   local ModuleApply := proc(L::list,$) local Lx, Ly, out; Ly := sort(L, 'key'=(i->i[2]), 'output'='permutation'); Lx := sort(L, 'key'=(i->i[1]), 'output'='permutation'); out := Recurse(L, Lx, Ly, 1, numelems(L)); return sqrt(out[1]), out[2]; end proc; ...
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...
#Ring
Ring
  x = funcs(7) see x + nl   func funcs n fn = list(n) for i = 1 to n fn[i] =i*i next return fn  
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...
#Ruby
Ruby
procs = Array.new(10){|i| ->{i*i} } # -> creates a lambda p procs[7].call # => 49
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...
#Go
Go
package main   import ( "fmt" "math" )   var ( Two = "Two circles." R0 = "R==0.0 does not describe circles." Co = "Coincident points describe an infinite number of circles." CoR0 = "Coincident points with r==0.0 describe a degenerate circle." Diam = "Points form a diameter and describe ...
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...
#Factor
Factor
USING: circular formatting io kernel math qw sequences sequences.repeating ; IN: rosetta-code.zodiac   <PRIVATE   ! Offset start index by -4 because first cycle started on 4 CE. : circularize ( seq -- obj ) [ -4 ] dip <circular> [ change-circular-start ] keep ;   : animals ( -- obj ) qw{ Rat Ox Tiger Ra...
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...
#FreeBASIC
FreeBASIC
dim as string yy(0 to 1) = {"yang", "yin"} dim as string elements(0 to 4) = {"Wood", "Fire", "Earth", "Metal", "Water"} dim as string animals(0 to 11) = {"Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake",_ "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"}   dim as uinteger yr, y, e, ...