task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square root of
A
{\displaystyle A}
, as described in Cholesky decomposition.
In a 3x3 example, we have to solve the following system of equations:
A
=
(
a
11
a
21
a
31
a
21
a
22
a
32
a
31
a
32
a
33
)
=
(
l
11
0
0
l
21
l
22
0
l
31
l
32
l
33
)
(
l
11
l
21
l
31
0
l
22
l
32
0
0
l
33
)
≡
L
L
T
=
(
l
11
2
l
21
l
11
l
31
l
11
l
21
l
11
l
21
2
+
l
22
2
l
31
l
21
+
l
32
l
22
l
31
l
11
l
31
l
21
+
l
32
l
22
l
31
2
+
l
32
2
+
l
33
2
)
{\displaystyle {\begin{aligned}A&={\begin{pmatrix}a_{11}&a_{21}&a_{31}\\a_{21}&a_{22}&a_{32}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}\\&={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}l_{11}&l_{21}&l_{31}\\0&l_{22}&l_{32}\\0&0&l_{33}\end{pmatrix}}\equiv LL^{T}\\&={\begin{pmatrix}l_{11}^{2}&l_{21}l_{11}&l_{31}l_{11}\\l_{21}l_{11}&l_{21}^{2}+l_{22}^{2}&l_{31}l_{21}+l_{32}l_{22}\\l_{31}l_{11}&l_{31}l_{21}+l_{32}l_{22}&l_{31}^{2}+l_{32}^{2}+l_{33}^{2}\end{pmatrix}}\end{aligned}}}
We can see that for the diagonal elements (
l
k
k
{\displaystyle l_{kk}}
) of
L
{\displaystyle L}
there is a calculation pattern:
l
11
=
a
11
{\displaystyle l_{11}={\sqrt {a_{11}}}}
l
22
=
a
22
−
l
21
2
{\displaystyle l_{22}={\sqrt {a_{22}-l_{21}^{2}}}}
l
33
=
a
33
−
(
l
31
2
+
l
32
2
)
{\displaystyle l_{33}={\sqrt {a_{33}-(l_{31}^{2}+l_{32}^{2})}}}
or in general:
l
k
k
=
a
k
k
−
∑
j
=
1
k
−
1
l
k
j
2
{\displaystyle l_{kk}={\sqrt {a_{kk}-\sum _{j=1}^{k-1}l_{kj}^{2}}}}
For the elements below the diagonal (
l
i
k
{\displaystyle l_{ik}}
, where
i
>
k
{\displaystyle i>k}
) there is also a calculation pattern:
l
21
=
1
l
11
a
21
{\displaystyle l_{21}={\frac {1}{l_{11}}}a_{21}}
l
31
=
1
l
11
a
31
{\displaystyle l_{31}={\frac {1}{l_{11}}}a_{31}}
l
32
=
1
l
22
(
a
32
−
l
31
l
21
)
{\displaystyle l_{32}={\frac {1}{l_{22}}}(a_{32}-l_{31}l_{21})}
which can also be expressed in a general formula:
l
i
k
=
1
l
k
k
(
a
i
k
−
∑
j
=
1
k
−
1
l
i
j
l
k
j
)
{\displaystyle l_{ik}={\frac {1}{l_{kk}}}\left(a_{ik}-\sum _{j=1}^{k-1}l_{ij}l_{kj}\right)}
Task description
The task is to implement a routine which will return a lower Cholesky factor
L
{\displaystyle L}
for every given symmetric, positive definite nxn matrix
A
{\displaystyle A}
. You should then test it on the following two examples and include your output.
Example 1:
25 15 -5 5 0 0
15 18 0 --> 3 3 0
-5 0 11 -1 1 3
Example 2:
18 22 54 42 4.24264 0.00000 0.00000 0.00000
22 70 86 62 --> 5.18545 6.56591 0.00000 0.00000
54 86 174 134 12.72792 3.04604 1.64974 0.00000
42 62 134 106 9.89949 1.62455 1.84971 1.39262
Note
The Cholesky decomposition of a Pascal upper-triangle matrix is the Identity matrix of the same size.
The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size. | #Wren | Wren | import "/matrix" for Matrix
import "/fmt" for Fmt
var arrays = [
[ [25, 15, -5],
[15, 18, 0],
[-5, 0, 11] ],
[ [18, 22, 54, 42],
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106] ]
]
for (array in arrays) {
System.print("Original:")
Fmt.mprint(array, 3, 0)
System.print("\nLower Cholesky factor:")
Fmt.mprint(Matrix.new(array).cholesky(), 8, 5)
System.print()
} |
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 few values to it.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Raven | Raven | [ 1 2 3 'abc' ] as a_list
a_list print
list (4 items)
0 => 1
1 => 2
2 => 3
3 => "abc" |
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
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Ursala | Ursala | choices = ^(iota@r,~&l); leql@a^& ~&al?\&! ~&arh2fabt2RDfalrtPXPRT |
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 if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #Wren | Wren | for (b in [true, false]) {
if (b) {
System.print(true)
} else {
System.print(false)
}
// equivalent code using ternary operator
System.print(b ? true : false)
// equivalent code using && operator
System.print(b && true)
// equivalent code using || operator
System.print(b || false)
System.print()
} |
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, as a type, has the values and operations of its own.
The operations of are usually called methods of the root type.
Both operations and values are called polymorphic.
A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument.
The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual.
Operations with multiple arguments and/or the results of the class are called multi-methods.
A further generalization of is the operation with arguments and/or results from different classes.
single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x).
multiple-dispatch languages allow many arguments and/or results to control the dispatch.
A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type.
This type is sometimes called the most specific type of a [polymorphic] value.
The type tag of the value is used in order to resolve the dispatch.
The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class.
In many OO languages
the type of the class of T and T itself are considered equivalent.
In some languages they are distinct (like in Ada).
When class T and T are equivalent, there is no way to distinguish
polymorphic and specific values.
Task
Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
| #TIScript | TIScript | class Car
{
//Constructor function.
function this(brand, weight, price = 0) {
this.brand = brand;
this.weight = weight || 1000; // Resort to default value (with 'or' notation).
this._price = price;
}
property price(v) // computable property, special kind of member function
{
get { return this._price; } // getter section
set { this._price = v; } // setter section
}
function toString() { // member function, method of a Car.
return String.printf("<%s>",this.brand);
}
}
class Truck : Car
{
function this(brand, size) {
super(brand, 2000); // Call of constructor of super class (Car here)
this.size = size; // Custom property for just this object.
}
}
var cars = [ // Some example car objects.
new Car("Mazda"),
new Truck("Volvo", 2, 30000)
];
for (var (i,car) in cars) // TIScript allows enumerate indexes and values
{
stdout.printf("#%d %s $%d %v %v, %v %v", i, car.brand, car.price, car.weight, car.size,
car instanceof Car, car instanceof Truck);
} |
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 their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.
If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language.
If the points are too far apart then no circles can be drawn.
Task detail
Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned.
Show here the output for the following inputs:
p1 p2 r
0.1234, 0.9876 0.8765, 0.2345 2.0
0.0000, 2.0000 0.0000, 0.0000 1.0
0.1234, 0.9876 0.1234, 0.9876 2.0
0.1234, 0.9876 0.8765, 0.2345 0.5
0.1234, 0.9876 0.1234, 0.9876 0.0
Related task
Total circles area.
See also
Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
| #Stata | Stata | real matrix centers(real colvector a, real colvector b, real scalar r) {
real matrix rot
real scalar d, u, v
d = norm(b-a)
if (r == 0 | d == 0) {
if (r == 0 & d == 0) {
return((a,a))
} else {
return(J(2, 2, .))
}
} else if (d <= 2*r) {
u = d/(2*r)
v = sqrt(1-u^2)
rot = u,-v\v,u
return((rot*(b-a),rot'*(b-a))*r/d:+a)
} else {
return(J(2, 2, .))
}
} |
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 unusual filename: `Abdu'l-Bahá.txt
| #NewLISP | NewLISP | (dolist (file '("input.txt" "/input.txt"))
(if (file? file true)
(println "file " file " exists")))
(dolist (dir '("docs" "/docs"))
(if (directory? dir)
(println "directory " dir " exists"))) |
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 unusual filename: `Abdu'l-Bahá.txt
| #Nim | Nim | import os
echo fileExists "input.txt"
echo fileExists "/input.txt"
echo dirExists "docs"
echo dirExists "/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 the corresponding character.
| #langur | langur | val .a1 = 'a'
val .a2 = 97
val .a3 = "a"[1]
val .a4 = s2cp "a", 1
val .a5 = [.a1, .a2, .a3, .a4]
writeln .a1 == .a2
writeln .a2 == .a3
writeln .a3 == .a4
writeln "numbers: ", join ", ", [.a1, .a2, .a3, .a4, .a5]
writeln "letters: ", join ", ", [cp2s(.a1), cp2s(.a2), cp2s(.a3), cp2s(.a4), cp2s(.a5)] |
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 the corresponding character.
| #Lasso | Lasso | 'a'->integer
'A'->integer
97->bytes
65->bytes |
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 root of
A
{\displaystyle A}
, as described in Cholesky decomposition.
In a 3x3 example, we have to solve the following system of equations:
A
=
(
a
11
a
21
a
31
a
21
a
22
a
32
a
31
a
32
a
33
)
=
(
l
11
0
0
l
21
l
22
0
l
31
l
32
l
33
)
(
l
11
l
21
l
31
0
l
22
l
32
0
0
l
33
)
≡
L
L
T
=
(
l
11
2
l
21
l
11
l
31
l
11
l
21
l
11
l
21
2
+
l
22
2
l
31
l
21
+
l
32
l
22
l
31
l
11
l
31
l
21
+
l
32
l
22
l
31
2
+
l
32
2
+
l
33
2
)
{\displaystyle {\begin{aligned}A&={\begin{pmatrix}a_{11}&a_{21}&a_{31}\\a_{21}&a_{22}&a_{32}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}\\&={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}l_{11}&l_{21}&l_{31}\\0&l_{22}&l_{32}\\0&0&l_{33}\end{pmatrix}}\equiv LL^{T}\\&={\begin{pmatrix}l_{11}^{2}&l_{21}l_{11}&l_{31}l_{11}\\l_{21}l_{11}&l_{21}^{2}+l_{22}^{2}&l_{31}l_{21}+l_{32}l_{22}\\l_{31}l_{11}&l_{31}l_{21}+l_{32}l_{22}&l_{31}^{2}+l_{32}^{2}+l_{33}^{2}\end{pmatrix}}\end{aligned}}}
We can see that for the diagonal elements (
l
k
k
{\displaystyle l_{kk}}
) of
L
{\displaystyle L}
there is a calculation pattern:
l
11
=
a
11
{\displaystyle l_{11}={\sqrt {a_{11}}}}
l
22
=
a
22
−
l
21
2
{\displaystyle l_{22}={\sqrt {a_{22}-l_{21}^{2}}}}
l
33
=
a
33
−
(
l
31
2
+
l
32
2
)
{\displaystyle l_{33}={\sqrt {a_{33}-(l_{31}^{2}+l_{32}^{2})}}}
or in general:
l
k
k
=
a
k
k
−
∑
j
=
1
k
−
1
l
k
j
2
{\displaystyle l_{kk}={\sqrt {a_{kk}-\sum _{j=1}^{k-1}l_{kj}^{2}}}}
For the elements below the diagonal (
l
i
k
{\displaystyle l_{ik}}
, where
i
>
k
{\displaystyle i>k}
) there is also a calculation pattern:
l
21
=
1
l
11
a
21
{\displaystyle l_{21}={\frac {1}{l_{11}}}a_{21}}
l
31
=
1
l
11
a
31
{\displaystyle l_{31}={\frac {1}{l_{11}}}a_{31}}
l
32
=
1
l
22
(
a
32
−
l
31
l
21
)
{\displaystyle l_{32}={\frac {1}{l_{22}}}(a_{32}-l_{31}l_{21})}
which can also be expressed in a general formula:
l
i
k
=
1
l
k
k
(
a
i
k
−
∑
j
=
1
k
−
1
l
i
j
l
k
j
)
{\displaystyle l_{ik}={\frac {1}{l_{kk}}}\left(a_{ik}-\sum _{j=1}^{k-1}l_{ij}l_{kj}\right)}
Task description
The task is to implement a routine which will return a lower Cholesky factor
L
{\displaystyle L}
for every given symmetric, positive definite nxn matrix
A
{\displaystyle A}
. You should then test it on the following two examples and include your output.
Example 1:
25 15 -5 5 0 0
15 18 0 --> 3 3 0
-5 0 11 -1 1 3
Example 2:
18 22 54 42 4.24264 0.00000 0.00000 0.00000
22 70 86 62 --> 5.18545 6.56591 0.00000 0.00000
54 86 174 134 12.72792 3.04604 1.64974 0.00000
42 62 134 106 9.89949 1.62455 1.84971 1.39262
Note
The Cholesky decomposition of a Pascal upper-triangle matrix is the Identity matrix of the same size.
The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size. | #zkl | zkl | var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
fcn lowerCholesky(m){ // trans: C
rows:=m.rows;
lcm:=GSL.Matrix(rows,rows); // zero filled
foreach i,j in (rows,i+1){
s:=(0).reduce(j,'wrap(s,k){ s + lcm[i,k]*lcm[j,k] },0.0);
lcm[i,j]=( if(i==j)(m[i,i] - s).sqrt()
else 1.0/lcm[j,j]*(m[i,j] - s) );
}
lcm
} |
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 root of
A
{\displaystyle A}
, as described in Cholesky decomposition.
In a 3x3 example, we have to solve the following system of equations:
A
=
(
a
11
a
21
a
31
a
21
a
22
a
32
a
31
a
32
a
33
)
=
(
l
11
0
0
l
21
l
22
0
l
31
l
32
l
33
)
(
l
11
l
21
l
31
0
l
22
l
32
0
0
l
33
)
≡
L
L
T
=
(
l
11
2
l
21
l
11
l
31
l
11
l
21
l
11
l
21
2
+
l
22
2
l
31
l
21
+
l
32
l
22
l
31
l
11
l
31
l
21
+
l
32
l
22
l
31
2
+
l
32
2
+
l
33
2
)
{\displaystyle {\begin{aligned}A&={\begin{pmatrix}a_{11}&a_{21}&a_{31}\\a_{21}&a_{22}&a_{32}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}\\&={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}l_{11}&l_{21}&l_{31}\\0&l_{22}&l_{32}\\0&0&l_{33}\end{pmatrix}}\equiv LL^{T}\\&={\begin{pmatrix}l_{11}^{2}&l_{21}l_{11}&l_{31}l_{11}\\l_{21}l_{11}&l_{21}^{2}+l_{22}^{2}&l_{31}l_{21}+l_{32}l_{22}\\l_{31}l_{11}&l_{31}l_{21}+l_{32}l_{22}&l_{31}^{2}+l_{32}^{2}+l_{33}^{2}\end{pmatrix}}\end{aligned}}}
We can see that for the diagonal elements (
l
k
k
{\displaystyle l_{kk}}
) of
L
{\displaystyle L}
there is a calculation pattern:
l
11
=
a
11
{\displaystyle l_{11}={\sqrt {a_{11}}}}
l
22
=
a
22
−
l
21
2
{\displaystyle l_{22}={\sqrt {a_{22}-l_{21}^{2}}}}
l
33
=
a
33
−
(
l
31
2
+
l
32
2
)
{\displaystyle l_{33}={\sqrt {a_{33}-(l_{31}^{2}+l_{32}^{2})}}}
or in general:
l
k
k
=
a
k
k
−
∑
j
=
1
k
−
1
l
k
j
2
{\displaystyle l_{kk}={\sqrt {a_{kk}-\sum _{j=1}^{k-1}l_{kj}^{2}}}}
For the elements below the diagonal (
l
i
k
{\displaystyle l_{ik}}
, where
i
>
k
{\displaystyle i>k}
) there is also a calculation pattern:
l
21
=
1
l
11
a
21
{\displaystyle l_{21}={\frac {1}{l_{11}}}a_{21}}
l
31
=
1
l
11
a
31
{\displaystyle l_{31}={\frac {1}{l_{11}}}a_{31}}
l
32
=
1
l
22
(
a
32
−
l
31
l
21
)
{\displaystyle l_{32}={\frac {1}{l_{22}}}(a_{32}-l_{31}l_{21})}
which can also be expressed in a general formula:
l
i
k
=
1
l
k
k
(
a
i
k
−
∑
j
=
1
k
−
1
l
i
j
l
k
j
)
{\displaystyle l_{ik}={\frac {1}{l_{kk}}}\left(a_{ik}-\sum _{j=1}^{k-1}l_{ij}l_{kj}\right)}
Task description
The task is to implement a routine which will return a lower Cholesky factor
L
{\displaystyle L}
for every given symmetric, positive definite nxn matrix
A
{\displaystyle A}
. You should then test it on the following two examples and include your output.
Example 1:
25 15 -5 5 0 0
15 18 0 --> 3 3 0
-5 0 11 -1 1 3
Example 2:
18 22 54 42 4.24264 0.00000 0.00000 0.00000
22 70 86 62 --> 5.18545 6.56591 0.00000 0.00000
54 86 174 134 12.72792 3.04604 1.64974 0.00000
42 62 134 106 9.89949 1.62455 1.84971 1.39262
Note
The Cholesky decomposition of a Pascal upper-triangle matrix is the Identity matrix of the same size.
The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size. | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET d=2000: GO SUB 1000: GO SUB 4000: GO SUB 5000
20 LET d=3000: GO SUB 1000: GO SUB 4000: GO SUB 5000
30 STOP
1000 RESTORE d
1010 READ a,b
1020 DIM m(a,b)
1040 FOR i=1 TO a
1050 FOR j=1 TO b
1060 READ m(i,j)
1070 NEXT j
1080 NEXT i
1090 RETURN
2000 DATA 3,3,25,15,-5,15,18,0,-5,0,11
3000 DATA 4,4,18,22,54,42,22,70,86,62,54,86,174,134,42,62,134,106
4000 REM Cholesky decomposition
4005 DIM l(a,b)
4010 FOR i=1 TO a
4020 FOR j=1 TO i
4030 LET s=0
4050 FOR k=1 TO j-1
4060 LET s=s+l(i,k)*l(j,k)
4070 NEXT k
4080 IF i=j THEN LET l(i,j)=SQR (m(i,i)-s): GO TO 4100
4090 LET l(i,j)=(m(i,j)-s)/l(j,j)
4100 NEXT j
4110 NEXT i
4120 RETURN
5000 REM Print
5010 FOR r=1 TO a
5020 FOR c=1 TO b
5030 PRINT l(r,c);" ";
5040 NEXT c
5050 PRINT
5060 NEXT r
5070 RETURN |
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 few values to it.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #REXX | REXX | pr. = /*define a default for all elements for the array*/
pr.1 = 2 /*note that this array starts at 1 (one). */
pr.2 = 3
pr.3 = 5
pr.4 = 7
pr.5 = 11
pr.6 = 13
pr.7 = 17
pr.8 = 19
pr.9 = 23
pr.10 = 29
pr.11 = 31
pr.12 = 37
pr.13 = 41
pr.14 = 43
pr.15 = 47
y. = 0 /*define a default for all years (Y) to be zero*/
y.1985 = 6020
y.1986 = 7791
y.1987 = 8244
y.1988 = 10075
x = y.2012 /*the variable X will have a value of zero (0).*/
fib.0 = 0 /*this stemmed arrays will start with zero (0). */
fib.1 = 1
fib.2 = 1
fib.3 = 2
fib.4 = 3
fib.5 = 5
fib.6 = 8
fib.7 = 17
do n=-5 to 5 /*define a stemmed array from -5 to 5 */
sawtooth.n = n /*the sawtooth array is, well, a sawtooth curve*/
end /*n*/ /*note that eleven elements will be defined. */ |
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
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #V | V | [comb [m lst] let
[ [m zero?] [[[]]]
[lst null?] [[]]
[true] [m pred lst rest comb [lst first swap cons] map
m lst rest comb concat]
] when]. |
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 if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #X86_Assembly | X86 Assembly |
if(i>1)
DoSomething
FailedSoContinueCodeExecution.
|
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 if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #XLISP | XLISP | (if (eq s "Rosetta Code")
"The well-known programming chrestomathy site"
"Some other website, maybe, I dunno" ) |
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, as a type, has the values and operations of its own.
The operations of are usually called methods of the root type.
Both operations and values are called polymorphic.
A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument.
The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual.
Operations with multiple arguments and/or the results of the class are called multi-methods.
A further generalization of is the operation with arguments and/or results from different classes.
single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x).
multiple-dispatch languages allow many arguments and/or results to control the dispatch.
A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type.
This type is sometimes called the most specific type of a [polymorphic] value.
The type tag of the value is used in order to resolve the dispatch.
The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class.
In many OO languages
the type of the class of T and T itself are considered equivalent.
In some languages they are distinct (like in Ada).
When class T and T are equivalent, there is no way to distinguish
polymorphic and specific values.
Task
Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
| #Transd | Transd | #lang transd
class Point : {
x: Double(),
y: Double(),
@init: (λ v Vector<Double>() (= x (get v 0)) (= y (get v 1))),
print: (λ (textout "Point(" x "; " y ")\n" ))
}
MainModule: {
v_: [[1.0, 2.0], [3.0, 4.0]],
_start: (λ
// creating an instance of class
(with pt Point([5.0, 6.0])
// calling a class' method
(print pt)
)
// creating several instances using data deserialization
(with v Vector<Point>(v_)
(for p in v do (print p))
) )
} |
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points | Circles of given radius through two points |
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
Exceptions
r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.
If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language.
If the points are too far apart then no circles can be drawn.
Task detail
Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned.
Show here the output for the following inputs:
p1 p2 r
0.1234, 0.9876 0.8765, 0.2345 2.0
0.0000, 2.0000 0.0000, 0.0000 1.0
0.1234, 0.9876 0.1234, 0.9876 2.0
0.1234, 0.9876 0.8765, 0.2345 0.5
0.1234, 0.9876 0.1234, 0.9876 0.0
Related task
Total circles area.
See also
Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
| #Swift | Swift | import Foundation
struct Point: Equatable {
var x: Double
var y: Double
}
struct Circle {
var center: Point
var radius: Double
static func circleBetween(
_ p1: Point,
_ p2: Point,
withRadius radius: Double
) -> (Circle, Circle?)? {
func applyPoint(_ p1: Point, _ p2: Point, op: (Double, Double) -> Double) -> Point {
return Point(x: op(p1.x, p2.x), y: op(p1.y, p2.y))
}
func mul2(_ p: Point, mul: Double) -> Point {
return Point(x: p.x * mul, y: p.y * mul)
}
func div2(_ p: Point, div: Double) -> Point {
return Point(x: p.x / div, y: p.y / div)
}
func norm(_ p: Point) -> Point {
return div2(p, div: (p.x * p.x + p.y * p.y).squareRoot())
}
guard radius != 0, p1 != p2 else {
return nil
}
let diameter = 2 * radius
let pq = applyPoint(p1, p2, op: -)
let magPQ = (pq.x * pq.x + pq.y * pq.y).squareRoot()
guard diameter >= magPQ else {
return nil
}
let midpoint = div2(applyPoint(p1, p2, op: +), div: 2)
let halfPQ = magPQ / 2
let magMidC = abs(radius * radius - halfPQ * halfPQ).squareRoot()
let midC = mul2(norm(Point(x: -pq.y, y: pq.x)), mul: magMidC)
let center1 = applyPoint(midpoint, midC, op: +)
let center2 = applyPoint(midpoint, midC, op: -)
if center1 == center2 {
return (Circle(center: center1, radius: radius), nil)
} else {
return (Circle(center: center1, radius: radius), Circle(center: center2, radius: radius))
}
}
}
let testCases = [
(Point(x: 0.1234, y: 0.9876), Point(x: 0.8765, y: 0.2345), 2.0),
(Point(x: 0.0000, y: 2.0000), Point(x: 0.0000, y: 0.0000), 1.0),
(Point(x: 0.1234, y: 0.9876), Point(x: 0.1234, y: 0.9876), 2.0),
(Point(x: 0.1234, y: 0.9876), Point(x: 0.8765, y: 0.2345), 0.5),
(Point(x: 0.1234, y: 0.9876), Point(x: 0.1234, y: 0.9876), 0.0)
]
for testCase in testCases {
switch Circle.circleBetween(testCase.0, testCase.1, withRadius: testCase.2) {
case nil:
print("No ans")
case (let circle1, nil)?:
print("One ans: \(circle1)")
case (let circle1, let circle2?)?:
print("Two ans: \(circle1) \(circle2)")
}
}
|
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 unusual filename: `Abdu'l-Bahá.txt
| #Objeck | Objeck |
use IO;
bundle Default {
class Test {
function : Main(args : String[]) ~ Nil {
File->Exists("input.txt")->PrintLine();
File->Exists("/input.txt")->PrintLine();
Directory->Exists("docs")->PrintLine();
Directory->Exists("/docs")->PrintLine();
}
}
|
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 the corresponding character.
| #LFE | LFE | > (list 68 111 110 39 116 32 80 97 110 105 99 46)
"Don't Panic." |
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 the corresponding character.
| #Liberty_BASIC | Liberty BASIC | charCode = 97
char$ = "a"
print chr$(charCode) 'prints a
print asc(char$) 'prints 97 |
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 few values to it.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Ring | Ring |
text = list(2)
text[1] = "Hello "
text[2] = "world!"
see text[1] + text[2] + nl
|
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
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #VBA | VBA | Option Explicit
Option Base 0
'Option Base 1
Private ArrResult
Sub test()
'compute
Main_Combine 5, 3
'return
Dim j As Long, i As Long, temp As String
For i = LBound(ArrResult, 1) To UBound(ArrResult, 1)
temp = vbNullString
For j = LBound(ArrResult, 2) To UBound(ArrResult, 2)
temp = temp & " " & ArrResult(i, j)
Next
Debug.Print temp
Next
Erase ArrResult
End Sub
Private Sub Main_Combine(M As Long, N As Long)
Dim MyArr, i As Long
ReDim MyArr(M - 1)
If LBound(MyArr) > 0 Then ReDim MyArr(M) 'Case Option Base 1
For i = LBound(MyArr) To UBound(MyArr)
MyArr(i) = i
Next i
i = IIf(LBound(MyArr) > 0, N, N - 1)
ReDim ArrResult(i, LBound(MyArr))
Combine MyArr, N, LBound(MyArr), LBound(MyArr)
ReDim Preserve ArrResult(UBound(ArrResult, 1), UBound(ArrResult, 2) - 1)
'In VBA Excel we can use Application.Transpose instead of personal Function Transposition
ArrResult = Transposition(ArrResult)
End Sub
Private Sub Combine(MyArr As Variant, Nb As Long, Deb As Long, Ind As Long)
Dim i As Long, j As Long, N As Long
For i = Deb To UBound(MyArr, 1)
ArrResult(Ind, UBound(ArrResult, 2)) = MyArr(i)
N = IIf(LBound(ArrResult, 1) = 0, Nb - 1, Nb)
If Ind = N Then
ReDim Preserve ArrResult(UBound(ArrResult, 1), UBound(ArrResult, 2) + 1)
For j = LBound(ArrResult, 1) To UBound(ArrResult, 1)
ArrResult(j, UBound(ArrResult, 2)) = ArrResult(j, UBound(ArrResult, 2) - 1)
Next j
Else
Call Combine(MyArr, Nb, i + 1, Ind + 1)
End If
Next i
End Sub
Private Function Transposition(ByRef MyArr As Variant) As Variant
Dim T, i As Long, j As Long
ReDim T(LBound(MyArr, 2) To UBound(MyArr, 2), LBound(MyArr, 1) To UBound(MyArr, 1))
For i = LBound(MyArr, 1) To UBound(MyArr, 1)
For j = LBound(MyArr, 2) To UBound(MyArr, 2)
T(j, i) = MyArr(i, j)
Next j
Next i
Transposition = T
Erase T
End Function |
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 if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #XPL0 | XPL0 | if BOOLEAN EXPRESSION then STATEMENT
if BOOLEAN EXPRESSION then STATEMENT else STATEMENT
if BOOLEAN EXPRESSION then EXPRESSION else EXPRESSION
case INTEGER EXPRESSION of
INTEGER EXPRESSION, ... INTEGER EXPRESSION: STATEMENT;
...
INTEGER EXPRESSION, ... INTEGER EXPRESSION: STATEMENT
other STATEMENT
case of
BOOLEAN EXPRESSION, ... BOOLEAN EXPRESSION: STATEMENT;
...
BOOLEAN EXPRESSION, ... BOOLEAN EXPRESSION: STATEMENT
other STATEMENT
|
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, as a type, has the values and operations of its own.
The operations of are usually called methods of the root type.
Both operations and values are called polymorphic.
A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument.
The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual.
Operations with multiple arguments and/or the results of the class are called multi-methods.
A further generalization of is the operation with arguments and/or results from different classes.
single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x).
multiple-dispatch languages allow many arguments and/or results to control the dispatch.
A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type.
This type is sometimes called the most specific type of a [polymorphic] value.
The type tag of the value is used in order to resolve the dispatch.
The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class.
In many OO languages
the type of the class of T and T itself are considered equivalent.
In some languages they are distinct (like in Ada).
When class T and T are equivalent, there is no way to distinguish
polymorphic and specific values.
Task
Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
| #TXR | TXR | (defstruct shape ()
cached-area
(:init (self)
(put-line `@self is born!`))
(:fini (self)
(put-line `@self says goodbye!`))
(:method area (self)
(or self.cached-area
(set self.cached-area self.(calc-area)))))
(defstruct circle shape
(radius 1.0)
(:method calc-area (self)
(* %pi% self.radius self.radius)))
(defstruct square shape
(length 1.0)
(:method calc-area (self)
(* self.length self.length))) |
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, as a type, has the values and operations of its own.
The operations of are usually called methods of the root type.
Both operations and values are called polymorphic.
A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument.
The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual.
Operations with multiple arguments and/or the results of the class are called multi-methods.
A further generalization of is the operation with arguments and/or results from different classes.
single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x).
multiple-dispatch languages allow many arguments and/or results to control the dispatch.
A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type.
This type is sometimes called the most specific type of a [polymorphic] value.
The type tag of the value is used in order to resolve the dispatch.
The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class.
In many OO languages
the type of the class of T and T itself are considered equivalent.
In some languages they are distinct (like in Ada).
When class T and T are equivalent, there is no way to distinguish
polymorphic and specific values.
Task
Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
| #UNIX_Shell | UNIX Shell | typeset -T Summation_t=(
integer sum
# the constructor
function create {
_.sum=0
}
# a method
function add {
(( _.sum += $1 ))
}
)
Summation_t s
for i in 1 2 3 4 5; do
s.add $i
done
print ${s.sum} |
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 their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.
If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language.
If the points are too far apart then no circles can be drawn.
Task detail
Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned.
Show here the output for the following inputs:
p1 p2 r
0.1234, 0.9876 0.8765, 0.2345 2.0
0.0000, 2.0000 0.0000, 0.0000 1.0
0.1234, 0.9876 0.1234, 0.9876 2.0
0.1234, 0.9876 0.8765, 0.2345 0.5
0.1234, 0.9876 0.1234, 0.9876 0.0
Related task
Total circles area.
See also
Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
| #Tcl | Tcl | proc findCircles {p1 p2 r} {
lassign $p1 x1 y1
lassign $p2 x2 y2
# Special case: coincident & zero size
if {$x1 == $x2 && $y1 == $y2 && $r == 0.0} {
return [list [list $x1 $y1 0.0]]
}
if {$r <= 0.0} {
error "radius must be positive for sane results"
}
if {$x1 == $x2 && $y1 == $y2} {
error "no sane solution: points are coincident"
}
# Calculate distance apart and separation vector
set dx [expr {$x2 - $x1}]
set dy [expr {$y2 - $y1}]
set q [expr {hypot($dx, $dy)}]
if {$q > 2*$r} {
error "no solution: points are further apart than required diameter"
}
# Calculate midpoint
set x3 [expr {($x1+$x2)/2.0}]
set y3 [expr {($y1+$y2)/2.0}]
# Fractional distance along the mirror line
set f [expr {($r**2 - ($q/2.0)**2)**0.5 / $q}]
# The two answers
set c1 [list [expr {$x3 - $f*$dy}] [expr {$y3 + $f*$dx}] $r]
set c2 [list [expr {$x3 + $f*$dy}] [expr {$y3 - $f*$dx}] $r]
return [list $c1 $c2]
} |
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 unusual filename: `Abdu'l-Bahá.txt
| #Objective-C | Objective-C | NSFileManager *fm = [NSFileManager defaultManager];
NSLog(@"input.txt %s", [fm fileExistsAtPath:@"input.txt"] ? @"exists" : @"doesn't exist");
NSLog(@"docs %s", [fm fileExistsAtPath:@"docs"] ? @"exists" : @"doesn't exist"); |
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 the corresponding character.
| #LIL | LIL | print [char 97]
print [codeat "a" 0] |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #Lingo | Lingo | -- returns Unicode code point (=ASCII code for ASCII characters) for character
put chartonum("a")
-- 97
-- returns character for Unicode code point (=ASCII code for ASCII characters)
put numtochar(934)
-- Φ |
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 few values to it.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Ruby | Ruby | # creating an empty array and adding values
a = [] #=> []
a[0] = 1 #=> [1]
a[3] = "abc" #=> [1, nil, nil, "abc"]
a << 3.14 #=> [1, nil, nil, "abc", 3.14]
# creating an array with the constructor
a = Array.new #=> []
a = Array.new(3) #=> [nil, nil, nil]
a = Array.new(3, 0) #=> [0, 0, 0]
a = Array.new(3){|i| i*2} #=> [0, 2, 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
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #VBScript | VBScript |
Function Dec2Bin(n)
q = n
Dec2Bin = ""
Do Until q = 0
Dec2Bin = CStr(q Mod 2) & Dec2Bin
q = Int(q / 2)
Loop
Dec2Bin = Right("00000" & Dec2Bin,6)
End Function
Sub Combination(n,k)
Dim arr()
ReDim arr(n-1)
For h = 0 To n-1
arr(h) = h + 1
Next
Set list = CreateObject("System.Collections.Arraylist")
For i = 1 To 2^n
bin = Dec2Bin(i)
c = 0
tmp_combo = ""
If Len(Replace(bin,"0","")) = k Then
For j = Len(bin) To 1 Step -1
If CInt(Mid(bin,j,1)) = 1 Then
tmp_combo = tmp_combo & arr(c) & ","
End If
c = c + 1
Next
list.Add Mid(tmp_combo,1,(k*2)-1)
End If
Next
list.Sort
For l = 0 To list.Count-1
WScript.StdOut.Write list(l)
WScript.StdOut.WriteLine
Next
End Sub
'Testing with n = 5 / k = 3
Call Combination(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 if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #XSLT | XSLT | <xsl:if test="condition">
<!-- executed if XPath expression evaluates to true -->
</xsl:if> |
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, as a type, has the values and operations of its own.
The operations of are usually called methods of the root type.
Both operations and values are called polymorphic.
A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument.
The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual.
Operations with multiple arguments and/or the results of the class are called multi-methods.
A further generalization of is the operation with arguments and/or results from different classes.
single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x).
multiple-dispatch languages allow many arguments and/or results to control the dispatch.
A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type.
This type is sometimes called the most specific type of a [polymorphic] value.
The type tag of the value is used in order to resolve the dispatch.
The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class.
In many OO languages
the type of the class of T and T itself are considered equivalent.
In some languages they are distinct (like in Ada).
When class T and T are equivalent, there is no way to distinguish
polymorphic and specific values.
Task
Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
| #Vala | Vala | public class MyClass : Object {
// Instance variable
public int variable;
// Method
public void some_method() {
variable = 24;
}
// Constructor
public MyClass() {
variable = 42;
}
}
void main() {
// Class instance
MyClass instance = new MyClass();
print("%d\n", instance.variable);
instance.some_method();
print("%d\n", instance.variable);
instance.variable = 84;
print("%d\n", instance.variable);
} |
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 their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.
If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language.
If the points are too far apart then no circles can be drawn.
Task detail
Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned.
Show here the output for the following inputs:
p1 p2 r
0.1234, 0.9876 0.8765, 0.2345 2.0
0.0000, 2.0000 0.0000, 0.0000 1.0
0.1234, 0.9876 0.1234, 0.9876 2.0
0.1234, 0.9876 0.8765, 0.2345 0.5
0.1234, 0.9876 0.1234, 0.9876 0.0
Related task
Total circles area.
See also
Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
| #VBA | VBA | Public Sub circles()
tests = [{0.1234, 0.9876, 0.8765, 0.2345, 2.0; 0.0000, 2.0000, 0.0000, 0.0000, 1.0; 0.1234, 0.9876, 0.1234, 0.9876, 2.0; 0.1234, 0.9876, 0.8765, 0.2345, 0.5; 0.1234, 0.9876, 0.1234, 0.9876, 0.0}]
For i = 1 To UBound(tests)
x1 = tests(i, 1)
y1 = tests(i, 2)
x2 = tests(i, 3)
y2 = tests(i, 4)
R = tests(i, 5)
xd = x2 - x1
yd = y1 - y2
s2 = xd * xd + yd * yd
sep = Sqr(s2)
xh = (x1 + x2) / 2
yh = (y1 + y2) / 2
Dim txt As String
If sep = 0 Then
txt = "same points/" & IIf(R = 0, "radius is zero", "infinite solutions")
Else
If sep = 2 * R Then
txt = "opposite ends of diameter with centre " & xh & ", " & yh & "."
Else
If sep > 2 * R Then
txt = "too far apart " & sep & " > " & 2 * R
Else
md = Sqr(R * R - s2 / 4)
xs = md * xd / sep
ys = md * yd / sep
txt = "{" & Format(xh + ys, "0.0000") & ", " & Format(yh + xs, "0.0000") & _
"} and {" & Format(xh - ys, "0.0000") & ", " & Format(yh - xs, "0.0000") & "}"
End If
End If
End If
Debug.Print "points " & "{" & x1 & ", " & y1 & "}" & ", " & "{" & x2 & ", " & y2 & "}" & " with radius " & R & " ==> " & txt
Next i
End Sub |
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 unusual filename: `Abdu'l-Bahá.txt
| #OCaml | OCaml | Sys.file_exists "input.txt";;
Sys.file_exists "docs";;
Sys.file_exists "/input.txt";;
Sys.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 unusual filename: `Abdu'l-Bahá.txt
| #ooRexx | ooRexx | /**********************************************************************
* exists(filespec)
* returns 1 if filespec identifies a file with size>0
* (a file of size 0 is deemed not to exist.)
* or a directory
* 0 otherwise
* 09.06.2013 Walter Pachl (retrieved from my toolset)
**********************************************************************/
exists:
parse arg spec
call sysfiletree spec, 'LIST', 'BL'
if list.0\=1 then return 0 -- does not exist
parse var list.1 . . size flags .
if size>0 then return 1 -- real file
If substr(flags,2,1)='D' Then Do
Say spec 'is a directory'
Return 1
End
If size=0 Then Say spec 'is a zero-size file'
Return 0 |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #Little | Little | puts("Unicode value of ñ is ${scan("ñ", "%c")}");
printf("The code 241 in Unicode is the letter: %c.\n", 241);
|
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 few values to it.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Rust | Rust | let a = [1u8,2,3,4,5]; // a is of type [u8; 5];
let b = [0;256] // Equivalent to `let b = [0,0,0,0,0,0... repeat 256 times]` |
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
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Wren | Wren | import "./perm" for Comb
var fib = Fiber.new { Comb.generate((0..4).toList, 3) }
while (true) {
var c = fib.call()
if (!c) return
System.print(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 if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #Yabasic | Yabasic |
// if-then-endif, switch / end switch
// on gosub, on goto
// repeat / until, do / loop, while / end while
if expr_booleana then
sentencia(s)
endif
if expr_booleana sentencia(s)
if expr_booleana1 then
sentencia(s)
elsif expr_booleana2
sentencia(s)
elsif expr_booleana3 then
sentencia(s)
else
sentencia(s)
endif
switch expr_booleana
case valor1
sentencia(s)
case valor2
sentencia(s)
default
sentencia(s)
end switch
on expresion gosub label1, label2
sentencia(s)
label label1
sentencia(s)
return
label label2
sentencia(s)
return
on expresion goto label1, label2
sentencia(s)
label label1
sentencia(s)
label label2
sentencia(s)
repeat
sentencia(s)
until valor1
do
sentencia(s)
loop
while expr_booleana
sentencia(s)
end while
|
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, as a type, has the values and operations of its own.
The operations of are usually called methods of the root type.
Both operations and values are called polymorphic.
A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument.
The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual.
Operations with multiple arguments and/or the results of the class are called multi-methods.
A further generalization of is the operation with arguments and/or results from different classes.
single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x).
multiple-dispatch languages allow many arguments and/or results to control the dispatch.
A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type.
This type is sometimes called the most specific type of a [polymorphic] value.
The type tag of the value is used in order to resolve the dispatch.
The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class.
In many OO languages
the type of the class of T and T itself are considered equivalent.
In some languages they are distinct (like in Ada).
When class T and T are equivalent, there is no way to distinguish
polymorphic and specific values.
Task
Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
| #VBA | VBA | Private Const m_default = 10
Private m_bar As Integer
Private Sub Class_Initialize()
'constructor, can be used to set default values
m_bar = m_default
End Sub
Private Sub Class_Terminate()
'destructor, can be used to do some cleaning up
'here we just print a message
Debug.Print "---object destroyed---"
End Sub
Property Let Bar(value As Integer)
m_bar = value
End Property
Property Get Bar() As Integer
Bar = m_bar
End Property
Function DoubleBar()
m_bar = m_bar * 2
End Function
Function MultiplyBar(x As Integer)
'another method
MultiplyBar = m_bar * x
'Note: instead of using the instance variable m_bar we could refer to the Bar property of this object using the special word "Me":
' MultiplyBar = Me.Bar * x
End Function |
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 their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.
If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language.
If the points are too far apart then no circles can be drawn.
Task detail
Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned.
Show here the output for the following inputs:
p1 p2 r
0.1234, 0.9876 0.8765, 0.2345 2.0
0.0000, 2.0000 0.0000, 0.0000 1.0
0.1234, 0.9876 0.1234, 0.9876 2.0
0.1234, 0.9876 0.8765, 0.2345 0.5
0.1234, 0.9876 0.1234, 0.9876 0.0
Related task
Total circles area.
See also
Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
| #Visual_Basic_.NET | Visual Basic .NET | Public Class CirclesOfGivenRadiusThroughTwoPoints
Public Shared Sub Main()
For Each valu In New Double()() {
New Double() {0.1234, 0.9876, 0.8765, 0.2345, 2},
New Double() {0.0, 2.0, 0.0, 0.0, 1},
New Double() {0.1234, 0.9876, 0.1234, 0.9876, 2},
New Double() {0.1234, 0.9876, 0.8765, 0.2345, 0.5},
New Double() {0.1234, 0.9876, 0.1234, 0.9876, 0},
New Double() {0.1234, 0.9876, 0.2345, 0.8765, 0}}
Dim p = New Point(valu(0), valu(1)), q = New Point(valu(2), valu(3))
Console.WriteLine($"Points {p} and {q} with radius {valu(4)}:")
Try
Console.WriteLine(vbTab & String.Join(" and ", FindCircles(p, q, valu(4))))
Catch ex As Exception
Console.WriteLine(vbTab & ex.Message)
End Try
Next
If System.Diagnostics.Debugger.IsAttached Then Console.ReadKey()
End Sub
Private Shared Function FindCircles(ByVal p As Point, ByVal q As Point, ByVal rad As Double) As Point()
If rad < 0 Then Throw New ArgumentException("Negative radius.")
If rad = 0 Then Throw New InvalidOperationException(If(p = q,
String.Format("{0} (degenerate circle)", {p}), "No circles."))
If p = q Then Throw New InvalidOperationException("Infinite number of circles.")
Dim dist As Double = Point.Distance(p, q), sqDist As Double = dist * dist,
sqDiam As Double = 4 * rad * rad
If sqDist > sqDiam Then Throw New InvalidOperationException(
String.Format("Points are too far apart (by {0}).", sqDist - sqDiam))
Dim midPoint As Point = New Point((p.X + q.X) / 2, (p.Y + q.Y) / 2)
If sqDist = sqDiam Then Return {midPoint}
Dim d As Double = Math.Sqrt(rad * rad - sqDist / 4),
a As Double = d * (q.X - p.X) / dist, b As Double = d * (q.Y - p.Y) / dist
Return {New Point(midPoint.X - b, midPoint.Y + a), New Point(midPoint.X + b, midPoint.Y - a)}
End Function
Public Structure Point
Public ReadOnly Property X As Double
Public ReadOnly Property Y As Double
Public Sub New(ByVal ix As Double, ByVal iy As Double)
Me.New() : X = ix : Y = iy
End Sub
Public Shared Operator =(ByVal p As Point, ByVal q As Point) As Boolean
Return p.X = q.X AndAlso p.Y = q.Y
End Operator
Public Shared Operator <>(ByVal p As Point, ByVal q As Point) As Boolean
Return p.X <> q.X OrElse p.Y <> q.Y
End Operator
Public Shared Function SquaredDistance(ByVal p As Point, ByVal q As Point) As Double
Dim dx As Double = q.X - p.X, dy As Double = q.Y - p.Y
Return dx * dx + dy * dy
End Function
Public Shared Function Distance(ByVal p As Point, ByVal q As Point) As Double
Return Math.Sqrt(SquaredDistance(p, q))
End Function
Public Overrides Function ToString() As String
Return $"({X}, {Y})"
End Function
End Structure
End Class |
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 unusual filename: `Abdu'l-Bahá.txt
| #Oz | Oz | declare
[Path] = {Module.link ['x-oz://system/os/Path.ozf']}
in
{Show {Path.exists "docs"}}
{Show {Path.exists "input.txt"}}
{Show {Path.exists "/docs"}}
{Show {Path.exists "/input.txt"}} |
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 unusual filename: `Abdu'l-Bahá.txt
| #PARI.2FGP | PARI/GP | trap(,"does not exist",read("input.txt");"exists")
trap(,"does not exist",read("c:\\input.txt");"exists")
trap(,"does not exist",read("c:\\dirname\\nul");"exists") |
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 the corresponding character.
| #LiveCode | LiveCode | Since 7.0.x works with unicode
put charToNum("") && numToChar(240) |
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 the corresponding character.
| #Logo | Logo | print ascii "a ; 97
print char 97 ; 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 few values to it.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Scala | Scala | Windows PowerShell
Copyright (C) 2012 Microsoft Corporation. All rights reserved.
PS C:\Users\FransAdm> scala
Welcome to Scala version 2.10.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_25).
Type in expressions to have them evaluated.
Type :help for more information.
scala> // Immutable collections do not and cannot change the instantiated object
scala> // Lets start with Lists
scala> val list = Nil // Empty List
list: scala.collection.immutable.Nil.type = List()
scala> val list2 = List("one", "two") // List with two elements (Strings)
list2: List[String] = List(one, two)
scala> val list3 = 3 :: list2 // prepend 3 to list2, using a special operator
list3: List[Any] = List(3, one, two)
scala> // The result was a mixture with a Int and Strings, so the common superclass Any is used.
scala> // Let test the Set collection
scala> val set = Set.empty[Char] // Empty Set of Char type
set: scala.collection.immutable.Set[Char] = Set()
scala> val set1 = set + 'c' // add an element
set1: scala.collection.immutable.Set[Char] = Set(c)
scala> val set2 = set + 'a' + 'c' + 'c' // try to add another and the same element twice
set2: scala.collection.immutable.Set[Char] = Set(a, c)
scala> // Let's look at the most universal map: TrieMap (Cache-aware lock-free concurrent hash trie)
scala> val capital = collection.concurrent.TrieMap("US" -> "Washington", "France" -> "Paris") // This map is mutable
capital: scala.collection.concurrent.TrieMap[String,String] = TrieMap(US -> Washington, France -> Paris)
scala> capital - "France" // This is only an expression, does not modify the map itself
res0: scala.collection.concurrent.TrieMap[String,String] = TrieMap(US -> Washington)
scala> capital += ("Tokio" -> "Japan") // Adding an element, object is changed - not the val capital
res1: capital.type = TrieMap(US -> Washington, Tokio -> Japan, France -> Paris)
scala> capital // Check what we have sofar
res2: scala.collection.concurrent.TrieMap[String,String] = TrieMap(US -> Washington, Tokio -> Japan, France -> Paris)
scala> val queue = new scala.collection.mutable.Queue[String]
queue: scala.collection.mutable.Queue[String] = Queue()
scala> queue += "first"
res17: queue.type = Queue("first")
scala> queue += "second"
res19: queue.type = Queue("first", "second")
scala> |
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
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #XPL0 | XPL0 | code ChOut=8, CrLf=9, IntOut=11;
def M=3, N=5;
int A(N-1);
proc Combos(D, S); \Display all size M combinations of N in sorted order
int D, S; \depth of recursion, starting value of N
int I;
[if D<M then \depth < size
for I:= S to N-1 do
[A(D):= I;
Combos(D+1, I+1);
]
else [for I:= 0 to M-1 do
[IntOut(0, A(I)); ChOut(0, ^ )];
CrLf(0);
];
];
Combos(0, 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 if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #Z80_Assembly | Z80 Assembly |
char x;
if (x == 20)
{
doThis();
}
else
{
doThat();
} |
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, as a type, has the values and operations of its own.
The operations of are usually called methods of the root type.
Both operations and values are called polymorphic.
A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument.
The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual.
Operations with multiple arguments and/or the results of the class are called multi-methods.
A further generalization of is the operation with arguments and/or results from different classes.
single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x).
multiple-dispatch languages allow many arguments and/or results to control the dispatch.
A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type.
This type is sometimes called the most specific type of a [polymorphic] value.
The type tag of the value is used in order to resolve the dispatch.
The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class.
In many OO languages
the type of the class of T and T itself are considered equivalent.
In some languages they are distinct (like in Ada).
When class T and T are equivalent, there is no way to distinguish
polymorphic and specific values.
Task
Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
| #Visual_Basic_.NET | Visual Basic .NET | Class Foo
Private m_Bar As Integer
Public Sub New()
End Sub
Public Sub New(ByVal bar As Integer)
m_Bar = bar
End Sub
Public Property Bar() As Integer
Get
Return m_Bar
End Get
Set(ByVal value As Integer)
m_Bar = value
End Set
End Property
Public Sub DoubleBar()
m_Bar *= 2
End Sub
Public Function MultiplyBar(ByVal x As Integer) As Integer
Return x * Bar
End Function
End Class |
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 their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.
If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language.
If the points are too far apart then no circles can be drawn.
Task detail
Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned.
Show here the output for the following inputs:
p1 p2 r
0.1234, 0.9876 0.8765, 0.2345 2.0
0.0000, 2.0000 0.0000, 0.0000 1.0
0.1234, 0.9876 0.1234, 0.9876 2.0
0.1234, 0.9876 0.8765, 0.2345 0.5
0.1234, 0.9876 0.1234, 0.9876 0.0
Related task
Total circles area.
See also
Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
| #Visual_FoxPro | Visual FoxPro |
LOCAL p1 As point, p2 As point, rr As Double
CLOSE DATABASES ALL
SET FIXED ON
SET DECIMALS TO 4
CLEAR
CREATE CURSOR circles (xc1 B(4), yc1 B(4), xc2 B(4), yc2 B(4), rad B(4))
INSERT INTO circles VALUES (0.1234, 0.9876, 0.8765, 0.2345, 2.0)
INSERT INTO circles VALUES (0.0000, 2.0000, 0.0000, 0.0000, 1.0)
INSERT INTO circles VALUES (0.1234, 0.9876, 0.1234, 0.9876, 2.0)
INSERT INTO circles VALUES (0.1234, 0.9876, 0.8765, 0.2345, 0.5)
INSERT INTO circles VALUES (0.1234, 0.9876, 0.1234, 0.9876, 0.0)
GO TOP
p1 = NEWOBJECT("point")
p2 = NEWOBJECT("point")
SCAN
p1.SetPoints(xc1, yc1)
p2.SetPoints(xc2, yc2)
rr = rad
GetCircles(p1, p2, rr)
?
ENDSCAN
SET DECIMALS TO
SET FIXED OFF
PROCEDURE GetCircles(op1 As point, op2 As point, r As Double)
LOCAL ctr As point, half As point, lenhalf As Double, dist As Double, rot As point, c As String
ctr = NEWOBJECT("point")
half = NEWOBJECT("point")
ctr.SetPoints((op1.xc + op2.xc)/2, (op1.yc + op2.yc)/2)
half.SetPoints(op1.xc - ctr.xc, op1.yc - ctr.yc)
lenhalf = half.nLength
PrintPoints(op1, op2, r)
IF r < lenhalf
? "Cannot solve for these parameters."
RETURN
ENDIF
IF lenhalf = 0
? "Points are coincident."
RETURN
ENDIF
dist = SQRT(r^2 - lenhalf^2)/lenhalf
rot = NEWOBJECT("point")
rot.SetPoints(-dist*(op1.yc - ctr.yc) + ctr.xc, dist*(op1.xc - ctr.xc) + ctr.yc)
TEXT TO c TEXTMERGE NOSHOW PRETEXT 3
Circle 1 (<<rot.xc>>, <<rot.yc>>)
ENDTEXT
? c
rot.SetPoints(-(rot.xc - ctr.xc) + ctr.xc, -((rot.yc - ctr.yc)) + ctr.yc)
TEXT TO c TEXTMERGE NOSHOW PRETEXT 3
Circle 2 (<<rot.xc>>, <<rot.yc>>)
ENDTEXT
? c
ENDPROC
PROCEDURE PrintPoints(op1 As point, op2 As point, r As Double)
LOCAL lcTxt As String
TEXT TO lcTxt TEXTMERGE NOSHOW PRETEXT 3
Points (<<op1.xc>>,<<op1.yc>>), (<<op2.xc>>,<<op2.yc>>) Radius <<r>>.
ENDTEXT
? lcTxt
ENDPROC
DEFINE CLASS point As Custom
xc = 0
yc = 0
nLength = 0
PROCEDURE Init
DODEFAULT()
ENDPROC
PROCEDURE SetPoints(tnx As Double, tny As Double)
THIS.xc = tnx
THIS.yc = tny
THIS.nLength = THIS.GetLength()
ENDPROC
FUNCTION GetLength()
RETURN SQRT(THIS.xc*THIS.xc + THIS.yc*THIS.yc)
ENDFUNC
ENDDEFINE
|
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 unusual filename: `Abdu'l-Bahá.txt
| #Pascal | Pascal | use File::Spec::Functions qw(catfile rootdir);
# here
print -e 'input.txt';
print -d 'docs';
# root dir
print -e catfile rootdir, 'input.txt';
print -d catfile rootdir, '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 unusual filename: `Abdu'l-Bahá.txt
| #Perl | Perl | use File::Spec::Functions qw(catfile rootdir);
# here
print -e 'input.txt';
print -d 'docs';
# root dir
print -e catfile rootdir, 'input.txt';
print -d catfile rootdir, '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 the corresponding character.
| #Logtalk | Logtalk | |?- char_code(Char, 97), write(Char).
a
Char = a
yes |
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 few values to it.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Scheme | Scheme | (list obj ...) |
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
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #zkl | zkl | fcn comb(k,seq){ // no repeats, seq is finite
seq=seq.makeReadOnly(); // because I append to parts of seq
fcn(k,seq){
if(k<=0) return(T(T));
if(not seq) return(T);
self.fcn(k-1,seq[1,*]).pump(List,seq[0,1].extend)
.extend(self.fcn(k,seq[1,*]));
}(k,seq);
} |
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 if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #zkl | zkl | if (x) y else z;
if(a)b else if (c) else d; etc
x:=(if (a) b else c);
a and b or c // usually the same as if(a) b else c, beware if b evals to False
switch(x){
case(1){...}
case("2"){...} // matches anything
case(a)[fallthrough]{...} // no break, no break has to be explicit
case(b){...}
else {...} // case a C's default, has to be at the end
} |
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, as a type, has the values and operations of its own.
The operations of are usually called methods of the root type.
Both operations and values are called polymorphic.
A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument.
The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual.
Operations with multiple arguments and/or the results of the class are called multi-methods.
A further generalization of is the operation with arguments and/or results from different classes.
single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x).
multiple-dispatch languages allow many arguments and/or results to control the dispatch.
A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type.
This type is sometimes called the most specific type of a [polymorphic] value.
The type tag of the value is used in order to resolve the dispatch.
The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class.
In many OO languages
the type of the class of T and T itself are considered equivalent.
In some languages they are distinct (like in Ada).
When class T and T are equivalent, there is no way to distinguish
polymorphic and specific values.
Task
Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
| #Visual_FoxPro | Visual FoxPro |
LOCAL o1 As MyClass, o2 As MyClass
*!* Instantiate o1
o1 = NEWOBJECT("MyClass")
o1.ShowInstance()
*!* Instantiate o2
o2 = CREATEOBJECT("MyClass", 2)
o2.ShowInstance()
DEFINE CLASS MyClass As Session
*!* Custom property (protected)
PROTECTED nInstance
nInstance = 0
*!* Constructor
PROCEDURE Init(tnInstance As Integer)
IF VARTYPE(tnInstance) = "N"
THIS.nInstance = tnInstance
ELSE
THIS.nInstance = THIS.nInstance + 1
ENDIF
ENDPROC
*!* Custom Method
PROCEDURE ShowInstance
? "Instance", THIS.nInstance
ENDPROC
ENDDEFINE
|
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, as a type, has the values and operations of its own.
The operations of are usually called methods of the root type.
Both operations and values are called polymorphic.
A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument.
The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual.
Operations with multiple arguments and/or the results of the class are called multi-methods.
A further generalization of is the operation with arguments and/or results from different classes.
single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x).
multiple-dispatch languages allow many arguments and/or results to control the dispatch.
A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type.
This type is sometimes called the most specific type of a [polymorphic] value.
The type tag of the value is used in order to resolve the dispatch.
The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class.
In many OO languages
the type of the class of T and T itself are considered equivalent.
In some languages they are distinct (like in Ada).
When class T and T are equivalent, there is no way to distinguish
polymorphic and specific values.
Task
Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
| #Wren | Wren | class Bear {
// Constructs a Bear instance passing it a name
// which is stored in the field _name
// automatically created by Wren.
construct new(name) { _name = name }
// Property to get the name
name { _name }
// Method to make a noise.
makeNoise() { System.print("Growl!") }
}
// Create a new Bear instance and assign a reference to it
// to the variable b.
var b = Bear.new("Bruno")
// Print the bear's name.
System.print("The bear is called %(b.name).")
// Make a noise.
b.makeNoise() |
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 their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.
If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language.
If the points are too far apart then no circles can be drawn.
Task detail
Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned.
Show here the output for the following inputs:
p1 p2 r
0.1234, 0.9876 0.8765, 0.2345 2.0
0.0000, 2.0000 0.0000, 0.0000 1.0
0.1234, 0.9876 0.1234, 0.9876 2.0
0.1234, 0.9876 0.8765, 0.2345 0.5
0.1234, 0.9876 0.1234, 0.9876 0.0
Related task
Total circles area.
See also
Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
| #Vlang | Vlang | import math
const (
two = "two circles."
r0 = "R==0.0 does not describe circles."
co = "coincident points describe an infinite number of circles."
cor0 = "coincident points with r==0.0 describe a degenerate circle."
diam = "Points form a diameter and describe only a single circle."
far = "Points too far apart to form circles."
)
struct Point {
x f64
y f64
}
fn circles(p1 Point, p2 Point, r f64) (Point, Point, string) {
mut case := ''
c1, c2 := p1, p2
if p1 == p2 {
if r == 0 {
return p1, p1, cor0
}
case = co
return c1, c2, case
}
if r == 0 {
return p1, p2, r0
}
dx := p2.x - p1.x
dy := p2.y - p1.y
q := math.hypot(dx, dy)
if q > 2*r {
case = far
return c1, c2, case
}
m := Point{(p1.x + p2.x) / 2, (p1.y + p2.y) / 2}
if q == 2*r {
return m, m, diam
}
d := math.sqrt(r*r - q*q/4)
ox := d * dx / q
oy := d * dy / q
return Point{m.x - oy, m.y + ox}, Point{m.x + oy, m.y - ox}, two
}
struct Cir {
p1 Point
p2 Point
r f64
}
const td = [
Cir{Point{0.1234, 0.9876}, Point{0.8765, 0.2345}, 2.0},
Cir{Point{0.0000, 2.0000}, Point{0.0000, 0.0000}, 1.0},
Cir{Point{0.1234, 0.9876}, Point{0.1234, 0.9876}, 2.0},
Cir{Point{0.1234, 0.9876}, Point{0.8765, 0.2345}, 0.5},
Cir{Point{0.1234, 0.9876}, Point{0.1234, 0.9876}, 0.0},
]
fn main() {
for tc in td {
println("p1: $tc.p1")
println("p2: $tc.p2")
println("r: $tc.r")
c1, c2, case := circles(tc.p1, tc.p2, tc.r)
println(" $case")
match case {
cor0, diam{
println(" Center: $c1")
}
two {
println(" Center 1: $c1")
println(" Center 2: $c2")
}
else{}
}
println('')
}
} |
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 unusual filename: `Abdu'l-Bahá.txt
| #Phix | Phix | without js -- (file i/o)
procedure check(string name)
bool bExists = file_exists(name),
bDir = get_file_type(name)=FILETYPE_DIRECTORY
string exists = iff(bExists?"exists":"does not exist"),
dfs = iff(bExists?iff(bDir?"directory ":"file "):"")
printf(1,"%s%s %s.\n",{dfs,name,exists})
end procedure
check("input.txt")
check("docs")
check("/input.txt")
check("/docs")
check("/pagefile.sys")
check("/Program Files (x86)")
|
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 unusual filename: `Abdu'l-Bahá.txt
| #Phixmonti | Phixmonti | "foo.bar" "w" fopen
"Hallo !" over fputs
fclose
"fou.bar" "r" fopen
dup 0 < if "Could not open 'foo.bar' for reading" print drop else fclose endif |
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 the corresponding character.
| #Lua | Lua | print(string.byte("a")) -- prints "97"
print(string.char(97)) -- prints "a" |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #M2000_Interpreter | M2000 Interpreter |
\\ ANSI
Print Asc("a")
Print Chr$(Asc("a"))
\\ Utf16-Le
Print ChrCode("a")
Print ChrCode$(ChrCode("a"))
\\ (,) is an empty array.
Function Codes(a$) {
If Len(A$)=0 then =(,) : Exit
Buffer Mem as byte*Len(a$)
\\ Str$(string) return one byte character
Return Mem, 0:=Str$(a$)
Inventory Codes
For i=0 to len(Mem)-1
Append Codes, i:=Eval(Mem, i)
Next i
=Codes
}
Print Codes("abcd")
\\ 97 98 99 100
|
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 few values to it.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
enable_output(set of string);
const proc: main is func
local
var set of string: aSet is {"iron", "copper"};
begin
writeln(aSet);
incl(aSet, "silver");
writeln(aSet);
end func; |
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 if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #Zig | Zig | const std = @import("std");
const builtin = @import("builtin");
fn printOpenSource(comptime is_open_source: bool) !void {
if (is_open_source) {
try std.io.getStdOut().writer().writeAll("Open source.\n");
} else {
try std.io.getStdOut().writer().writeAll("No open source.\n");
}
}
fn printYesOpenSource() !void {
try std.io.getStdOut().writer().writeAll("Open source.\n");
}
fn printNoOpenSource() !void {
try std.io.getStdOut().writer().writeAll("No open source.\n");
}
const fnProto = switch (builtin.zig_backend) {
.stage1 => fn () anyerror!void,
else => *const fn () anyerror!void,
};
const Vtable = struct {
fnptrs: [2]fnProto,
};
// dynamic dispatch: logic(this function) + vtable + data
fn printBySelectedType(data: bool, vtable: Vtable) !void {
if (data) {
try @call(.{}, vtable.fnptrs[0], .{});
} else {
try @call(.{}, vtable.fnptrs[1], .{});
}
}
pub fn main() !void {
// if-else
if (true) {
std.debug.assert(true);
} else {
std.debug.assert(false);
}
// comptime switch
const open_source = comptime switch (builtin.os.tag) {
.freestanding => true,
.linux => true,
.macos => false,
.windows => false,
else => unreachable,
};
// conditional compilation
std.debug.assert(builtin.zig_backend != .stage2_llvm);
// static dispatch (more complex examples work typically via comptime enums)
try printOpenSource(open_source);
// dynamic dispatch (runtime attach function pointer)
var vtable = Vtable{
.fnptrs = undefined,
};
// runtime-attach function pointers (dynamic dispatch)
vtable.fnptrs[0] = printYesOpenSource;
vtable.fnptrs[1] = printNoOpenSource;
try printBySelectedType(open_source, vtable);
// TODO Arithmetic if once https://github.com/ziglang/zig/issues/8220 is finished
} |
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, as a type, has the values and operations of its own.
The operations of are usually called methods of the root type.
Both operations and values are called polymorphic.
A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument.
The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual.
Operations with multiple arguments and/or the results of the class are called multi-methods.
A further generalization of is the operation with arguments and/or results from different classes.
single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x).
multiple-dispatch languages allow many arguments and/or results to control the dispatch.
A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type.
This type is sometimes called the most specific type of a [polymorphic] value.
The type tag of the value is used in order to resolve the dispatch.
The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class.
In many OO languages
the type of the class of T and T itself are considered equivalent.
In some languages they are distinct (like in Ada).
When class T and T are equivalent, there is no way to distinguish
polymorphic and specific values.
Task
Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
| #X86-64_Assembly | X86-64 Assembly |
option casemap:none
ifndef __SOMECLASS_CLASS__
__SOMECLASS_CLASS__ equ 1
;; Once again, HeapAlloc/Free is REQUIRED by the class extention for windows.
;; Malloc/Free are used by Linux and OSX. So the function prototypes have to
;; be defined somewhere. If you have include files where they're defined, just
;; include them in the usual way and remove the option dllimports.
if @Platform eq 1 ;; Windows 64
;; include windows.inc
;; includelib kernel32.lib
option dllimport:<kernel32>
HeapAlloc proto :qword, :dword, :qword
HeapFree proto :qword, :dword, :qword
ExitProcess proto :dword
GetProcessHeap proto
option dllimport:none
exit equ ExitProcess
elseif @Platform eq 3 ;; Linux 64
;;include libc.inc
malloc proto SYSTEMV :qword
free proto SYSTEMV :qword
exit proto SYSTEMV :dword
endif
printf proto :qword, :VARARG
CLASS someClass
CMETHOD someMethod
ENDMETHODS
var dd ?
ENDCLASS
;; The OS' ABI has an effect on this class extention. That is, the class self pointetr
;; is usually refferenced in the first arg register. So for Windows it would be rcx and
;; Linux would be rdi. So to write code that will assemble on both we use a register
;; that ISN'T used to pass arguments in either ABI(Not sure about OSX's ABI however)
METHOD someClass, Init, <VOIDARG>, <>, a:dword
mov rbx, thisPtr
assume rbx:ptr someClass
mov [rbx].var, a
mov rax, rbx
assume rbx:nothing
ret
ENDMETHOD
METHOD someClass, someMethod, <dword>, <>
mov rbx, thisPtr
assume rbx:ptr someClass
mov eax, [rbx].var
assume rbx:nothing
ret
ENDMETHOD
METHOD someClass, Destroy, <VOIDARG>, <>
ret
ENDMETHOD
endif ;; __CLASS_CLASS_
.code
main proc
local meh:ptr someClass
;; Create a new instance of someClass with an arg of 7
mov meh, _NEW(someClass, 7)
meh->someMethod() ;;Get meh->var value and return it in RAX
invoke printf, CSTR("class->someMethod = %i",10), rax
_DELETE(meh) ;; DIIIIIIIE!
invoke exit, 0 ;; Crashy crashy without it.
ret
main endp
end
|
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 their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.
If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language.
If the points are too far apart then no circles can be drawn.
Task detail
Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned.
Show here the output for the following inputs:
p1 p2 r
0.1234, 0.9876 0.8765, 0.2345 2.0
0.0000, 2.0000 0.0000, 0.0000 1.0
0.1234, 0.9876 0.1234, 0.9876 2.0
0.1234, 0.9876 0.8765, 0.2345 0.5
0.1234, 0.9876 0.1234, 0.9876 0.0
Related task
Total circles area.
See also
Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
| #Wren | Wren | import "/math" for Math
var Two = "Two circles."
var R0 = "R == 0 does not describe circles."
var Co = "Coincident points describe an infinite number of circles."
var CoR0 = "Coincident points with r == 0 describe a degenerate circle."
var Diam = "Points form a diameter and describe only a single circle."
var Far = "Points too far apart to form circles."
class Point {
construct new(x, y) {
_x = x
_y = y
}
x { _x }
y { _y }
==(p) { _x == p.x && _y == p.y }
toString { "(%(_x), %(_y))" }
}
var circles = Fn.new { |p1, p2, r|
var c1 = Point.new(0, 0)
var c2 = Point.new(0, 0)
if (p1 == p2) {
if (r == 0) return [p1, p1, CoR0]
return [c1, c2, Co]
}
if (r == 0) return [p1, p2, R0]
var dx = p2.x - p1.x
var dy = p2.y - p1.y
var q = Math.hypot(dx, dy)
if (q > 2*r) return [c1, c2, Far]
var m = Point.new((p1.x + p2.x)/2, (p1.y + p2.y)/2)
if (q == 2*r) return [m, m, Diam]
var d = (r*r - q*q/4).sqrt
var ox = d * dx / q
var oy = d * dy / q
return [Point.new(m.x - oy, m.y + ox), Point.new(m.x + oy, m.y - ox), Two]
}
var td = [
[Point.new(0.1234, 0.9876), Point.new(0.8765, 0.2345), 2.0],
[Point.new(0.0000, 2.0000), Point.new(0.0000, 0.0000), 1.0],
[Point.new(0.1234, 0.9876), Point.new(0.1234, 0.9876), 2.0],
[Point.new(0.1234, 0.9876), Point.new(0.8765, 0.2345), 0.5],
[Point.new(0.1234, 0.9876), Point.new(0.1234, 0.9876), 0.0]
]
for (tc in td) {
System.print("p1: %(tc[0])")
System.print("p2: %(tc[1])")
System.print("r : %(tc[2])")
var res = circles.call(tc[0], tc[1], tc[2])
System.print(" %(res[2])")
if (res[2] == CoR0 || res[2] == Diam) {
System.print(" Center: %(res[0])")
} else if (res[2] == Two) {
System.print(" Center 1: %(res[0])")
System.print(" Center 2: %(res[1])")
}
System.print()
} |
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 unusual filename: `Abdu'l-Bahá.txt
| #PHP | PHP | if (file_exists('input.txt')) echo 'input.txt is here right by my side';
if (file_exists('docs' )) echo 'docs is here with me';
if (file_exists('/input.txt')) echo 'input.txt is over there in the root dir';
if (file_exists('/docs' )) echo 'docs is over there in the root 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 unusual filename: `Abdu'l-Bahá.txt
| #PicoLisp | PicoLisp | (if (info "file.txt")
(prinl "Size: " (car @) " bytes, last modified " (stamp (cadr @) (cddr @)))
(prinl "File doesn't exist") )
# for directory existing
# Nehal-Singhal 2018-05-25
(if (info "./docs")
(print 'exists)
(print 'doesNotExist)))
# To verify if it's really a directory, (CAR of return value will be 'T').
# abu 2018-05-25
(let I (info "./docs")
(prinl
(nond
(I "Does not exist")
((=T (car I)) "Is not a directory")
(NIL "Directory exists") ) ) )
|
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 the corresponding character.
| #Maple | Maple | > use StringTools in Ord( "A" ); Char( 65 ) end;
65
"A"
|
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ToCharacterCode["abcd"]
FromCharacterCode[{97}] |
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 few values to it.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Setl4 | Setl4 |
set = new('set 5 10 15 20 25 25')
add(set,30)
show(set)
show.eval('member(set,5)')
show.eval('member(set,6)')
show.eval("exists(set,'eq(this,10)')")
show.eval("forall(set,'eq(this,40)')")
|
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, as a type, has the values and operations of its own.
The operations of are usually called methods of the root type.
Both operations and values are called polymorphic.
A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument.
The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual.
Operations with multiple arguments and/or the results of the class are called multi-methods.
A further generalization of is the operation with arguments and/or results from different classes.
single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x).
multiple-dispatch languages allow many arguments and/or results to control the dispatch.
A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type.
This type is sometimes called the most specific type of a [polymorphic] value.
The type tag of the value is used in order to resolve the dispatch.
The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class.
In many OO languages
the type of the class of T and T itself are considered equivalent.
In some languages they are distinct (like in Ada).
When class T and T are equivalent, there is no way to distinguish
polymorphic and specific values.
Task
Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
| #XBS | XBS | class Person {
construct=func(self,Name,Age,Gender){
self:Name=Name;
self:Age=Age;
self:Gender=Gender;
}{Name="John",Age=20,Gender="Male"};
ToString=func(self){
send self.Name+" ("+self.Gender+"): Age "+self.Age;
}
}
set John = new Person with [];
log(John::ToString());
set Jane = new Person with ["Jane",20,"Female"]
log(Jane::ToString()); |
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, as a type, has the values and operations of its own.
The operations of are usually called methods of the root type.
Both operations and values are called polymorphic.
A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument.
The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual.
Operations with multiple arguments and/or the results of the class are called multi-methods.
A further generalization of is the operation with arguments and/or results from different classes.
single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x).
multiple-dispatch languages allow many arguments and/or results to control the dispatch.
A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type.
This type is sometimes called the most specific type of a [polymorphic] value.
The type tag of the value is used in order to resolve the dispatch.
The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class.
In many OO languages
the type of the class of T and T itself are considered equivalent.
In some languages they are distinct (like in Ada).
When class T and T are equivalent, there is no way to distinguish
polymorphic and specific values.
Task
Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
| #XLISP | XLISP | (DEFINE-CLASS PROGRAMMING-LANGUAGE
(INSTANCE-VARIABLES NAME YEAR))
(DEFINE-METHOD (PROGRAMMING-LANGUAGE 'INITIALIZE X)
(SETQ NAME X)
SELF)
(DEFINE-METHOD (PROGRAMMING-LANGUAGE 'WAS-CREATED-IN X)
(SETQ YEAR X))
(DEFINE-METHOD (PROGRAMMING-LANGUAGE 'DESCRIBE)
`(THE PROGRAMMING LANGUAGE ,NAME WAS CREATED IN ,YEAR))
(DEFINE LISP (PROGRAMMING-LANGUAGE 'NEW 'LISP))
(LISP 'WAS-CREATED-IN 1958)
(DISPLAY (LISP 'DESCRIBE))
(NEWLINE) |
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 their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.
If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language.
If the points are too far apart then no circles can be drawn.
Task detail
Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned.
Show here the output for the following inputs:
p1 p2 r
0.1234, 0.9876 0.8765, 0.2345 2.0
0.0000, 2.0000 0.0000, 0.0000 1.0
0.1234, 0.9876 0.1234, 0.9876 2.0
0.1234, 0.9876 0.8765, 0.2345 0.5
0.1234, 0.9876 0.1234, 0.9876 0.0
Related task
Total circles area.
See also
Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
| #XPL0 | XPL0 | include c:\cxpl\codes;
proc Circles; real Data; \Show centers of circles, given points P & Q and radius
real Px, Py, Qx, Qy, R, X, Y, X1, Y1, Bx, By, PB, CB;
[Px:= Data(0); Py:= Data(1); Qx:= Data(2); Qy:= Data(3); R:= Data(4);
if R = 0.0 then [Text(0, "Radius = zero gives no circles^M^J"); return];
X:= (Qx-Px)/2.0; Y:= (Qy-Py)/2.0;
Bx:= Px+X; By:= Py+Y;
PB:= sqrt(X*X + Y*Y);
if PB = 0.0 then [Text(0, "Coincident points give infinite circles^M^J"); return];
if PB > R then [Text(0, "Points are too far apart for radius^M^J"); return];
CB:= sqrt(R*R - PB*PB);
X1:= Y*CB/PB; Y1:= X*CB/PB;
RlOut(0, Bx-X1); ChOut(0, ^,); RlOut(0, By+Y1); ChOut(0, 9\tab\);
RlOut(0, Bx+X1); ChOut(0, ^,); RlOut(0, By-Y1); CrLf(0);
];
real Tbl; int I;
[Tbl:=[[0.1234, 0.9876, 0.8765, 0.2345, 2.0],
[0.0000, 2.0000, 0.0000, 0.0000, 1.0],
[0.1234, 0.9876, 0.1234, 0.9876, 2.0],
[0.1234, 0.9876, 0.8765, 0.2345, 0.5],
[0.1234, 0.9876, 0.1234, 0.9876, 0.0]];
for I:= 0 to 4 do Circles(Tbl(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 their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.
If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language.
If the points are too far apart then no circles can be drawn.
Task detail
Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned.
Show here the output for the following inputs:
p1 p2 r
0.1234, 0.9876 0.8765, 0.2345 2.0
0.0000, 2.0000 0.0000, 0.0000 1.0
0.1234, 0.9876 0.1234, 0.9876 2.0
0.1234, 0.9876 0.8765, 0.2345 0.5
0.1234, 0.9876 0.1234, 0.9876 0.0
Related task
Total circles area.
See also
Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
| #Yabasic | Yabasic |
sub twoCircles (x1, y1, x2, y2, radio)
if x1 = x2 and y1 = y2 then //Si los puntos coinciden
if radio = 0 then //a no ser que radio=0
print "Los puntos son los mismos\n"
return true
else
print "Hay cualquier numero de circulos a traves de un solo punto (", x1, ",", y1, ") de radio ", radio : print
return true
end if
end if
r2 = sqr((x1-x2)^2+(y1-y2)^2) / 2 //distancia media entre puntos
if radio < r2 then
print "Los puntos estan demasiado separados (", 2*r2, ") - no hay circulos de radio ", radio : print
return true
end if
//si no, calcular dos centros
cx = (x1+x2) / 2 //punto medio
cy = (y1+y2) / 2
//debe moverse desde el punto medio a lo largo de la perpendicular en dd2
dd2 = sqr(radio^2 - r2^2) //distancia perpendicular
dx1 = x2-cx //vector al punto medio
dy1 = y2-cy
dx = 0-dy1 / r2*dd2 //perpendicular:
dy = dx1 / r2*dd2 //rotar y escalar
print " -> Circulo 1 (", cx+dy, ", ", cy+dx, ")" //dos puntos, con (+)
print " -> Circulo 2 (", cx-dy, ", ", cy-dx, ")\n" //y (-)
end sub
for i = 1 to 5
read x1, y1, x2, y2, radio
print "Puntos ", "(", x1, ",", y1, "), (", x2, ",", y2, ")", ", Radio ", radio
twoCircles (x1, y1, x2, y2, radio)
next
end
//p1 p2 radio
data 0.1234, 0.9876, 0.8765, 0.2345, 2.0
data 0.0000, 2.0000, 0.0000, 0.0000, 1.0
data 0.1234, 0.9876, 0.1234, 0.9876, 2.0
data 0.1234, 0.9876, 0.8765, 0.2345, 0.5
data 0.1234, 0.9876, 0.1234, 0.9876, 0.0
|
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 unusual filename: `Abdu'l-Bahá.txt
| #Pike | Pike | import Stdio;
int main(){
if(exist("/var")){
write("/var exists!\n");
}
if(exist("file-exists.pike")){
write("I exist!\n");
}
} |
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 unusual filename: `Abdu'l-Bahá.txt
| #PL.2FI | PL/I | *Process source or(!);
/*********************************************************************
* 20.10.2013 Walter Pachl
* 'set dd:f=d:\_l\xxx.txt,recsize(300)'
* 'tex'
*********************************************************************/
tex: Proc Options(main);
Dcl fid Char(30) Var Init('D:\_l\tst.txt');
Dcl xxx Char(30) Var Init('D:\_l\nix.txt');
Dcl r Char(1000) Var;
Dcl f Record input;
On Undefinedfile(f) Goto label;
Open File(f) Title('/'!!fid);
Read file(f) Into(r);
Put Skip List('First line of file '!!fid!!': '!!r);
Close File(f);
Open File(f) Title('/'!!xxx);
Read file(f) Into(r);
Put Skip List(r);
Close File(f);
Label: Put Skip List('File '!!xxx!!' not found');
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 the corresponding character.
| #MATLAB_.2F_Octave | MATLAB / Octave | character = char(asciiNumber) |
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 the corresponding character.
| #Maxima | Maxima | ascii(65);
"A"
cint("A");
65 |
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 few values to it.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Sidef | Sidef | # creating an empty array and adding values
var a = [] #=> []
a[0] = 1 #=> [1]
a[3] = "abc" #=> [1, nil, nil, "abc"]
a << 3.14 #=> [1, nil, nil, "abc", 3.14] |
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, as a type, has the values and operations of its own.
The operations of are usually called methods of the root type.
Both operations and values are called polymorphic.
A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument.
The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual.
Operations with multiple arguments and/or the results of the class are called multi-methods.
A further generalization of is the operation with arguments and/or results from different classes.
single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x).
multiple-dispatch languages allow many arguments and/or results to control the dispatch.
A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type.
This type is sometimes called the most specific type of a [polymorphic] value.
The type tag of the value is used in order to resolve the dispatch.
The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class.
In many OO languages
the type of the class of T and T itself are considered equivalent.
In some languages they are distinct (like in Ada).
When class T and T are equivalent, there is no way to distinguish
polymorphic and specific values.
Task
Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
| #zkl | zkl | class C{ // define class named "C", no parents or attributes
println("starting construction"); // all code outside functions is wrapped into the constructor
var v; // instance data for this class
fcn init(x) // initializer for this class, calls constructor
{ v = x }
println("ending construction of ",self);
}
c1:=C(5); // create a new instance of C
c2:=c1("hoho"); // create another instance of C
println(C.v," ",c1.v," ",c2.v); |
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, as a type, has the values and operations of its own.
The operations of are usually called methods of the root type.
Both operations and values are called polymorphic.
A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument.
The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual.
Operations with multiple arguments and/or the results of the class are called multi-methods.
A further generalization of is the operation with arguments and/or results from different classes.
single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x).
multiple-dispatch languages allow many arguments and/or results to control the dispatch.
A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type.
This type is sometimes called the most specific type of a [polymorphic] value.
The type tag of the value is used in order to resolve the dispatch.
The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class.
In many OO languages
the type of the class of T and T itself are considered equivalent.
In some languages they are distinct (like in Ada).
When class T and T are equivalent, there is no way to distinguish
polymorphic and specific values.
Task
Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
| #zonnon | zonnon |
module Graphics;
type
{ref,public} (* class *)
Point = object(ord,abs: integer)
var
(* instance variables *)
{public,immutable} x,y: integer;
(* method *)
procedure {public} Ord():integer;
begin
return y
end Ord;
(* method *)
procedure {public} Abs():integer;
begin
return x
end Abs;
(* constructor *)
begin
self.x := ord;
self.y := abs;
end Point;
end Graphics.
module Main;
import Graphics;
var
p: Graphics.Point;
procedure Write(p: Graphics.Point);
begin
writeln('[':1,p.x:3,',':1,p.y:3,']':1)
end Write;
begin
p := new Graphics.Point(12,12);
Write(p);
writeln("Abs: ":4,p.Abs():3," Ord: ":5,p.Ord():3);
end Main.
|
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 their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.
If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language.
If the points are too far apart then no circles can be drawn.
Task detail
Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned.
Show here the output for the following inputs:
p1 p2 r
0.1234, 0.9876 0.8765, 0.2345 2.0
0.0000, 2.0000 0.0000, 0.0000 1.0
0.1234, 0.9876 0.1234, 0.9876 2.0
0.1234, 0.9876 0.8765, 0.2345 0.5
0.1234, 0.9876 0.1234, 0.9876 0.0
Related task
Total circles area.
See also
Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
| #zkl | zkl | fcn findCircles(a,b, c,d, r){ //-->T(T(x,y,r) [,T(x,y,r)]))
delta:=(a-c).hypot(b-d);
switch(delta){ // could just catch MathError
case(0.0){"singularity"} // should use epsilon test
case(r*2){T(T((a+c)/2,(b+d)/2,r))}
else{
if(delta > 2*r) "Point delta > diameter";
else{
md:=(r.pow(2) - (delta/2).pow(2)).sqrt();
T(T((a+c)/2 + md*(b-d)/delta,(b+d)/2 + md*(c-b)/delta,r),
T((a+c)/2 - md*(b-d)/delta,(b+d)/2 - md*(c-b)/delta,r));
}
}
}
}
data:=T(
T(0.1234, 0.9876, 0.8765, 0.2345, 2.0),
T(0.0000, 2.0000, 0.0000, 0.0000, 1.0),
T(0.1234, 0.9876, 0.1234, 0.9876, 2.0),
T(0.1234, 0.9876, 0.8765, 0.2345, 0.5),
T(0.1234, 0.9876, 0.1234, 0.9876, 0.0),
);
ppFmt:="(%2.4f,%2.4f)";
pprFmt:=ppFmt+" r=%2.1f";
foreach a,b, c,d, r in (data){
println("Points: ",ppFmt.fmt(a,b),", ",pprFmt.fmt(c,d,r));
print(" Circles: ");
cs:=findCircles(a,b,c,d,r);
if(List.isType(cs))
print(cs.pump(List,'wrap(c){pprFmt.fmt(c.xplode())}).concat(", "));
else print(cs);
println();
} |
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 unusual filename: `Abdu'l-Bahá.txt
| #PL.2FM | PL/M | 100H:
DECLARE FCB$SIZE LITERALLY '36';
BDOS: PROCEDURE( FN, ARG )BYTE; /* CP/M BDOS SYSTEM CALL, RETURNS A VALUE */
DECLARE FN BYTE, ARG ADDRESS;
GOTO 5;
END BDOS;
BDOS$P: PROCEDURE( FN, ARG ); /* CP/M BDOS SYSTEM CALL, NO RETURN VALUE */
DECLARE FN BYTE, ARG ADDRESS;
GOTO 5;
END BDOS$P;
PRINT$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS$P( 2, C ); END;
PRINT$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS$P( 9, S ); END;
PRINT$NL: PROCEDURE; CALL PRINT$STRING( .( 0DH, 0AH, '$' ) ); END;
SEARCH$FIRST: PROCEDURE( FCB )BYTE; /* RETURN 0, 1, 2, 3 IF FILE IN FCB */
DECLARE FCB ADDRESS; /* EXISTS, 255 OTHERWISE */
RETURN BDOS( 17, FCB );
END SEARCH$FIRST ;
INIT$FCB: PROCEDURE( FCB, NAME ); /* INITIALISE A FILE-CONTROL-BLOCK */
DECLARE ( FCB, NAME ) ADDRESS; /* SETTING THE FILE NAME */
DECLARE ( F$PTR, N$PTR, X$PTR ) ADDRESS;
DECLARE F BASED F$PTR BYTE, N BASED N$PTR BYTE;
DECLARE BLANKS ( 5 )BYTE INITIAL( ' ', ' ', ' ', ' ', '$' );
X$PTR = .BLANKS;
N$PTR = NAME + 1;
F$PTR = FCB;
IF N <> ':' THEN DO; /* NO DRIVE LETTER */
F = 0;
N$PTR = NAME;
END;
ELSE DO; /* FIRST CHAR IS THE DRIVE LETTER */
N$PTR = NAME;
F = ( N + 1 ) - 'A';
N$PTR = N$PTR + 2;
END;
DO F$PTR = FCB + 1 TO FCB + 8; /* NAME */
IF N = '$' THEN N$PTR = .BLANKS;
ELSE IF N = '.' THEN DO; /* START OF THE EXTENSION */
X$PTR = N$PTR + 1;
N$PTR = .BLANKS;
END;
F = N;
N$PTR = N$PTR + 1;
END;
N$PTR = X$PTR; /* EXTENSION */
DO F$PTR = FCB + 9 TO FCB + 11;
IF N = '$' THEN N$PTR =.BLANKS;
F = N;
N$PTR = N$PTR + 1;
END;
DO F$PTR = FCB + 12 TO FCB + ( FCB$SIZE - 1 ); /* OTHER FIELDS */
F = 0;
END;
END INIT$FCB ;
EXISTS: PROCEDURE( FCB )BYTE; /* RETURNS TRUE IF THE FILE NAMED IN THE */
DECLARE FCB ADDRESS; /* FCB EXISTS */
RETURN ( SEARCH$FIRST( FCB ) < 4 );
END EXISTS ;
DECLARE FCB$1$DATA ( FCB$SIZE )BYTE; /* DECLARE A FILE-CONTROL-BLOCK */
DECLARE FCB$1 ADDRESS;
FCB$1 = .FCB$1$DATA;
/* CP/M DOES NOT HAVE DIRECTORIES/FOLDERS - THIS TESTS FOR INPUT.TXT IN */
/* THE CURRENT DEFAULT DRIVE */
CALL INIT$FCB( FCB$1, .'INPUT.TXT$' );
CALL PRINT$STRING( .'INPUT.TXT: $' );
IF EXISTS( FCB$1 ) THEN CALL PRINT$STRING( .'EXISTS$' );
ELSE CALL PRINT$STRING( .'DOES NOT EXIST$' );
CALL PRINT$NL;
/* CHECK FOR INPUT.TXT IN THE D: DRIVE */
/* !!! THIS WILL CAUSE AN ERROR IF THERE IS NO DRIVE D: !!! */
/* !!! OR THERE IS NO DISC IN DRIVE D: !!! */
CALL INIT$FCB( FCB$1, .'D:INPUT.TXT$' );
CALL PRINT$STRING( .'D:INPUT.TXT: $' );
IF EXISTS( FCB$1 ) THEN CALL PRINT$STRING( .'EXISTS$' );
ELSE CALL PRINT$STRING( .'DOES NOT EXIST$' );
CALL PRINT$NL;
EOF |
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 unusual filename: `Abdu'l-Bahá.txt
| #Pop11 | Pop11 | sys_file_exists('input.txt') =>
sys_file_exists('/input.txt') =>
sys_file_exists('docs') =>
sys_file_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 the corresponding character.
| #Metafont | Metafont | message "enter a letter: ";
string a;
a := readstring;
message decimal (ASCII a); % writes the decimal number of the first character
% of the string a
message "enter a number: ";
num := scantokens readstring;
message char num; % num can be anything between 0 and 255; what will be seen
% on output depends on the encoding used by the "terminal"; e.g.
% any code beyond 127 when UTF-8 encoding is in use will give
% a bad encoding; e.g. to see correctly an "è", we should write
message char10; % (this add a newline...)
message char hex"c3" & char hex"a8"; % since C3 A8 is the UTF-8 encoding for "è"
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 the corresponding character.
| #Microsoft_Small_Basic | Microsoft Small Basic | TextWindow.WriteLine("The ascii code for 'A' is: " + Text.GetCharacterCode("A") + ".")
TextWindow.WriteLine("The character for '65' is: " + Text.GetCharacter(65) + ".") |
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 few values to it.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Slate | Slate | {1. 2. 3. 4. 5} collect: [|:x| x + 1]. "--> {2. 3. 4. 5. 6}"
{1. 2. 3. 4. 5} select: #isOdd `er. "--> {1. 3. 5}"
({3. 2. 7} collect: #+ `er <- 3) sort. "--> {"SortedArray traitsWindow" 5. 6. 10}"
ExtensibleArray new `>> [addLast: 3. addFirst: 4. ]. "--> {"ExtensibleArray traitsWindow" 4. 3}" |
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 their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.
If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language.
If the points are too far apart then no circles can be drawn.
Task detail
Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned.
Show here the output for the following inputs:
p1 p2 r
0.1234, 0.9876 0.8765, 0.2345 2.0
0.0000, 2.0000 0.0000, 0.0000 1.0
0.1234, 0.9876 0.1234, 0.9876 2.0
0.1234, 0.9876 0.8765, 0.2345 0.5
0.1234, 0.9876 0.1234, 0.9876 0.0
Related task
Total circles area.
See also
Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 FOR i=1 TO 5
20 READ x1,y1,x2,y2,r
30 PRINT i;") ";x1;" ";y1;" ";x2;" ";y2;" ";r
40 GO SUB 1000
50 NEXT i
60 STOP
70 DATA 0.1234,0.9876,0.8765,0.2345,2.0
80 DATA 0.0000,2.0000,0.0000,0.0000,1.0
90 DATA 0.1234,0.9876,0.1234,0.9876,2.0
100 DATA 0.1234,0.9876,0.8765,0.2345,0.5
110 DATA 0.1234,0.9876,0.1234,0.9876,0.0
1000 IF NOT (x1=x2 AND y1=y2) THEN GO TO 1090
1010 IF r=0 THEN PRINT "It will be a single point (";x1;",";y1;") of radius 0": RETURN
1020 PRINT "There are any number of circles via single point (";x1;",";y1;") of radius ";r: RETURN
1090 LET p1=(x1-x2): LET p2=(y1-y2)
1100 LET r2=SQR (p1*p1+p2*p2)/2
1110 IF r<r2 THEN PRINT "Points are too far apart (";2*r2;") - there are no circles of radius ";r: RETURN
1120 LET cx=(x1+x2)/2
1130 LET cy=(y1+y2)/2
1140 LET dd2=SQR (r^2-r2^2)
1150 LET dx1=x2-cx
1160 LET dy1=y2-cy
1170 LET dx=0-dy1/r2*dd2
1180 LET dy=dx1/r2*dd2
1190 PRINT "(";cx+dy;",";cy+dx;")"
1200 PRINT "(";cx-dy;",";cy-dx;")"
1210 RETURN |
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 unusual filename: `Abdu'l-Bahá.txt
| #PowerShell | PowerShell | if (Test-Path -Path .\input.txt) {
write-host "File input exist"
}
else {
write-host "File input doesn't 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 unusual filename: `Abdu'l-Bahá.txt
| #Prolog | Prolog |
exists_file('input.txt'),
exists_directory('docs').
exits_file('/input.txt'),
exists_directory('/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 the corresponding character.
| #Modula-2 | Modula-2 | MODULE asc;
IMPORT InOut;
VAR letter : CHAR;
ascii : CARDINAL;
BEGIN
letter := 'a';
InOut.Write (letter);
ascii := ORD (letter);
InOut.Write (11C); (* ASCII TAB *)
InOut.WriteCard (ascii, 8);
ascii := ascii - ORD ('0');
InOut.Write (11C); (* ASCII TAB *)
InOut.Write (CHR (ascii));
InOut.WriteLn
END asc. |
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 the corresponding character.
| #Modula-3 | Modula-3 | ORD('a') (* Returns 97 *)
VAL(97, CHAR); (* Returns '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 few values to it.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Smalltalk | Smalltalk | |anOrdered aBag aSet aSorted aSorted2 aDictionary|
anOrdered := OrderedCollection new.
anOrdered add: 1; add: 5; add: 3.
anOrdered printNl.
aBag := Bag new.
aBag add: 5; add: 5; add: 5; add: 6.
aBag printNl.
aSet := Set new.
aSet add: 10; add: 5; add: 5; add: 6; add: 10.
aSet printNl.
aSorted := SortedCollection new.
aSorted add: 10; add: 9; add: 8; add: 5.
aSorted printNl.
"another sorted with custom comparator: let's sort
the other collections according to their size (number of
elements)"
aSorted2 := SortedCollection sortBlock: [ :a :b |
(a size) < (b size) ].
aSorted2 add: anOrdered; add: aBag; add: aSet; add: aSorted.
aSorted2 printNl.
aDictionary := Dictionary new.
aDictionary at: 'OrderedCollection' put: anOrdered;
at: 'Bag' put: aBag;
at: 'Set' put: aSet;
at: 'SortedCollection' put: { aSorted. aSorted2 }.
aDictionary printNl. |
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 unusual filename: `Abdu'l-Bahá.txt
| #PureBasic | PureBasic | result = ReadFile(#PB_Any, "input.txt")
If result>0 : Debug "this local file exists"
Else : Debug "result=" +Str(result) +" so this local file is missing"
EndIf
result = ReadFile(#PB_Any, "/input.txt")
If result>0 : Debug "this root file exists"
Else : Debug "result=" +Str(result) +" so this root file is missing"
EndIf
result = ExamineDirectory(#PB_Any,"docs","")
If result>0 : Debug "this local directory exists"
Else : Debug "result=" +Str(result) +" so this local directory is missing"
EndIf
result = ExamineDirectory(#PB_Any,"/docs","")
If result>0 : Debug "this root directory exists"
Else : Debug "result=" +Str(result) +" so this root directory is missing"
EndIf |
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 unusual filename: `Abdu'l-Bahá.txt
| #Python | Python | import os
os.path.isfile("input.txt")
os.path.isfile("/input.txt")
os.path.isdir("docs")
os.path.isdir("/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 the corresponding character.
| #MUMPS | MUMPS | WRITE $ASCII("M")
WRITE $CHAR(77) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.