task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#Trith
Trith
true ["yes" print] ["no" print] branch
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 ...
#True_BASIC
True BASIC
  ! IF-ELSEIF-ELSE-END IF ! SELECT-CASE ! ON GOTO, ON GOSUB   IF expr_booleana THEN sentencia(s) END IF     IF expr_booleana1 THEN sentencia(s) ELSEIF expr_booleana2 THEN sentencia(s) ELSEIF expr_booleana3 THEN sentencia(s) ELSE sentencia(s) END IF     SELECT CASE expr_booleana CASE 1 sentencia(s) C...
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 ...
#REXX
REXX
/*REXX program demonstrates Sun Tzu's (or Sunzi's) Chinese Remainder Theorem. */ parse arg Ns As . /*get optional arguments from the C.L. */ if Ns=='' | Ns=="," then Ns= '3,5,7' /*Ns not specified? Then use default.*/ if As=='' | As=="," then As= '2,3,2' ...
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...
#Processing
Processing
class ProgrammingLanguage { // instance variable: private String name; // constructor (let's use it to give the instance variable a value): public ProgrammingLanguage(String name) { this.name = name; // note use of "this" to distinguish the instance variable from the argument } // a met...
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...
#PureBasic
PureBasic
Interface OO_Interface ; Interface for any value of this type Get.i() Set(Value.i) ToString.s() Destroy() EndInterface   Structure OO_Structure ; The *VTable structure Get.i Set.i ToString.i Destroy.i EndStructure   Structure OO_Var *VirtualTable.OO_Structure Value.i EndStructure  ...
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...
#Scala
Scala
import scala.collection.mutable.ListBuffer import scala.util.Random   object ClosestPair { case class Point(x: Double, y: Double){ def distance(p: Point) = math.hypot(x-p.x, y-p.y)   override def toString = "(" + x + ", " + y + ")" }   case class Pair(point1: Point, point2: Point) { val distance: Doub...
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...
#PL.2FI
PL/I
twoci: Proc Options(main); Dcl 1 *(5), 2 m1x Dec Float Init(0.1234, 0,0.1234,0.1234,0.1234), 2 m1y Dec Float Init(0.9876, 2,0.9876,0.9876,0.9876), 2 m2x Dec Float Init(0.8765, 0,0.1234,0.8765,0.1234), 2 m2y Dec Float Init(0.2345, 0,0.9876,0.2345,0.9876), 2 r Dec Float In...
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...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "console.s7i";   const array string: animals is [0] ("Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"); const array string: elements is [0] ("Wood", "Fire", "Earth", "Metal", "Water"); const array string: animalChars is [0] ("子", "...
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo...
#Sidef
Sidef
func zodiac(year) { var animals = %w(Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog Pig) var elements = %w(Wood Fire Earth Metal Water) var terrestrial_han = %w(子 丑 寅 卯 辰 巳 午 未 申 酉 戌 亥) var terrestrial_pinyin = %w(zĭ chŏu yín măo chén sì wŭ wèi shēn yŏu xū hài) var celestial_han = %w(甲 乙 丙 丁 戊...
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 ...
#JavaScript
JavaScript
var fso = new ActiveXObject("Scripting.FileSystemObject");   fso.FileExists('input.txt'); fso.FileExists('c:/input.txt'); fso.FolderExists('docs'); fso.FolderExists('c:/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 ...
#Julia
Julia
@show isfile("input.txt") @show isfile("/input.txt") @show isdir("docs") @show isdir("/docs") @show isfile("") @show isfile("`Abdu'l-Bahá.txt")
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a ...
#R
R
  # Chaos Game (Sierpinski triangle) 2/15/17 aev # pChaosGameS3(size, lim, clr, fn, ttl) # Where: size - defines matrix and picture size; lim - limit of the dots; # fn - file name (.ext will be added); ttl - plot title; pChaosGameS3 <- function(size, lim, clr, fn, ttl) { cat(" *** START:", date(), "size=",size, "...
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 ...
#Racket
Racket
#lang racket   (require 2htdp/image)   (define SIZE 300)   (define (game-of-chaos fns WIDTH HEIGHT SIZE #:offset-x [offset-x 0] #:offset-y [offset-y 0] #:iters [iters 10000] #:bg [bg 'white] #:fg [fg 'black]) (define dot (square 1 'solid fg)) (def...
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.
#Wren
Wren
/* chat_server.wren */   class Clients { foreign static max foreign static count foreign static isActive(vmi) foreign static connfd(vmi) foreign static uid(vmi) foreign static name(vmi) foreign static setName(vmi, s) foreign static printAddr(vmi) foreign static delete(vmi) }   class ...
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...
#Frink
Frink
println[char["a"]] // prints 97 println[chars["a"]] // prints [97] (an array) println[char[97]] // prints a println[char["Frink rules!"]] // prints [70, 114, 105, 110, 107, 32, 114, 117, 108, 101, 115, 33] println[[70, 114, 105, 110, 107, 32, 114, 117, 108, 101, 115, 33]] // pr...
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...
#Gambas
Gambas
Public Sub Form_Open() Dim sChar As String   sChar = InputBox("Enter a character") Print "Character " & sChar & " = ASCII " & Str(Asc(sChar))   sChar = InputBox("Enter a ASCII code") Print "ASCII code " & sChar & " represents " & Chr(Val(sChar))   End
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square r...
#REXX
REXX
/*REXX program performs the Cholesky decomposition on a square matrix & displays results*/ niner = '25 15 -5' , /*define a 3x3 matrix with elements. */ '15 18 0' , '-5 0 11' call Cholesky niner hexer = 18 22 54 42, ...
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...
#Perl
Perl
use strict; my @c = (); # create an empty "array" collection   # fill it push @c, 10, 11, 12; push @c, 65; # print it print join(" ",@c) . "\n";   # create an empty hash my %h = (); # add some pair $h{'one'} = 1; $h{'two'} = 2; # print it foreach my $i ( keys %h ) { print $i . " -> " . $h{$i} . "\n"; }
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 ...
#Rust
Rust
  fn comb<T: std::fmt::Default>(arr: &[T], n: uint) { let mut incl_arr: ~[bool] = std::vec::from_elem(arr.len(), false); comb_intern(arr, n, incl_arr, 0); }   fn comb_intern<T: std::fmt::Default>(arr: &[T], n: uint, incl_arr: &mut [bool], index: uint) { if (arr.len() < n + index) { return; } if (n == 0) { l...
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 ...
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT   condition="c" IF (condition=="a") THEN ---> do something ELSEIF (condition=="b") THEN ---> do something ELSE ---> do something ENDIF  
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 ...
#Ruby
Ruby
  def chinese_remainder(mods, remainders) max = mods.inject( :* ) series = remainders.zip( mods ).map{|r,m| r.step( max, m ).to_a } series.inject( :& ).first #returns nil when empty end   p chinese_remainder([3,5,7], [2,3,2]) #=> 23 p chinese_remainder([10,4,9], [11,22,19]) #=> ni...
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...
#Python
Python
class MyClass: name2 = 2 # Class attribute   def __init__(self): """ Constructor (Technically an initializer rather than a true "constructor") """ self.name1 = 0 # Instance attribute   def someMethod(self): """ Method """ self.name1 = 1 ...
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...
#Seed7
Seed7
const type: point is new struct var float: x is 0.0; var float: y is 0.0; end struct;   const func float: distance (in point: p1, in point: p2) is return sqrt((p1.x-p2.x)**2+(p1.y-p2.y)**2);   const func array point: closest_pair (in array point: points) is func result var array point: result is 0 tim...
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...
#PureBasic
PureBasic
DataSection DataStart: Data.d 0.1234, 0.9876, 0.8765, 0.2345, 2.0 Data.d 0.0000, 2.0000, 0.0000, 0.0000, 1.0 Data.d 0.1234, 0.9876, 0.1234, 0.9876, 2.0 Data.d 0.1234, 0.9876, 0.9765, 0.2345, 0.5 Data.d 0.1234, 0.9876, 0.1234, 0.9876, 0.0 DataEnd: EndDataSection Macro MaxRec : (?Da...
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...
#tbas
tbas
  DATA "甲","乙","丙","丁","戊","己","庚","辛","壬","癸" DECLARE celestial$(10) MAT READ celestial$   DATA "子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥" DECLARE terrestrial$(12) MAT READ terrestrial$   DATA "Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig" DECLARE animals$(12) ...
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 ...
#Klingphix
Klingphix
include ..\Utilitys.tlhy   "foo.bar" "w" fopen "Hallo !" over fputs fclose   "fou.bar" "r" fopen dup 0 < ( ["Could not open 'fou.bar' for reading" print drop] [fclose] ) if   " " input
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 ...
#Kotlin
Kotlin
// version 1.0.6   import java.io.File   fun main(args: Array<String>) { val filePaths = arrayOf("input.txt", "c:\\input.txt", "zero_length.txt", "`Abdu'l-Bahá.txt") val dirPaths = arrayOf("docs", "c:\\docs") for (filePath in filePaths) { val f = File(filePath) println("$filePath ${if (f.ex...
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 ...
#Raku
Raku
use Image::PNG::Portable;   my ($w, $h) = (640, 640);   my $png = Image::PNG::Portable.new: :width($w), :height($h);   my @vertex = [0, 0], [$w, 0], [$w/2, $h];   my @xy = [0,0], [0,0], [0,0], [0,0];   # :degree must be equal to or less than @xy elements. (^1e5).race(:4degree).map: { my $p = ++$ % +@xy; @xy[$p]...
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.
#zkl
zkl
const PORT=23;   var users=Dictionary(); // ( handle:socket, ...) pipe:=Thread.Pipe(); // how server tells thread to connect to user   fcn accept(pipe){ // a thread waiting for the server to send a socket while(socket:=pipe.read()){ println("Somebody is connecting ..."); socket.read(); // telnet stuff ...
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...
#GAP
GAP
# Code must be in 0 .. 255. CharInt(65); # 'A' IntChar('Z'); # 90
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...
#Go
Go
fmt.Println('a') // prints "97" fmt.Println('π') // 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...
#Ring
Ring
  # Project : Cholesky decomposition   load "stdlib.ring" decimals(5) m1 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]] cholesky(m1) printarray(m1) see nl   m2 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]] cholesky(m2) printarray(...
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...
#Ruby
Ruby
require 'matrix'   class Matrix def symmetric? return false if not square? (0 ... row_size).each do |i| (0 .. i).each do |j| return false if self[i,j] != self[j,i] end end true end   def cholesky_factor raise ArgumentError, "must provide symmetric matrix" unless symmetric? ...
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...
#Phix
Phix
with javascript_semantics sequence collection = {} collection = append(collection,"one") collection = prepend(collection,2) ? collection -- {2,"one"}
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 ...
#Scala
Scala
implicit def toComb(m: Int) = new AnyRef { def comb(n: Int) = recurse(m, List.range(0, n)) private def recurse(m: Int, l: List[Int]): List[List[Int]] = (m, l) match { case (0, _) => List(Nil) case (_, Nil) => Nil case _ => (recurse(m - 1, l.tail) map (l.head :: _)) ::: recurse(m, l.tail) } }
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 ...
#TXR
TXR
  @(choose :shortest x) @x:@y @(or) @x<--@y @(or) @x+@y @(end)
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 ...
#UNIX_Shell
UNIX Shell
if test 3 -lt 5; then echo '3 is less than 5'; fi
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 ...
#Rust
Rust
fn egcd(a: i64, b: i64) -> (i64, i64, i64) { if a == 0 { (b, 0, 1) } else { let (g, x, y) = egcd(b % a, a); (g, y - (b / a) * x, x) } }   fn mod_inv(x: i64, n: i64) -> Option<i64> { let (g, x, _) = egcd(x, n); if g == 1 { Some((x % n + n) % n) } else { Non...
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 ...
#Scala
Scala
import scala.util.{Success, Try}   object ChineseRemainderTheorem extends App {   def chineseRemainder(n: List[Int], a: List[Int]): Option[Int] = { require(n.size == a.size) val prod = n.product   def iter(n: List[Int], a: List[Int], sm: Int): Int = { def mulInv(a: Int, b: Int): Int = { def ...
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...
#R
R
#You define a class simply by setting the class attribute of an object circS3 <- list(radius=5.5, centre=c(3, 4.2)) class(circS3) <- "circle"   #plot is a generic function, so we can define a class specific method by naming it plot.classname plot.circle <- function(x, ...) { t <- seq(0, 2*pi, length.out=200) plot...
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...
#Sidef
Sidef
func dist_squared(a, b) { sqr(a[0] - b[0]) + sqr(a[1] - b[1]) }   func closest_pair_simple(arr) { arr.len < 2 && return Inf var (a, b, d) = (arr[0, 1], dist_squared(arr[0,1])) arr.clone! while (arr) { var p = arr.pop for l in arr { var t = dist_squared(p, l) i...
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points
Circles of given radius through two points
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of circles with the point on thei...
#Python
Python
from collections import namedtuple from math import sqrt   Pt = namedtuple('Pt', 'x, y') Circle = Cir = namedtuple('Circle', 'x, y, r')   def circles_from_p1p2r(p1, p2, r): 'Following explanation at http://mathforum.org/library/drmath/view/53027.html' if r == 0.0: raise ValueError('radius of zero') ...
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...
#Tcl
Tcl
  proc cn_zodiac year { set year0 [expr $year-4] set animals {Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog Pig} set elements {Wood Fire Earth Metal Water} set stems {jia3 yi3 bing3 ding1 wu4 ji3 geng1 xin1 ren2 gui3} set gan {\u7532 \u4E59 \u4E19 \u4E01 \u620A \u5DF1 \u5E9A \u8F9B \u58E...
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 ...
#LabVIEW
LabVIEW
// local file file_exists('input.txt')   // local directory file_exists('docs')   // file in root file system (requires permissions at user OS level) file_exists('//input.txt')   // directory in root file system (requires permissions at user OS level) file_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 ...
#Lasso
Lasso
// local file file_exists('input.txt')   // local directory file_exists('docs')   // file in root file system (requires permissions at user OS level) file_exists('//input.txt')   // directory in root file system (requires permissions at user OS level) file_exists('//docs')
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a ...
#REXX
REXX
/*REXX pgm draws a Sierpinski triangle by running the chaos game with a million points*/ parse value scrsize() with sd sw . /*obtain the depth and width of screen.*/ sw= sw - 2 /*adjust the screen width down by two. */ sd= sd - 4 ...
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...
#Golfscript
Golfscript
97[]+''+p
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...
#Groovy
Groovy
printf ("%d\n", ('a' as char) as int) printf ("%c\n", 97)
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square r...
#Rust
Rust
fn cholesky(mat: Vec<f64>, n: usize) -> Vec<f64> { let mut res = vec![0.0; mat.len()]; for i in 0..n { for j in 0..(i+1){ let mut s = 0.0; for k in 0..j { s += res[i * n + k] * res[j * n + k]; } res[i * n + j] = if i == j { (mat[i * n + i] ...
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a fe...
#PHP
PHP
<?php $a = array(); # add elements "at the end" array_push($a, 55, 10, 20); print_r($a); # using an explicit key $a['one'] = 1; $a['two'] = 2; print_r($a); ?>
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 ...
#Scheme
Scheme
(define (comb m lst) (cond ((= m 0) '(())) ((null? lst) '()) (else (append (map (lambda (y) (cons (car lst) y)) (comb (- m 1) (cdr lst))) (comb m (cdr lst))))))   (comb 3 '(0 1 2 3 4))
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#Unison
Unison
factorial : Nat -> Nat factorial x = if x == 0 then 1 else x * fac (Nat.drop x 1)
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 ...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "bigint.s7i";   const func integer: modInverse (in integer: a, in integer: b) is return ord(modInverse(bigInteger conv a, bigInteger conv b));   const proc: main is func local const array integer: n is [] (3, 5, 7); const array integer: a is [] (2, 3, 2); var integer:...
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 ...
#Sidef
Sidef
func chinese_remainder(*n) { var N = n.prod func (*a) { n.range.sum { |i| var p = (N / n[i]) a[i] * p.invmod(n[i]) * p } % N } }   say chinese_remainder(3, 5, 7)(2, 3, 2)
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...
#Racket
Racket
  #lang racket   (define fish% (class object% (super-new)    ;; an instance variable & constructor argument (init-field size)    ;; a new method (define/public (eat) (displayln "gulp!"))))   ;; constructing an instance (new fish% [size 50])  
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...
#Raku
Raku
class Camel { has Int $.humps = 1; }   my Camel $a .= new; say $a.humps; # Automatically generated accessor method.   my Camel $b .= new: humps => 2; say $b.humps;
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...
#Smalltalk
Smalltalk
import Foundation   struct Point { var x: Double var y: Double   func distance(to p: Point) -> Double { let x = pow(p.x - self.x, 2) let y = pow(p.y - self.y, 2)   return (x + y).squareRoot() } }   extension Collection where Element == Point { func closestPair() -> (Point, Point)? { let (xP, x...
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...
#Racket
Racket
  #lang racket (require plot/utils)   (define (circle-centers p1 p2 r) (when (zero? r) (err "zero radius.")) (when (equal? p1 p2) (err "the points coinside."))  ; the midle point (define m (v/ (v+ p1 p2) 2))  ; the vector connecting given points (define d (v/ (v- p1 p2) 2))  ; the distance between the center...
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...
#uBasic.2F4tH
uBasic/4tH
dim @y(2) ' yin or yang dim @e(5) ' the elements dim @a(12) ' the animals   Push Dup("yang"), Dup("yin") ' fill Ying/Yang table For i = 1 to 0 step -1 : @y(i) = Pop() : Next i ' fill El...
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#LFE
LFE
  > (: filelib is_regular '"input.txt") false > (: filelib is_dir '"docs") false > (: filelib is_regular '"/input.txt") false > (: filelib is_dir '"/docs")) false  
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 ...
#Ring
Ring
  # Project : Chaos game   load "guilib.ring"   paint = null   new qapp { win1 = new qwidget() { setwindowtitle("Archimedean spiral") setgeometry(100,100,500,600) label1 = new qlabel(win1) { setgeometry(10,10,400,400) ...
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...
#Haskell
Haskell
import Data.Char   main = do print (ord 'a') -- prints "97" print (chr 97) -- prints "'a'" print (ord 'π') -- prints "960" print (chr 960) -- 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...
#Scala
Scala
case class Matrix( val matrix:Array[Array[Double]] ) {   // Assuming matrix is positive-definite, symmetric and not empty...   val rows,cols = matrix.size   def getOption( r:Int, c:Int ) : Option[Double] = Pair(r,c) match { case (r,c) if r < rows && c < rows => Some(matrix(r)(c)) case _ => None }   de...
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...
#Picat
Picat
go => L = [1,2,3,4], L2 = L ++ [[5,6,7]], % adding a list L3 = ["a string"] ++ L2, % adding a string    % Prolog way append([0],L,[5],L4).
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 ...
#Seed7
Seed7
$ include "seed7_05.s7i";   const type: combinations is array array integer;   const func combinations: comb (in array integer: arr, in integer: k) is func result var combinations: combResult is combinations.value; local var integer: x is 0; var integer: i is 0; var array integer: suffix is 0 times ...
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 ...
#V
V
[true] ['is true' puts] ['is false' puts] ifte   =is true
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 ...
#SQL
SQL
CREATE TEMPORARY TABLE inputs(remainder INT, modulus INT);   INSERT INTO inputs VALUES (2, 3), (3, 5), (2, 7);   WITH recursive   -- Multiply out the product of moduli multiplication(idx, product) AS ( SELECT 1, 1   UNION ALL   SELECT multiplication.idx+1, multiplication.product * inputs.mod...
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...
#RapidQ
RapidQ
TYPE MyClass EXTENDS QObject Variable AS INTEGER   CONSTRUCTOR Variable = 0 END CONSTRUCTOR   SUB someMethod MyClass.Variable = 1 END SUB END TYPE   ' create an instance DIM instance AS MyClass   ' invoke the method instance.someMethod
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...
#Raven
Raven
class Alpha 'I am Alpha.' as greeting define say_hello greeting print   class Beta extend Alpha 'I am Beta!' as greeting
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...
#Swift
Swift
import Foundation   struct Point { var x: Double var y: Double   func distance(to p: Point) -> Double { let x = pow(p.x - self.x, 2) let y = pow(p.y - self.y, 2)   return (x + y).squareRoot() } }   extension Collection where Element == Point { func closestPair() -> (Point, Point)? { let (xP, x...
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...
#Raku
Raku
multi sub circles (@A, @B where ([and] @A Z== @B), 0.0) { 'Degenerate point' } multi sub circles (@A, @B where ([and] @A Z== @B), $) { 'Infinitely many share a point' } multi sub circles (@A, @B, $radius) { my @middle = (@A Z+ @B) X/ 2; my @diff = @A Z- @B; my $q = sqrt [+] @diff X** 2; return 'Too fa...
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...
#UNIX_Shell
UNIX Shell
#!/usr/bin/env bash declare -A pinyin=( [甲]='jiă' [乙]='yĭ' [丙]='bĭng' [丁]='dīng' [戊]='wù' [己]='jĭ' [庚]='gēng' [辛]='xīn' [壬]='rén' [癸]='gŭi' [子]='zĭ' [丑]='chŏu' [寅]='yín' [卯]='măo' [辰]='chén' [巳]='sì' [午]='wŭ' [未]='wèi' [申]='shén' [酉]='yŏu' [戌]='xū' [亥]='hài' ) celestial=(甲 ...
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...
#UTFool
UTFool
  ··· http://rosettacode.org/wiki/Chinese_zodiac ··· ■ ChineseZodiac § static tiangan⦂ String[][]: ¤ · 10 celestial stems ¤ "甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸" ¤ "jiă", "yĭ", "bĭng", "dīng", "wù", "jĭ", "gēng", "xīn", "rén", "gŭi"   dizhi⦂ String[][]: ¤ · 12 terrestrial branches ¤ ...
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 ...
#Liberty_BASIC
Liberty BASIC
'fileExists.bas - Show how to determine if a file exists dim info$(10,10) input "Type a file path (ie. c:\windows\somefile.txt)?"; fpath$ if fileExists(fpath$) then print fpath$; " exists!" else print fpath$; " doesn't exist!" end if end   'return a true if the file in fullPath$ exists, else return false functi...
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 ...
#Run_BASIC
Run BASIC
x = int(rnd(0) * 200) y = int(rnd(0) * 173) graphic #g, 200,200 #g color("green") for i =1 TO 20000 v = int(rnd(0) * 3) + 1 if v = 1 then x = x/2 y = y/2 end if if v = 2 then x = 100 + (100-x)/2 y = 173 - (173-y)/2 end if if v = 3 then x = 200 - (200-x)/2 y = y/2 end if #g set(x,y) next render #g
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 ...
#Rust
Rust
  extern crate image; extern crate rand;   use rand::prelude::*; use std::f32;   fn main() { let max_iterations = 50_000; let img_side = 800; let tri_size = 400.0;   // Create a new ImgBuf let mut imgbuf = image::ImageBuffer::new(img_side, img_side);   // Create triangle vertices let mut ver...
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...
#HicEst
HicEst
WRITE(Messagebox) ICHAR('a'), 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...
#HolyC
HolyC
Print("%d\n", 'a'); /* prints "97" */ Print("%c\n", 97); /* prints "a" */
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square r...
#Scilab
Scilab
a = [25 15 -5; 15 18 0; -5 0 11]; chol(a) ans =   5. 3. -1. 0. 3. 1. 0. 0. 3.     a = [18 22 54 42; 22 70 86 62; 54 86 174 134; 42 62 134 106];   chol(a) ans =   4.2426407 5.1854497 12.727922 9.8994949 0. 6.5659052 3.0460385 1.6245539 0. 0. 1.64...
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...
#PicoLisp
PicoLisp
: (setq Lst (3 4 5 6)) -> (3 4 5 6)   : (push 'Lst 2) -> 2   : (push 'Lst 1) -> 1   : Lst -> (1 2 3 4 5 6)   : (insert 4 Lst 'X) -> (1 2 3 X 4 5 6)
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 ...
#SETL
SETL
print({0..4} npow 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 ...
#VBA
VBA
  Sub C_S_If() Dim A$, B$   A = "Hello" B = "World" 'test If A = B Then Debug.Print A & " = " & B 'other syntax If A = B Then Debug.Print A & " = " & B Else Debug.Print A & " and " & B & " are differents." End If 'other syntax If A = B Then Debug.Print A &...
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 ...
#Swift
Swift
import Darwin   /* * Function: euclid * Usage: (r,s) = euclid(m,n) * -------------------------- * The extended Euclidean algorithm subsequently performs * Euclidean divisions till the remainder is zero and then * returns the Bézout coefficients r and s. */   func euclid(_ m:Int, _ n:Int) -> (Int,Int) { if m ...
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 ...
#Tcl
Tcl
proc ::tcl::mathfunc::mulinv {a b} { if {$b == 1} {return 1} set b0 $b; set x0 0; set x1 1 while {$a > 1} { set x0 [expr {$x1 - ($a / $b) * [set x1 $x0]}] set b [expr {$a % [set a $b]}] } incr x1 [expr {($x1 < 0) * $b0}] } proc chineseRemainder {nList aList} { set sum 0; set prod [::tcl::matho...
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...
#REALbasic
REALbasic
  Class NumberContainer Private TheNumber As Integer Sub Constructor(InitialNumber As Integer) TheNumber = InitialNumber End Sub   Function Number() As Integer Return TheNumber End Function   Sub Number(Assigns NewNumber As Integer) TheNumber = NewNumber End Sub End Class  
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...
#REBOL
REBOL
rebol [ Title: "Classes" URL: http://rosettacode.org/wiki/Classes ]   ; Objects are derived from the base 'object!' type. REBOL uses a ; prototyping object system, so any object can be treated as a class, ; from which to derive others.   cowboy: make object! [ name: "Tex" ; Instance variable. hi: does [ ; ...
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...
#Tcl
Tcl
package require Tcl 8.5   # retrieve the x-coordinate proc x p {lindex $p 0} # retrieve the y-coordinate proc y p {lindex $p 1}   proc distance {p1 p2} { expr {hypot(([x $p1]-[x $p2]), ([y $p1]-[y $p2]))} }   proc closest_bruteforce {points} { set n [llength $points] set mindist Inf set minpts {} fo...
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...
#REXX
REXX
/*REXX pgm finds 2 circles with a specific radius given 2 (X1,Y1) and (X2,Y2) ctr points*/ @.=; @.1= 0.1234 0.9876 0.8765 0.2345 2 @.2= 0 2 0 0 1 @.3= 0.1234 0.9876 0.1234 0.9876 2 @.4= 0.1234 0.9876 0.8765 0.2345 0.5 @.5= 0.1234 0.98...
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...
#VBScript
VBScript
' Chinese zodiac - VBS Animals = array( "Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig" ) Elements = array( "Wood","Fire","Earth","Metal","Water" ) YinYang = array( "Yang","Yin" ) Years = array( 1935, 1938, 1968, 1972, 1976, 1984, 2017 )   for i = LBound(Years) to UBound...
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 ...
#Little
Little
if (exists("input.txt")) { puts("The file \"input.txt\" exist"); } if (exists("/input.txt")) { puts("The file \"/input.txt\" exist"); } if (exists("docs")) { puts("The file \"docs\" exist"); } if (exists("/docs")) { puts("The file \"/docs\" exist"); }
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 ...
#LiveCode
LiveCode
there is a file "/input.txt" there is a file "input.txt" there is a folder "docs" there is a file "/docs/input.txt"
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a ...
#Scala
Scala
import javax.swing._ import java.awt._ import java.awt.event.ActionEvent   import scala.collection.mutable import scala.util.Random   object ChaosGame extends App { SwingUtilities.invokeLater(() => new JFrame("Chaos Game") {   class ChaosGame extends JPanel { private val (dim, margin)= (new Dimensio...
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...
#Hoon
Hoon
|% ++ enc |= char=@t `@ud`char ++ dec |= code=@ud `@t`code --
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...
#i
i
software { print(number('a')) print(text([97])) }
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square r...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i"; include "math.s7i";   const type: matrix is array array float;   const func matrix: cholesky (in matrix: a) is func result var matrix: cholesky is 0 times 0 times 0.0; local var integer: i is 0; var integer: j is 0; var integer: k is 0; var floa...
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...
#PL.2FI
PL/I
  declare countries character (20) varying controlled; allocate countries initial ('Britain'); allocate countries initial ('America'); allocate countries initial ('Argentina');  
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 ...
#Sidef
Sidef
combinations(5, 3, {|*c| say c })
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 ...
#VBScript
VBScript
If condition1 Then statement End If   If condition1 Then statement ElseIf condition2 Then statement ... ElseIf conditionN Then statement Else statement End If  
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 ...
#uBasic.2F4tH
uBasic/4tH
@(000) = 3 : @(001) = 5 : @(002) = 7 @(100) = 2 : @(101) = 3 : @(102) = 2   Print Func (_Chinese_Remainder (3))   ' -------------------------------------   @(000) = 11 : @(001) = 12 : @(002) = 13 @(100) = 10 : @(101) = 04 : @(102) = 12   Print Func (_Chinese_Remainder (3))   ' -------------------------------------   En...
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...
#Ring
Ring
  New point { x=10 y=20 z=30 print() } Class Point x y z func print see x + nl + y + nl + z + nl