task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, a... | #Ruby | Ruby | class MyClass
def initialize
@instance_var = 0
end
def add_1
@instance_var += 1
end
end
my_class = MyClass.new #allocates an object and calls it's initialize method, then returns it.
|
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... | #Ursala | Ursala | #import flo
clop = @iiK0 fleq$-&l+ *EZF ^\~& plus+ sqr~~+ minus~~bbI |
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... | #Ring | Ring |
# Project : Circles of given radius through two points
decimals(4)
x1 = 0.1234
y1 = 0.9876
x2 = 0.8765
y2 = 0.2345
r = 2.0
see "1 : " + x1 + " " + y1 + " " + x2 + " " + y2 + " " + r + nl
twocircles(x1, y1, x2, y2, r)
x1 = 0.0000
y1 = 2.0000
x2 = 0.0000
y2 = 0.0000
r = 1.0
see "2 : " + x1 + " " + y1 + " " + x2 + "... |
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... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
ReadOnly ANIMALS As String() = {"Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"}
ReadOnly ELEMENTS As String() = {"Wood", "Fire", "Earth", "Metal", "Water"}
ReadOnly ANIMAL_CHARS As String() = {"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申"... |
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 ... | #Logo | Logo | show file? "input.txt
show file? "/input.txt
show file? "docs
show file? "/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 ... | #Lua | Lua | function output( s, b )
if b then
print ( s, " does not exist." )
else
print ( s, " does exist." )
end
end
output( "input.txt", io.open( "input.txt", "r" ) == nil )
output( "/input.txt", io.open( "/input.txt", "r" ) == nil )
output( "docs", io.open( "docs", "r" ) == nil )
output( "/d... |
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 ... | #Scilab | Scilab | //Input
n_sides = 3;
side_length = 1;
ratio = 0.5;
n_steps = 1.0d5;
first_step = 0;
if n_sides<3 then
error("n_sides should be at least 3.");
end
//Calculating vertices' positions
theta = (2 * %pi) / n_sides;
alpha = (180 - (360/n_sides)) / 2 * (%pi/180);
radius = (sin(theta) / side_length) / sin(alpha);
vertic... |
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 ... | #Sidef | Sidef | require('Imager')
var width = 600
var height = 600
var points = [
[width//2, 0],
[ 0, height-1],
[height-1, height-1],
]
var img = %O|Imager|.new(
xsize => width,
ysize => height,
)
var color = %O|Imager::Color|.new('#ff0... |
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... | #Icon_and_Unicon | Icon and Unicon | procedure main(arglist)
if *arglist > 0 then L := arglist else L := [97, "a"]
every x := !L do
write(x, " ==> ", char(integer(x)) | ord(x) ) # char produces a character, ord produces a number
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... | #Io | Io | "a" at(0) println // --> 97
97 asCharacter println // --> a
"π" at(0) println // --> 960
960 asCharacter println // --> π |
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... | #Sidef | Sidef | func cholesky(matrix) {
var chol = matrix.len.of { matrix.len.of(0) }
for row in ^matrix {
for col in (0..row) {
var x = matrix[row][col]
for i in (0..col) {
x -= (chol[row][i] * chol[col][i])
}
chol[row][col] = (row == col ? x.sqrt : x/cho... |
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... | #PowerShell | PowerShell |
# Create an Array by separating the elements with commas:
$array = "one", 2, "three", 4
# Using explicit syntax:
$array = @("one", 2, "three", 4)
# Send the values back into individual variables:
$var1, $var2, $var3, $var4 = $array
# An array of several integer ([int]) values:
$array = 0, 1, 2, 3, 4, 5, 6, 7
... |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
... | #Smalltalk | Smalltalk |
(0 to: 4) combinations: 3 atATimeDo: [ :x | Transcript cr; show: x printString].
"output on Transcript:
#(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)"
|
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 ... | #Verbexx | Verbexx | @VAR a b = 1 2;
// -------------------------------------------------------------------------------------
// @IF verb (returns 0u0 = UNIT, if no then: or else: block is executed)
// ======== (note: both then: and else: keywords are optional)
@SAY "@IF 1 " ( @IF (a > b) then:{"then:"} 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
... | #VBA | VBA | Private Function chinese_remainder(n As Variant, a As Variant) As Variant
Dim p As Long, prod As Long, tot As Long
prod = 1: tot = 0
For i = 1 To UBound(n)
prod = prod * n(i)
Next i
Dim m As Variant
For i = 1 To UBound(n)
p = prod / n(i)
m = mul_inv(p, n(i))
If Wo... |
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... | #Rust | Rust |
struct MyClass {
variable: i32, // member variable = instance variable
}
impl MyClass {
// member function = method, with its implementation
fn some_method(&mut self) {
self.variable = 1;
}
// constructor, with its implementation
fn new() -> MyClass {
// Here could be more ... |
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... | #VBA | VBA | Option Explicit
Private Type MyPoint
X As Single
Y As Single
End Type
Private Type MyPair
p1 As MyPoint
p2 As MyPoint
End Type
Sub Main()
Dim points() As MyPoint, i As Long, BF As MyPair, d As Single, Nb As Long
Dim T#
Randomize Timer
Nb = 10
Do
ReDim points(1 To Nb)
For 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... | #Ruby | Ruby | Pt = Struct.new(:x, :y)
Circle = Struct.new(:x, :y, :r)
def circles_from(pt1, pt2, r)
raise ArgumentError, "Infinite number of circles, points coincide." if pt1 == pt2 && r > 0
# handle single point and r == 0
return [Circle.new(pt1.x, pt1.y, r)] if pt1 == pt2 && r == 0
dx, dy = pt2.x - pt1.x, pt2.y - pt1... |
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... | #Vlang | Vlang | const (
animal_string = ["Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake",
"Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"]
stem_yy_string = ["Yang", "Yin"]
element_string = ["Wood", "Fire", "Earth", "Metal", "Water"]
stem_ch = "甲乙丙丁戊己庚辛壬癸".split('')
branch_ch = "子丑寅卯辰巳午未申酉戌... |
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... | #Wren | Wren | import "/fmt" for Fmt
class ChineseZodiac {
static init() {
__animals = ["Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake",
"Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"]
__aspects = ["Yang","Yin"]
__elements = ["Wood", "Fire", "Earth", "Metal", "Water"]
__stems ... |
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 ... | #M2000_Interpreter | M2000 Interpreter |
Module ExistDirAndFile {
Let WorkingDir$=Dir$, RootDir$="C:\"
task(WorkingDir$)
task(RootDir$)
Dir User ' return to user directroy
Sub task(WorkingDir$)
Local counter
Dir WorkingDir$
If Not Exist.Dir("docs") then Report "docs not exist in "+Workin... |
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 ... | #Maple | Maple | with(FileTools):
Exists("input.txt");
Exists("docs") and IsDirectory("docs");
Exists("/input.txt");
Exists("/docs") and IsDirectory("/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 ... | #Simula | Simula | BEGIN
INTEGER U, COLUMNS, LINES;
COLUMNS := 40;
LINES := 80;
U := ININT;
BEGIN
CHARACTER ARRAY SCREEN(0:LINES, 0:COLUMNS);
INTEGER X, Y, I, VERTEX;
FOR X := 0 STEP 1 UNTIL LINES-1 DO
FOR Y := 0 STEP 1 UNTIL COLUMNS-1 DO
SCREEN(X, Y) := ' ';
... |
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 ... | #Wren | Wren | import "dome" for Window
import "graphics" for Canvas, Color
import "math" for Point
import "random" for Random
import "./dynamic" for Tuple
import "./seq" for Stack
var ColoredPoint = Tuple.create("ColoredPoint", ["x", "y", "colorIndex"])
class ChaosGame {
construct new(width, height) {
Window.resize(w... |
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... | #J | J | 4 u: 97 98 99 9786
abc☺
3 u: 7 u: 'abc☺'
97 98 99 9786 |
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... | #Smalltalk | Smalltalk |
FloatMatrix>>#cholesky
| l |
l := FloatMatrix zero: numRows.
1 to: numRows do: [:i |
1 to: i do: [:k | | rowSum lkk factor aki partialSum |
i = k
ifTrue: [
rowSum := (1 to: k - 1) sum: [:j | | lkj |
lkj := l at: j @ k.
lkj squared].
lkk := (self at: k @ k) - rowSum.
lkk := lkk ... |
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... | #Prolog | Prolog | % create a list
L = [a,b,c,d],
% prepend to the list
L2 = [before_a|L],
% append to the list
append(L2, ['Hello'], L3),
% delete from list
exclude(=(b), L3, 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
... | #SPAD | SPAD |
[reverse subSet(5,3,i)$SGCF for i in 0..binomial(5,3)-1]
[[0,1,2], [0,1,3], [0,2,3], [1,2,3], [0,1,4], [0,2,4], [1,2,4], [0,3,4],
[1,3,4], [2,3,4]]
Type: List(List(Integer))
|
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include ... | #Verilog | Verilog |
if( expr_booleana ) command1;
else command2;
|
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 ... | #Visual_Basic | Visual Basic | If condition Then
statement
End If
If condition Then
statement
Else
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
... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function ModularMultiplicativeInverse(a As Integer, m As Integer) As Integer
Dim b = a Mod m
For x = 1 To m - 1
If (b * x) Mod m = 1 Then
Return x
End If
Next
Return 1
End Function
Function Solve(n As Integer(), a As ... |
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... | #Sather | Sather | class CLASSTEST is
readonly attr x:INT; -- give a public getter, not a setter
private attr y:INT; -- no getter, no setter
attr z:INT; -- getter and setter
-- constructor
create(x, y, z:INT):CLASSTEST is
res :CLASSTEST := new; -- or res ::= new
res.x := x;
res.y := y;
res.z := 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... | #Scala | Scala | /** This class implicitly includes a constructor which accepts an Int and
* creates "val variable1: Int" with that value.
*/
class MyClass(val myMethod: Int) { // Acts like a getter, getter automatically generated.
var variable2 = "asdf" // Another instance variable; a public var this time
def this() = this(0) /... |
http://rosettacode.org/wiki/Closest-pair_problem | Closest-pair problem |
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a function to find the closest two p... | #Visual_FoxPro | Visual FoxPro |
CLOSE DATABASES ALL
CREATE CURSOR pairs(id I, xcoord B(6), ycoord B(6))
INSERT INTO pairs VALUES (1, 0.654682, 0.925557)
INSERT INTO pairs VALUES (2, 0.409382, 0.619391)
INSERT INTO pairs VALUES (3, 0.891663, 0.888594)
INSERT INTO pairs VALUES (4, 0.716629, 0.996200)
INSERT INTO pairs VALUES (5, 0.477721, 0.946355)
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... | #Run_BASIC | Run BASIC |
html "<TABLE border=1>"
html "<tr bgcolor=wheat align=center><td>No.</td><td>x1</td><td>y1</td><td>x2</td><td>y2</td><td>r</td><td>cir x1</td><td>cir y1</td><td>cir x2</td><td>cir y2</td></tr>"
for i = 1 to 5
read x1, y1, x2, y2,r
html "<tr align=right><td>";i;"</td><td>";x1;"</td><td>";y1;"</td><td>";x2;"</td><t... |
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo... | #Yabasic | Yabasic |
dim Animals$(12) : for a = 0 to 11 : read Animals$(a) : next a
dim Elements$(5) : for a = 0 to 4 : read Elements$(a): next a
dim YinYang$(2) : for a = 0 to 1 : read YinYang$(a) : next a
dim Years(7) : for a = 0 to 6 : read Years(a) : next a
for i = 0 to arraysize(Years(),1)-1
xYear = Years(i)
yEleme... |
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 ... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | wd = NotebookDirectory[];
FileExistsQ[wd <> "input.txt"]
DirectoryQ[wd <> "docs"]
FileExistsQ["/" <> "input.txt"]
DirectoryQ["/" <> "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 ... | #X86_Assembly | X86 Assembly | 1 ;Assemble with: tasm, tlink /t
2 0000 .model tiny
3 0000 .code
4 .386
5 org 100h
6 ... |
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... | #Java | Java | public class Foo {
public static void main(String[] args) {
System.out.println((int)'a'); // prints "97"
System.out.println((char)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... | #Stata | Stata | mata
: a=25,15,-5\15,18,0\-5,0,11
: a
[symmetric]
1 2 3
+----------------+
1 | 25 |
2 | 15 18 |
3 | -5 0 11 |
+----------------+
: cholesky(a)
1 2 3
+----------------+
1 | 5 0 0 |
2 | 3 3 0 |
3 | -1 1 3 |
+... |
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... | #PureBasic | PureBasic | Dim Text.s(9)
Text(3)="Hello"
Text(7)="World!" |
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
... | #Standard_ML | Standard ML | fun comb (0, _ ) = [[]]
| comb (_, [] ) = []
| comb (m, x::xs) = map (fn y => x :: y) (comb (m-1, xs)) @
comb (m, xs)
;
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 ... | #Visual_Basic_.NET | Visual Basic .NET | Dim result As String, a As String = "pants", b As String = "glasses"
If a = b Then
result = "passed"
Else
result = "failed"
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
... | #Wren | Wren | /* returns x where (a * x) % b == 1 */
var mulInv = Fn.new { |a, b|
if (b == 1) return 1
var b0 = b
var x0 = 0
var x1 = 1
while (a > 1) {
var q = (a/b).floor
var t = b
b = a % b
a = t
t = x0
x0 = x1 - q*x0
x1 = t
}
if (x1 < 0) x1 = x1 +... |
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... | #Scheme | Scheme | (define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds"))
(define (deposit amount)
(set! balance (+ balance amount))
balance)
(define (dispatch m)
(cond ((eq? m 'withdraw) withdraw)
((eq? m 'd... |
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... | #Wren | Wren | import "/math" for Math
import "/sort" for Sort
var distance = Fn.new { |p1, p2| Math.hypot(p1[0] - p2[0], p1[1] - p2[1]) }
var bruteForceClosestPair = Fn.new { |p|
var n = p.count
if (n < 2) Fiber.abort("There must be at least two points.")
var minPoints = [p[0], p[1]]
var minDistance = distance.ca... |
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... | #Rust | Rust | use std::fmt;
#[derive(Clone,Copy)]
struct Point {
x: f64,
y: f64
}
fn distance (p1: Point, p2: Point) -> f64 {
((p1.x - p2.x).powi(2) + (p1.y - p2.y).powi(2)).sqrt()
}
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({:.4}, {:.4})", self.x, ... |
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo... | #zkl | zkl | fcn ceToChineseZodiac(ce_year){ // --> list of strings
# encoding: utf-8
var [const] pinyin=SD( // create some static variables, SD is small fixed dictionary
"甲","jiă", "乙","yĭ", "丙","bĭng", "丁","dīng", "戊","wù", "己","jĭ",
"庚","gēng", "辛","xīn", "壬","rén", "癸","gŭi",
"子","zĭ", "丑","chŏu", "寅... |
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 ... | #MATLAB_.2F_Octave | MATLAB / Octave | exist('input.txt','file')
exist('/input.txt','file')
exist('docs','dir')
exist('/docs','dir') |
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 ... | #MAXScript | MAXScript | -- Here
doesFileExist "input.txt"
(getDirectories "docs").count == 1
-- Root
doesFileExist "\input.txt"
(getDirectories "C:\docs").count == 1 |
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 ... | #XPL0 | XPL0 | int Tx, Ty, X, Y, R;
[SetVid($12); \640x480x4 graphics
Tx:= [320, 320-277, 320+277]; \equilateral triangle
Ty:= [0, 479, 479]; \277 = 480 / (2*Sin(60))
X:= Ran(640); \random starting point
Y:= Ran(480);
repeat R:= Ran(3); \select random triangle point
... |
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 ... | #Yabasic | Yabasic | width = 640 : height = 480
open window width, height
window origin "lb"
x = ran(width)
y = ran(height)
for i = 1 to 200000
vertex = int(ran(3))
if vertex = 1 then
x = width / 2 + (width / 2 - x) / 2
y = height - (height - y) / 2
elseif vertex = 2 then
x = width - (width - x) / 2
... |
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... | #JavaScript | JavaScript | console.log('a'.charCodeAt(0)); // prints "97"
console.log(String.fromCharCode(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... | #Swift | Swift | func cholesky(matrix: [Double], n: Int) -> [Double] {
var res = [Double](repeating: 0, count: matrix.count)
for i in 0..<n {
for j in 0..<i+1 {
var s = 0.0
for k in 0..<j {
s += res[i * n + k] * res[j * n + k]
}
if i == j {
res[i * n + j] = (matrix[i * n + i] - s).s... |
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... | #Python | Python | collection = [0, '1'] # Lists are mutable (editable) and can be sorted in place
x = collection[0] # accessing an item (which happens to be a numeric 0 (zero)
collection.append(2) # adding something to the end of the list
collection.insert(0, '-1') # insert... |
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
... | #Stata | Stata | program combin
tempfile cp
tempvar k
gen `k'=1
quietly save "`cp'"
rename `1' `1'1
forv i=2/`2' {
joinby `k' using "`cp'"
rename `1' `1'`i'
quietly drop if `1'`i'<=`1'`=`i'-1'
}
sort `1'*
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 ... | #Vlang | Vlang | if boolean_expression {
statements
} |
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
... | #zkl | zkl | var BN=Import("zklBigNum"), one=BN(1);
fcn crt(xs,ys){
p:=xs.reduce('*,BN(1));
X:=BN(0);
foreach x,y in (xs.zip(ys)){
q:=p/x;
z,s,_:=q.gcdExt(x);
if(z!=one) throw(Exception.ValueError("%d not coprime".fmt(x)));
X+=y*s*q;
}
return(X % p);
} |
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
... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 DIM n(3): DIM a(3)
20 FOR i=1 TO 3
30 READ n(i),a(i)
40 NEXT i
50 DATA 3,2,5,3,7,2
100 LET prod=1: LET sum=0
110 FOR i=1 TO 3: LET prod=prod*n(i): NEXT i
120 FOR i=1 TO 3
130 LET p=INT (prod/n(i)): LET a=p: LET b=n(i)
140 GO SUB 1000
150 LET sum=sum+a(i)*x1*p
160 NEXT i
170 PRINT FN m(sum,prod)
180 STOP
200 DEF FN ... |
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... | #Sidef | Sidef | class MyClass(instance_var) {
method add(num) {
instance_var += num;
}
}
var obj = MyClass(3); # `instance_var` will be set to 3
obj.add(5); # calls the add() method
say obj.instance_var; # prints the value of `instance_var`: 8 |
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... | #Simula | Simula | BEGIN
CLASS MyClass(instanceVariable);
INTEGER instanceVariable;
BEGIN
PROCEDURE doMyMethod(n);
INTEGER n;
BEGIN
Outint(instanceVariable, 5);
Outtext(" + ");
Outint(n, 5);
Outtext(" = ");
Outint(instanceVariable + n, 5);
... |
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... | #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
proc ClosestPair(P, N); \Show closest pair of points in array P
real P; int N;
real Dist2, MinDist2;
int I, J, SI, SJ;
[MinDist2:= 1e300;
for I:= 0 to N-2 do
[for J:= I+1 to N-1 do
[Dist2:= sq(P(I,0)-P(J,0)) + sq(P(I,1)-P(J,1));
... |
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points | Circles of given radius through two points |
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
Exceptions
r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
If the points are coincident then an infinite number of circles with the point on thei... | #Scala | Scala | import org.scalatest.FunSuite
import math._
case class V2(x: Double, y: Double) {
val distance = hypot(x, y)
def /(other: V2) = V2((x+other.x) / 2.0, (y+other.y) / 2.0)
def -(other: V2) = V2(x-other.x,y-other.y)
override def equals(other: Any) = other match {
case p: V2 => abs(x-p.x) < 0.0001 && abs(y-p.... |
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 ... | #Modula-3 | Modula-3 | MODULE FileTest EXPORTS Main;
IMPORT IO, Fmt, FS, File, OSError, Pathname;
PROCEDURE FileExists(file: Pathname.T): BOOLEAN =
VAR status: File.Status;
BEGIN
TRY
status := FS.Status(file);
RETURN TRUE;
EXCEPT
| OSError.E => RETURN FALSE;
END;
END FileExists;
BEGIN
IO.Put(Fmt.Bool... |
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 ... | #Z80_Assembly | Z80 Assembly | VREG: equ 99h ; VDP register port
VR0: equ 0F3DFh ; Copy of VDP R0 in memory
VR1: equ 0F3E0h ; Copy of VDP R1 in memory
NEWKEY: equ 0FBE5h ; MSX BIOS puts key data here
VDP: equ 98h ; VDP data port
ROM: equ 0FCC0h ; Main ROM slot
JIFFY: equ 0FCE9h ; BIOS timer
calslt: equ 1Ch ; Interslot call routine
initxt: equ 6Ch ; ... |
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... | #Joy | Joy | 'a ord.
97 chr. |
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... | #jq | jq | "a" | explode # => [ 97 ]
[97] | implode # => "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... | #Tcl | Tcl | proc cholesky a {
set m [llength $a]
set n [llength [lindex $a 0]]
set l [lrepeat $m [lrepeat $n 0.0]]
for {set i 0} {$i < $m} {incr i} {
for {set k 0} {$k < $i+1} {incr k} {
set sum 0.0
for {set j 0} {$j < $k} {incr j} {
set sum [expr {$sum + [lindex $l $i $j] * [lindex $l $k $j]}]
}
... |
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... | #R | R | numeric(5)
1:10
c(1, 3, 6, 10, 7 + 8, sqrt(441)) |
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
... | #Swift | Swift | func addCombo(prevCombo: [Int], var pivotList: [Int]) -> [([Int], [Int])] {
return (0..<pivotList.count)
.map {
_ -> ([Int], [Int]) in
(prevCombo + [pivotList.removeAtIndex(0)], pivotList)
}
}
func combosOfLength(n: Int, m: Int) -> [[Int]] {
return [Int](1...m)
.reduce([([Int](), [Int](0... |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include ... | #Vorpal | Vorpal | if(condition){
result = 'met'
}
else{
result = 'not 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... | #Slate | Slate | prototypes define: #MyPrototype &parents: {Cloneable} &slots: #(instanceVar).
MyPrototype traits addSlot: #classVar.
x@(MyPrototype traits) new
[
x clone `>> [instanceVar: 0. ]
].
x@(MyPrototype traits) someMethod
[
x instanceVar = 1 /\ (x classVar = 3)
]. |
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... | #Smalltalk | Smalltalk | Object subclass: #MyClass
instanceVariableNames: 'instanceVar'
classVariableNames: 'classVar'
poolDictionaries: ''
category: 'Testing' !
!MyClass class methodsFor: 'instance creation'!
new
^self basicNew instanceVar := 0 ! !
!MyClass methodsFor: 'testing'!
someMethod
^self instanceVar = 1; classVar = 3... |
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... | #Yabasic | Yabasic |
minDist = 1^30
dim x(9), y(9)
x(0) = 0.654682 : y(0) = 0.925557
x(1) = 0.409382 : y(1) = 0.619391
x(2) = 0.891663 : y(2) = 0.888594
x(3) = 0.716629 : y(3) = 0.996200
x(4) = 0.477721 : y(4) = 0.946355
x(5) = 0.925092 : y(5) = 0.818220
x(6) = 0.624291 : y(6) = 0.142924
x(7) = 0.211332 : y(7) = 0.221507
x(8) = 0.293786 ... |
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... | #Scheme | Scheme |
(import (scheme base)
(scheme inexact)
(scheme write))
;; c1 and c2 are pairs (x y), r a positive radius
(define (find-circles c1 c2 r)
(define x-coord car) ; for easier to read coordinate extraction from list
(define y-coord cadr)
(define (approx= a b) (< (- a b) 0.000001)) ; equal within tol... |
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 ... | #Nanoquery | Nanoquery | import Nanoquery.IO
def exists(fname)
f = new(File, fname)
return f.exists()
end |
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 ... | #Neko | Neko | /**
Check that file/dir exists, in Neko
*/
var sys_exists = $loader.loadprim("std@sys_exists", 1)
var sys_file_type = $loader.loadprim("std@sys_file_type", 1)
var sys_command = $loader.loadprim("std@sys_command", 1)
var name = "input.txt"
$print(name, " exists as file: ", sys_exists(name), "\n")
$print(name = "d... |
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 ... | #zkl | zkl | w,h:=640,640;
bitmap:=PPM(w,h,0xFF|FF|FF); // White background
colors:=T(0xFF|00|00,0x00|FF|00,0x00|00|FF); // red,green,blue
margin,size:=60, w - 2*margin;
points:=T(T(w/2, margin), T(margin,size), T(margin + size,size) );
N,done:=Atomic.Int(0),Atomic.Bool(False);
Thread.HeartBeat('wrap(hb){ // a thread
var... |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out... | #Julia | Julia | println(Int('a'))
println(Char(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... | #VBA | VBA | Function Cholesky(Mat As Range) As Variant
Dim A() As Double, L() As Double, sum As Double, sum2 As Double
Dim m As Byte, i As Byte, j As Byte, k As Byte
'Ensure matrix is square
If Mat.Rows.Count <> Mat.Columns.Count Then
MsgBox ("Correlation matrix is not square")
Exit Function
End If
... |
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... | #Racket | Racket |
#lang racket
;; create a list
(list 1 2 3 4)
;; create a list of size N
(make-list 100 0)
;; add an element to the front of a list (non-destructively)
(cons 1 (list 2 3 4))
|
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
... | #Tcl | Tcl | proc comb {m n} {
set set [list]
for {set i 0} {$i < $n} {incr i} {lappend set $i}
return [combinations $set $m]
}
proc combinations {list size} {
if {$size == 0} {
return [list [list]]
}
set retval {}
for {set i 0} {($i + $size) <= [llength $list]} {incr i} {
set firstElemen... |
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 ... | #Woma | Woma | <%>condition |
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... | #SuperCollider | SuperCollider |
SpecialObject {
classvar a = 42, <b = 0, <>c; // Class variables. 42 and 0 are default values.
var <>x, <>y; // Instance variables.
// Note: variables are private by default. In the above, "<" creates a getter, ">" creates a setter
*new { |value|
^super.new.init(value) // constructo... |
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... | #zkl | zkl | class Point{
fcn init(_x,_y){ var[const] x=_x, y=_y; }
fcn distance(p){ (p.x-x).hypot(p.y-y) }
fcn toString { String("Point(",x,",",y,")") }
}
// find closest two points using brute ugly force:
// find all combinations of two points, measure distance, pick smallest
fcn closestPoints(points){
pairs... |
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
include "math.s7i";
const type: point is new struct
var float: x is 0.0;
var float: y is 0.0;
end struct;
const func point: point (in float: x, in float: y) is func
result
var point: aPoint is point.value;
begin
aPoint.x := x;
aPoint.y := ... |
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 ... | #Nemerle | Nemerle | using System.Console;
using System.IO;
WriteLine(File.Exists("input.txt"));
WriteLine(File.Exists("/input.txt"));
WriteLine(Directory.Exists("docs"));
WriteLine(Directory.Exists("/docs")); |
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... | #K | K | _ic "abcABC"
97 98 99 65 66 67
_ci 97 98 99 65 66 67
"abcABC" |
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... | #Kotlin | Kotlin | fun main(args: Array<String>) {
var c = 'a'
var i = c.toInt()
println("$c <-> $i")
i += 2
c = i.toChar()
println("$i <-> $c")
} |
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... | #Vlang | Vlang | import math
// Symmetric and Lower use a packed representation that stores only
// the Lower triangle.
struct Symmetric {
order int
ele []f64
}
struct Lower {
mut:
order int
ele []f64
}
// Symmetric.print prints a square matrix from the packed representation,
// printing the upper triange 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... | #Raku | Raku | # Array
my @array = 1,2,3;
@array.push: 4,5,6;
# Hash
my %hash = 'a' => 1, 'b' => 2;
%hash<c d> = 3,4;
%hash.push: 'e' => 5, 'f' => 6;
# SetHash
my $s = SetHash.new: <a b c>;
$s ∪= <d e f>;
# BagHash
my $b = BagHash.new: <b a k l a v a>;
$b ⊎= <a b c>; |
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
... | #TXR | TXR | (defun comb-n-m (n m)
(comb (range* 0 n) m))
(put-line `3 comb 5 = @(comb-n-m 5 3)`) |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include ... | #Wrapl | Wrapl | condition => success // failure
condition => success
condition // failure |
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... | #Swift | Swift | class MyClass{
// stored property
var variable : Int
/**
* The constructor
*/
init() {
self.variable = 42
}
/**
* A method
*/
func someMethod() {
self.variable = 1
}
} |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, a... | #Tcl | Tcl | package require TclOO
oo::class create summation {
variable v
constructor {} {
set v 0
}
method add x {
incr v $x
}
method value {} {
return $v
}
destructor {
puts "Ended with value $v"
}
}
set sum [summation new]
puts "Start with [$sum value]"
for {se... |
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... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 DIM x(10): DIM y(10)
20 FOR i=1 TO 10
30 READ x(i),y(i)
40 NEXT i
50 LET min=1e30
60 FOR i=1 TO 9
70 FOR j=i+1 TO 10
80 LET p1=x(i)-x(j): LET p2=y(i)-y(j): LET dsq=p1*p1+p2*p2
90 IF dsq<min THEN LET min=dsq: LET mini=i: LET minj=j
100 NEXT j
110 NEXT i
120 PRINT "Closest pair is ";mini;" and ";minj;" at distance ";S... |
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... | #Sidef | Sidef | func circles(a, b, r) {
if (a == b) {
if (r == 0) {
return ['Degenerate point']
}
else {
return ['Infinitely many share a point']
}
}
var h = (b-a)/2
if (r**2 < h.norm) {
return ['Too far apart']
}
var l = sqrt(r**2 - h.norm... |
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 ... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols binary
runSample(arg)
return
-- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
method isExistingFile(fn) public static returns boolean
ff = File(fn)
fExists = ff.exists() & ff.isFile()
return fExists
-- . . . ... |
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... | #LabVIEW | LabVIEW | : CHAR "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[" comb
'\\ comb -1 remove append "]^_`abcdefghijklmnopqrstuvwxyz{|}~" comb append ;
: CODE 95 iota 33 + ; : comb "" split ;
: extract' rot 1 compress index subscript expand drop ;
: chr CHAR CODE extract' ;
: ord CODE CHAR ... |
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... | #Lang5 | Lang5 | : CHAR "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[" comb
'\\ comb -1 remove append "]^_`abcdefghijklmnopqrstuvwxyz{|}~" comb append ;
: CODE 95 iota 33 + ; : comb "" split ;
: extract' rot 1 compress index subscript expand drop ;
: chr CHAR CODE extract' ;
: ord CODE CHAR ... |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.