task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, 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.
| #Ruby | Ruby | class MyClass
def initialize
@instance_var = 0
end
def add_1
@instance_var += 1
end
end
my_class = MyClass.new #allocates an object and calls it's initialize method, then returns it.
|
http://rosettacode.org/wiki/Closest-pair_problem | Closest-pair problem |
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a function to find the closest two points among a set of given points in two dimensions, i.e. to solve the Closest pair of points problem in the planar case.
The straightforward solution is a O(n2) algorithm (which we can call brute-force algorithm); the pseudo-code (using indexes) could be simply:
bruteForceClosestPair of P(1), P(2), ... P(N)
if N < 2 then
return ∞
else
minDistance ← |P(1) - P(2)|
minPoints ← { P(1), P(2) }
foreach i ∈ [1, N-1]
foreach j ∈ [i+1, N]
if |P(i) - P(j)| < minDistance then
minDistance ← |P(i) - P(j)|
minPoints ← { P(i), P(j) }
endif
endfor
endfor
return minDistance, minPoints
endif
A better algorithm is based on the recursive divide&conquer approach, as explained also at Wikipedia's Closest pair of points problem, which is O(n log n); a pseudo-code could be:
closestPair of (xP, yP)
where xP is P(1) .. P(N) sorted by x coordinate, and
yP is P(1) .. P(N) sorted by y coordinate (ascending order)
if N ≤ 3 then
return closest points of xP using brute-force algorithm
else
xL ← points of xP from 1 to ⌈N/2⌉
xR ← points of xP from ⌈N/2⌉+1 to N
xm ← xP(⌈N/2⌉)x
yL ← { p ∈ yP : px ≤ xm }
yR ← { p ∈ yP : px > xm }
(dL, pairL) ← closestPair of (xL, yL)
(dR, pairR) ← closestPair of (xR, yR)
(dmin, pairMin) ← (dR, pairR)
if dL < dR then
(dmin, pairMin) ← (dL, pairL)
endif
yS ← { p ∈ yP : |xm - px| < dmin }
nS ← number of points in yS
(closest, closestPair) ← (dmin, pairMin)
for i from 1 to nS - 1
k ← i + 1
while k ≤ nS and yS(k)y - yS(i)y < dmin
if |yS(k) - yS(i)| < closest then
(closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)})
endif
k ← k + 1
endwhile
endfor
return closest, closestPair
endif
References and further readings
Closest pair of points problem
Closest Pair (McGill)
Closest Pair (UCSB)
Closest pair (WUStL)
Closest pair (IUPUI)
| #Ursala | Ursala | #import flo
clop = @iiK0 fleq$-&l+ *EZF ^\~& plus+ sqr~~+ minus~~bbI |
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points | Circles of given radius through two points |
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
Exceptions
r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
If the points are coincident then an infinite number of circles with the point on 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
| #Ring | Ring |
# Project : Circles of given radius through two points
decimals(4)
x1 = 0.1234
y1 = 0.9876
x2 = 0.8765
y2 = 0.2345
r = 2.0
see "1 : " + x1 + " " + y1 + " " + x2 + " " + y2 + " " + r + nl
twocircles(x1, y1, x2, y2, r)
x1 = 0.0000
y1 = 2.0000
x2 = 0.0000
y2 = 0.0000
r = 1.0
see "2 : " + x1 + " " + y1 + " " + x2 + " " + y2 + " " + r + nl
twocircles(x1, y1, x2, y2, r)
x1 = 0.1234
y1 = 0.9876
x2 = 0.1234
y2 = 0.9876
r = 2.0
see "3 : " + x1 + " " + y1 + " " + x2 + " " + y2 + " " + r + nl
twocircles(x1, y1, x2, y2, r)
x1 = 0.1234
y1 = 0.9876
x2 = 0.8765
y2 = 0.2345
r = 0.5
see "4 : " + x1 + " " + y1 + " " + x2 + " " + y2 + " " + r + nl
twocircles(x1, y1, x2, y2, r)
x1 = 0.1234
y1 = 0.9876
x2 = 0.1234
y2 = 0.9876
r= 0.0
see "5 : " + x1 + " " + y1 + " " + x2 + " " + y2 + " " + r + nl
twocircles(x1, y1, x2, y2, r)
func twocircles(x1, y1, x2, y2, r)
if x1=x2 and y1=y2
if r=0
see "It will be a single point (" + x1 + "," + y1 + ") of radius 0" + nl + nl
return
else
see "There are any number of circles via single point (" + x1 + "," + y1 + ") of radius " + r + nl + nl
return
ok
ok
r2 = sqrt(pow((x1-x2),2)+pow((y1-y2),2))/2
if r<r2
see "Points are too far apart (" + 2*r2 + ") - there are no circles of radius " + r + nl + nl
return
ok
cx=(x1+x2)/2
cy=(y1+y2)/2
dd2=sqrt(pow(r,2)-pow(r2,2))
dx1=x2-cx
dy1=y2-cy
dx = 0-dy1/r2*dd2
dy = dx1/r2*dd2
see "(" + (cx+dy) + ", " + (cy+dx) + ")" + nl
see "(" + (cx-dy) + ", " + (cy-dx) + ")" + nl + nl
|
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Tuesday, February 1, 2022 CE (in the common Gregorian calendar) will begin the lunisolar Year of the Tiger.
The celestial stems have no one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems each belong to one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element's governance is associated with yin, the other with yang.
Thus, 2022 is also the yang year of Water. Note that since 12 is an even number, the association between animals and yin/yang doesn't change. Consecutive Years of the Rooster will cycle through the five elements, but will always be yin, despite the apparent conceptual mismatch between the specifically-male English animal name and the female aspect denoted by yin.
Task
Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.
You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).
Requisite information
The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.
The element cycle runs in this order: Wood, Fire, Earth, Metal, Water.
The yang year precedes the yin year within each element.
The current 60-year cycle began in 1984 CE; the first cycle of the Common Era began in 4 CE.
Thus, 1984 was the year of the Wood Rat (yang), 1985 was the year of the Wood Ox (yin), and 1986 the year of the Fire Tiger (yang); 2022 - which, as already noted, is the year of the Water Tiger (yang) - is the 39th year of the current cycle.
Information for optional task
The ten celestial stems are 甲 jiă, 乙 yĭ, 丙 bĭng, 丁 dīng, 戊 wù, 己 jĭ, 庚 gēng, 辛 xīn, 壬 rén, and 癸 gŭi. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3".
The twelve terrestrial branches are 子 zĭ, 丑 chŏu, 寅 yín, 卯 măo, 辰 chén, 巳 sì, 午 wŭ, 未 wèi, 申 shēn, 酉 yŏu, 戌 xū, 亥 hài. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4".
Therefore 1984 was 甲子 (jiă-zĭ, or jia3-zi3). 2022 is 壬寅 (rén-yín or ren2-yin2).
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
ReadOnly ANIMALS As String() = {"Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"}
ReadOnly ELEMENTS As String() = {"Wood", "Fire", "Earth", "Metal", "Water"}
ReadOnly ANIMAL_CHARS As String() = {"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"}
ReadOnly ELEMENT_CHARS As String(,) = {{"甲", "丙", "戊", "庚", "壬"}, {"乙", "丁", "己", "辛", "癸"}}
Function GetYY(year As Integer) As String
If year Mod 2 = 0 Then
Return "yang"
End If
Return "yin"
End Function
Sub Main()
Console.OutputEncoding = System.Text.Encoding.UTF8
Dim years = {1935, 1938, 1968, 1972, 1976, 1984, 1985, 2017}
For i = 0 To years.Length - 1
Dim t0 = years(i)
Dim t1 = t0 - 4.0
Dim t2 = t1 Mod 10
Dim t3 = t2 / 2
Dim t4 = Math.Floor(t3)
Dim ei As Integer = Math.Floor(((years(i) - 4.0) Mod 10) / 2)
Dim ai = (years(i) - 4) Mod 12
Console.WriteLine("{0} is the year of the {1} {2} ({3}). {4}{5}", years(i), ELEMENTS(ei), ANIMALS(ai), GetYY(years(i)), ELEMENT_CHARS(years(i) Mod 2, ei), ANIMAL_CHARS((years(i) - 4) Mod 12))
Next
End Sub
End Module |
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
| #Logo | Logo | show file? "input.txt
show file? "/input.txt
show file? "docs
show file? "/docs |
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an unusual filename: `Abdu'l-Bahá.txt
| #Lua | Lua | function output( s, b )
if b then
print ( s, " does not exist." )
else
print ( s, " does exist." )
end
end
output( "input.txt", io.open( "input.txt", "r" ) == nil )
output( "/input.txt", io.open( "/input.txt", "r" ) == nil )
output( "docs", io.open( "docs", "r" ) == nil )
output( "/docs", io.open( "/docs", "r" ) == nil ) |
http://rosettacode.org/wiki/Chaos_game | Chaos game | The Chaos Game is a method of generating the attractor of an iterated function system (IFS).
One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.
Task
Play the Chaos Game using the corners of an equilateral triangle as the reference points. Add a starting point at random (preferably inside the triangle). Then add the next point halfway between the starting point and one of the reference points. This reference point is chosen at random.
After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.
See also
The Game of Chaos
| #Scilab | Scilab | //Input
n_sides = 3;
side_length = 1;
ratio = 0.5;
n_steps = 1.0d5;
first_step = 0;
if n_sides<3 then
error("n_sides should be at least 3.");
end
//Calculating vertices' positions
theta = (2 * %pi) / n_sides;
alpha = (180 - (360/n_sides)) / 2 * (%pi/180);
radius = (sin(theta) / side_length) / sin(alpha);
vertices = zeros(1,n_sides);
for i=1:n_sides
vertices(i) = radius * exp( %i * theta * (i-1) ); //equally spaced vertices over a circumference
//centered on 0 + 0i, or (0,0)
end
clear theta alpha radius i
//Iterations
tic();
points = zeros(1,n_steps);
points(1) = first_step;
i = 2;
while i <= n_steps
random=grand(1,'prm',[1:n_sides]'); //sort vertices randomly
random=random(1); //choose the first random vertices
points(i) = ( vertices(random) - points(i-1) ) * (1-ratio) + points(i-1);
i = i + 1;
end
time=toc();
disp('Time: '+string(time)+'s.');
//Ploting
scf(0); clf();
xname('Chaos game: '+string(n_sides)+'-sides polygon');
plot2d(real(points),imag(points),0)
plot2d(real(vertices),imag(vertices),-3);
set(gca(),'isoview','on'); |
http://rosettacode.org/wiki/Chaos_game | Chaos game | The Chaos Game is a method of generating the attractor of an iterated function system (IFS).
One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.
Task
Play the Chaos Game using the corners of an equilateral triangle as the reference points. Add a starting point at random (preferably inside the triangle). Then add the next point halfway between the starting point and one of the reference points. This reference point is chosen at random.
After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.
See also
The Game of Chaos
| #Sidef | Sidef | require('Imager')
var width = 600
var height = 600
var points = [
[width//2, 0],
[ 0, height-1],
[height-1, height-1],
]
var img = %O|Imager|.new(
xsize => width,
ysize => height,
)
var color = %O|Imager::Color|.new('#ff0000')
var r = [(width-1).irand, (height-1).irand]
30000.times {
var p = points.rand
r[] = (
(p[0] + r[0]) // 2,
(p[1] + r[1]) // 2,
)
img.setpixel(
x => r[0],
y => r[1],
color => color,
)
}
img.write(file => 'chaos_game.png') |
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.
| #Icon_and_Unicon | Icon and Unicon | procedure main(arglist)
if *arglist > 0 then L := arglist else L := [97, "a"]
every x := !L do
write(x, " ==> ", char(integer(x)) | ord(x) ) # char produces a character, ord produces a number
end |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #Io | Io | "a" at(0) println // --> 97
97 asCharacter println // --> a
"π" at(0) println // --> 960
960 asCharacter println // --> π |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square 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. | #Sidef | Sidef | func cholesky(matrix) {
var chol = matrix.len.of { matrix.len.of(0) }
for row in ^matrix {
for col in (0..row) {
var x = matrix[row][col]
for i in (0..col) {
x -= (chol[row][i] * chol[col][i])
}
chol[row][col] = (row == col ? x.sqrt : x/chol[col][col])
}
}
return chol
} |
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
| #PowerShell | PowerShell |
# Create an Array by separating the elements with commas:
$array = "one", 2, "three", 4
# Using explicit syntax:
$array = @("one", 2, "three", 4)
# Send the values back into individual variables:
$var1, $var2, $var3, $var4 = $array
# An array of several integer ([int]) values:
$array = 0, 1, 2, 3, 4, 5, 6, 7
# Using the range operator (..):
$array = 0..7
# Strongly typed:
[int[]] $stronglyTypedArray = 1, 2, 4, 8, 16, 32, 64, 128
# An empty array:
$array = @()
# An array with a single element:
$array = @("one")
# I suppose this would be a jagged array:
$jaggedArray = @((11, 12, 13),
(21, 22, 23),
(31, 32, 33))
$jaggedArray | Format-Wide {$_} -Column 3 -Force
$jaggedArray[1][1] # returns 22
# A Multi-dimensional array:
$multiArray = New-Object -TypeName "System.Object[,]" -ArgumentList 6,6
for ($i = 0; $i -lt 6; $i++)
{
for ($j = 0; $j -lt 6; $j++)
{
$multiArray[$i,$j] = ($i + 1) * 10 + ($j + 1)
}
}
$multiArray | Format-Wide {$_} -Column 6 -Force
$multiArray[2,2] # returns 33
|
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
| #Smalltalk | Smalltalk |
(0 to: 4) combinations: 3 atATimeDo: [ :x | Transcript cr; show: x printString].
"output on Transcript:
#(0 1 2)
#(0 1 3)
#(0 1 4)
#(0 2 3)
#(0 2 4)
#(0 3 4)
#(1 2 3)
#(1 2 4)
#(1 3 4)
#(2 3 4)"
|
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include 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.
| #Verbexx | Verbexx | @VAR a b = 1 2;
// -------------------------------------------------------------------------------------
// @IF verb (returns 0u0 = UNIT, if no then: or else: block is executed)
// ======== (note: both then: and else: keywords are optional)
@SAY "@IF 1 " ( @IF (a > b) then:{"then:"} else:{"else:"} );
@SAY "@IF 2 " ( @IF (b > a) else:{"else:"} then:{"then:"} );
@SAY "@IF 3 " ( @IF (a > b) then:{"then:"} );
@SAY "@IF 4 " ( @IF (b > a) then:{"then:"} );
@SAY "@IF 5 " ( @IF (a > b) else:{"else:"} );
@SAY "@IF 6 " ( @IF (b > a) else:{"else:"} );
@SAY "@IF 7 " ( @IF (b > a) );
// ---------------------------------------------------------------------------------
// ? verb (conditional operator)
// ====== ( 1st block (TRUE) is required, 2nd block (FALSE) is optional)
@SAY "? 1 " ( (a < b) ? {"1st"} {"2nd"} );
@SAY "? 2 " ( (a > b) ? {"1st"} {"2nd"} );
@SAY "? 3 " ( (a < b) ? {"1st"} );
@SAY "? 4 " ( (a > b) ? {"1st"} );
// -----------------------------------------------------------------------------------
// @CASE verb
// ==========
//
// - executes code block for first when: condition that evaluates to TRUE
//
// - normally, ends after running that code block
//
// - if no when: conditions are true, executes else: code block (if present)
//
// - can exit a when: block with @CONTINUE case: verb -- causes @CASE to continue
// looking for more true when: blocks or the else: block
@VAR n = 0;
@LOOP times:3
{
@SAY ( "n =" n " @CASE results:"
( @CASE
when:(n == 0) { "n == 0(1)" }
when:(n == 0) { "n == 0(2)" }
when:(n == 1) { "n == 1(1)"; @CONTINUE case: }
when:(n == 1) { "n == 1(2c)" }
else: { "else" }
)
)
;
n++;
};
/] -----------------------------------------------------------------------
Output:
@IF 1 else:
@IF 2 then:
@IF 3 0_u0
@IF 4 then:
@IF 5 else:
@IF 6 0_u0
@IF 7 0_u0
? 1 1st
? 2 2nd
? 3 1st
? 4 0_u0
n = 0 @CASE results: n == 0(1)
n = 1 @CASE results: n == 1(2c)
n = 2 @CASE results: else |
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
{\displaystyle a_{2}}
,
…
{\displaystyle \dots }
,
a
k
{\displaystyle a_{k}}
, there exists an integer
x
{\displaystyle x}
solving the following system of simultaneous congruences:
x
≡
a
1
(
mod
n
1
)
x
≡
a
2
(
mod
n
2
)
⋮
x
≡
a
k
(
mod
n
k
)
{\displaystyle {\begin{aligned}x&\equiv a_{1}{\pmod {n_{1}}}\\x&\equiv a_{2}{\pmod {n_{2}}}\\&{}\ \ \vdots \\x&\equiv a_{k}{\pmod {n_{k}}}\end{aligned}}}
Furthermore, all solutions
x
{\displaystyle x}
of this system are congruent modulo the product,
N
=
n
1
n
2
…
n
k
{\displaystyle N=n_{1}n_{2}\ldots n_{k}}
.
Task
Write a program to solve a system of linear congruences by applying the Chinese Remainder Theorem.
If the system of equations cannot be solved, your program must somehow indicate this.
(It may throw an exception or return a special false value.)
Since there are infinitely many solutions, the program should return the unique solution
s
{\displaystyle s}
where
0
≤
s
≤
n
1
n
2
…
n
k
{\displaystyle 0\leq s\leq n_{1}n_{2}\ldots n_{k}}
.
Show the functionality of this program by printing the result such that the
n
{\displaystyle n}
's are
[
3
,
5
,
7
]
{\displaystyle [3,5,7]}
and the
a
{\displaystyle a}
's are
[
2
,
3
,
2
]
{\displaystyle [2,3,2]}
.
Algorithm: The following algorithm only applies if the
n
i
{\displaystyle n_{i}}
's are pairwise co-prime.
Suppose, as above, that a solution is required for the system of congruences:
x
≡
a
i
(
mod
n
i
)
f
o
r
i
=
1
,
…
,
k
{\displaystyle x\equiv a_{i}{\pmod {n_{i}}}\quad \mathrm {for} \;i=1,\ldots ,k}
Again, to begin, the product
N
=
n
1
n
2
…
n
k
{\displaystyle N=n_{1}n_{2}\ldots n_{k}}
is defined.
Then a solution
x
{\displaystyle x}
can be found as follows:
For each
i
{\displaystyle i}
, the integers
n
i
{\displaystyle n_{i}}
and
N
/
n
i
{\displaystyle N/n_{i}}
are co-prime.
Using the Extended Euclidean algorithm, we can find integers
r
i
{\displaystyle r_{i}}
and
s
i
{\displaystyle s_{i}}
such that
r
i
n
i
+
s
i
N
/
n
i
=
1
{\displaystyle r_{i}n_{i}+s_{i}N/n_{i}=1}
.
Then, one solution to the system of simultaneous congruences is:
x
=
∑
i
=
1
k
a
i
s
i
N
/
n
i
{\displaystyle x=\sum _{i=1}^{k}a_{i}s_{i}N/n_{i}}
and the minimal solution,
x
(
mod
N
)
{\displaystyle x{\pmod {N}}}
.
| #VBA | VBA | Private Function chinese_remainder(n As Variant, a As Variant) As Variant
Dim p As Long, prod As Long, tot As Long
prod = 1: tot = 0
For i = 1 To UBound(n)
prod = prod * n(i)
Next i
Dim m As Variant
For i = 1 To UBound(n)
p = prod / n(i)
m = mul_inv(p, n(i))
If WorksheetFunction.IsText(m) Then
chinese_remainder = "fail"
Exit Function
End If
tot = tot + a(i) * m * p
Next i
chinese_remainder = tot Mod prod
End Function
Public Sub re()
Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])
Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])
Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])
Debug.Print chinese_remainder([{100,23}], [{19,0}])
End Sub |
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.
| #Rust | Rust |
struct MyClass {
variable: i32, // member variable = instance variable
}
impl MyClass {
// member function = method, with its implementation
fn some_method(&mut self) {
self.variable = 1;
}
// constructor, with its implementation
fn new() -> MyClass {
// Here could be more code.
MyClass { variable: 0 }
}
}
fn main () {
// Create an instance in the stack.
let mut instance = MyClass::new();
// Create an instance in the heap.
let mut p_instance = Box::new(MyClass::new());
// Invoke method on both istances,
instance.some_method();
p_instance.some_method();
// Both instances are automatically deleted when their scope ends.
}
|
http://rosettacode.org/wiki/Closest-pair_problem | Closest-pair problem |
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a function to find the closest two points among a set of given points in two dimensions, i.e. to solve the Closest pair of points problem in the planar case.
The straightforward solution is a O(n2) algorithm (which we can call brute-force algorithm); the pseudo-code (using indexes) could be simply:
bruteForceClosestPair of P(1), P(2), ... P(N)
if N < 2 then
return ∞
else
minDistance ← |P(1) - P(2)|
minPoints ← { P(1), P(2) }
foreach i ∈ [1, N-1]
foreach j ∈ [i+1, N]
if |P(i) - P(j)| < minDistance then
minDistance ← |P(i) - P(j)|
minPoints ← { P(i), P(j) }
endif
endfor
endfor
return minDistance, minPoints
endif
A better algorithm is based on the recursive divide&conquer approach, as explained also at Wikipedia's Closest pair of points problem, which is O(n log n); a pseudo-code could be:
closestPair of (xP, yP)
where xP is P(1) .. P(N) sorted by x coordinate, and
yP is P(1) .. P(N) sorted by y coordinate (ascending order)
if N ≤ 3 then
return closest points of xP using brute-force algorithm
else
xL ← points of xP from 1 to ⌈N/2⌉
xR ← points of xP from ⌈N/2⌉+1 to N
xm ← xP(⌈N/2⌉)x
yL ← { p ∈ yP : px ≤ xm }
yR ← { p ∈ yP : px > xm }
(dL, pairL) ← closestPair of (xL, yL)
(dR, pairR) ← closestPair of (xR, yR)
(dmin, pairMin) ← (dR, pairR)
if dL < dR then
(dmin, pairMin) ← (dL, pairL)
endif
yS ← { p ∈ yP : |xm - px| < dmin }
nS ← number of points in yS
(closest, closestPair) ← (dmin, pairMin)
for i from 1 to nS - 1
k ← i + 1
while k ≤ nS and yS(k)y - yS(i)y < dmin
if |yS(k) - yS(i)| < closest then
(closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)})
endif
k ← k + 1
endwhile
endfor
return closest, closestPair
endif
References and further readings
Closest pair of points problem
Closest Pair (McGill)
Closest Pair (UCSB)
Closest pair (WUStL)
Closest pair (IUPUI)
| #VBA | VBA | Option Explicit
Private Type MyPoint
X As Single
Y As Single
End Type
Private Type MyPair
p1 As MyPoint
p2 As MyPoint
End Type
Sub Main()
Dim points() As MyPoint, i As Long, BF As MyPair, d As Single, Nb As Long
Dim T#
Randomize Timer
Nb = 10
Do
ReDim points(1 To Nb)
For i = 1 To Nb
points(i).X = Rnd * Nb
points(i).Y = Rnd * Nb
Next
d = 1000000000000#
T = Timer
BF = BruteForce(points, d)
Debug.Print "For " & Nb & " points, runtime : " & Timer - T & " sec."
Debug.Print "point 1 : X:" & BF.p1.X & " Y:" & BF.p1.Y
Debug.Print "point 2 : X:" & BF.p2.X & " Y:" & BF.p2.Y
Debug.Print "dist : " & d
Debug.Print "--------------------------------------------------"
Nb = Nb * 10
Loop While Nb <= 10000
End Sub
Private Function BruteForce(p() As MyPoint, mindist As Single) As MyPair
Dim i As Long, j As Long, d As Single, ClosestPair As MyPair
For i = 1 To UBound(p) - 1
For j = i + 1 To UBound(p)
d = Dist(p(i), p(j))
If d < mindist Then
mindist = d
ClosestPair.p1 = p(i)
ClosestPair.p2 = p(j)
End If
Next
Next
BruteForce = ClosestPair
End Function
Private Function Dist(p1 As MyPoint, p2 As MyPoint) As Single
Dist = Sqr((p1.X - p2.X) ^ 2 + (p1.Y - p2.Y) ^ 2)
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
| #Ruby | Ruby | Pt = Struct.new(:x, :y)
Circle = Struct.new(:x, :y, :r)
def circles_from(pt1, pt2, r)
raise ArgumentError, "Infinite number of circles, points coincide." if pt1 == pt2 && r > 0
# handle single point and r == 0
return [Circle.new(pt1.x, pt1.y, r)] if pt1 == pt2 && r == 0
dx, dy = pt2.x - pt1.x, pt2.y - pt1.y
# distance between points
q = Math.hypot(dx, dy)
# Also catches pt1 != pt2 && r == 0
raise ArgumentError, "Distance of points > diameter." if q > 2.0*r
# halfway point
x3, y3 = (pt1.x + pt2.x)/2.0, (pt1.y + pt2.y)/2.0
d = (r**2 - (q/2)**2)**0.5
[Circle.new(x3 - d*dy/q, y3 + d*dx/q, r),
Circle.new(x3 + d*dy/q, y3 - d*dx/q, r)].uniq
end
# Demo:
ar = [[Pt.new(0.1234, 0.9876), Pt.new(0.8765, 0.2345), 2.0],
[Pt.new(0.0000, 2.0000), Pt.new(0.0000, 0.0000), 1.0],
[Pt.new(0.1234, 0.9876), Pt.new(0.1234, 0.9876), 2.0],
[Pt.new(0.1234, 0.9876), Pt.new(0.8765, 0.2345), 0.5],
[Pt.new(0.1234, 0.9876), Pt.new(0.1234, 0.9876), 0.0]]
ar.each do |p1, p2, r|
print "Given points:\n #{p1.values},\n #{p2.values}\n and radius #{r}\n"
begin
circles = circles_from(p1, p2, r)
puts "You can construct the following circles:"
circles.each{|c| puts " #{c}"}
rescue ArgumentError => e
puts e
end
puts
end |
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Tuesday, February 1, 2022 CE (in the common Gregorian calendar) will begin the lunisolar Year of the Tiger.
The celestial stems have no one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems each belong to one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element's governance is associated with yin, the other with yang.
Thus, 2022 is also the yang year of Water. Note that since 12 is an even number, the association between animals and yin/yang doesn't change. Consecutive Years of the Rooster will cycle through the five elements, but will always be yin, despite the apparent conceptual mismatch between the specifically-male English animal name and the female aspect denoted by yin.
Task
Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.
You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).
Requisite information
The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.
The element cycle runs in this order: Wood, Fire, Earth, Metal, Water.
The yang year precedes the yin year within each element.
The current 60-year cycle began in 1984 CE; the first cycle of the Common Era began in 4 CE.
Thus, 1984 was the year of the Wood Rat (yang), 1985 was the year of the Wood Ox (yin), and 1986 the year of the Fire Tiger (yang); 2022 - which, as already noted, is the year of the Water Tiger (yang) - is the 39th year of the current cycle.
Information for optional task
The ten celestial stems are 甲 jiă, 乙 yĭ, 丙 bĭng, 丁 dīng, 戊 wù, 己 jĭ, 庚 gēng, 辛 xīn, 壬 rén, and 癸 gŭi. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3".
The twelve terrestrial branches are 子 zĭ, 丑 chŏu, 寅 yín, 卯 măo, 辰 chén, 巳 sì, 午 wŭ, 未 wèi, 申 shēn, 酉 yŏu, 戌 xū, 亥 hài. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4".
Therefore 1984 was 甲子 (jiă-zĭ, or jia3-zi3). 2022 is 壬寅 (rén-yín or ren2-yin2).
| #Vlang | Vlang | const (
animal_string = ["Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake",
"Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"]
stem_yy_string = ["Yang", "Yin"]
element_string = ["Wood", "Fire", "Earth", "Metal", "Water"]
stem_ch = "甲乙丙丁戊己庚辛壬癸".split('')
branch_ch = "子丑寅卯辰巳午未申酉戌亥".split('')
)
fn cz(y int) (string, string, string, string, int) {
yr := y-4
stem := yr % 10
branch := yr % 12
return animal_string[branch],
stem_yy_string[stem%2],
element_string[stem/2],
[stem_ch[stem], branch_ch[branch]].join(''),
yr%60 + 1
}
fn main() {
for yr in [1935, 1938, 1968, 1972, 1976] {
a, yy, e, sb, cy := cz(yr)
println("$yr: $e $a, $yy, Cycle year $cy $sb")
}
} |
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Tuesday, February 1, 2022 CE (in the common Gregorian calendar) will begin the lunisolar Year of the Tiger.
The celestial stems have no one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems each belong to one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element's governance is associated with yin, the other with yang.
Thus, 2022 is also the yang year of Water. Note that since 12 is an even number, the association between animals and yin/yang doesn't change. Consecutive Years of the Rooster will cycle through the five elements, but will always be yin, despite the apparent conceptual mismatch between the specifically-male English animal name and the female aspect denoted by yin.
Task
Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.
You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).
Requisite information
The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.
The element cycle runs in this order: Wood, Fire, Earth, Metal, Water.
The yang year precedes the yin year within each element.
The current 60-year cycle began in 1984 CE; the first cycle of the Common Era began in 4 CE.
Thus, 1984 was the year of the Wood Rat (yang), 1985 was the year of the Wood Ox (yin), and 1986 the year of the Fire Tiger (yang); 2022 - which, as already noted, is the year of the Water Tiger (yang) - is the 39th year of the current cycle.
Information for optional task
The ten celestial stems are 甲 jiă, 乙 yĭ, 丙 bĭng, 丁 dīng, 戊 wù, 己 jĭ, 庚 gēng, 辛 xīn, 壬 rén, and 癸 gŭi. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3".
The twelve terrestrial branches are 子 zĭ, 丑 chŏu, 寅 yín, 卯 măo, 辰 chén, 巳 sì, 午 wŭ, 未 wèi, 申 shēn, 酉 yŏu, 戌 xū, 亥 hài. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4".
Therefore 1984 was 甲子 (jiă-zĭ, or jia3-zi3). 2022 is 壬寅 (rén-yín or ren2-yin2).
| #Wren | Wren | import "/fmt" for Fmt
class ChineseZodiac {
static init() {
__animals = ["Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake",
"Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"]
__aspects = ["Yang","Yin"]
__elements = ["Wood", "Fire", "Earth", "Metal", "Water"]
__stems = ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"]
__branches = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"]
__sNames = ["jiă", "yĭ", "bĭng", "dīng", "wù", "jĭ", "gēng", "xīn", "rén", "gŭi"]
__bNames = ["zĭ", "chŏu", "yín", "măo", "chén", "sì", "wŭ", "wèi", "shēn", "yŏu", "xū", "hài"]
}
construct new(year) {
var y = year - 4
var s = y % 10
var b = y % 12
_year = year
_stem = __stems[s]
_branch = __branches[b]
_sName = __sNames[s]
_bName = __bNames[b]
_element = __elements[(s/2).floor]
_animal = __animals[b]
_aspect = __aspects[s % 2]
_cycle = y % 60 + 1
}
toString {
var name = Fmt.s(-9, _sName + "-" + _bName)
var elem = Fmt.s(-7, _element)
var anim = Fmt.s(-7, _animal)
var aspt = Fmt.s(-6, _aspect)
var cycl = Fmt.dz(2, _cycle) + "/60"
return "%(_year) %(_stem)%(_branch) %(name) %(elem) %(anim) %(aspt) %(cycl)"
}
}
var years = [1935, 1938, 1968, 1972, 1976, 1984, 2017, 2020]
System.print("Year Chinese Pinyin Element Animal Aspect Cycle")
System.print("---- ------- --------- ------- ------- ------ -----")
ChineseZodiac.init()
for (year in years) System.print(ChineseZodiac.new(year)) |
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
| #M2000_Interpreter | M2000 Interpreter |
Module ExistDirAndFile {
Let WorkingDir$=Dir$, RootDir$="C:\"
task(WorkingDir$)
task(RootDir$)
Dir User ' return to user directroy
Sub task(WorkingDir$)
Local counter
Dir WorkingDir$
If Not Exist.Dir("docs") then Report "docs not exist in "+WorkingDir$ : counter++
If Not Exist("output.txt") Then {
Report "output.txt not exist in "+ WorkingDir$ : counter++
} Else.if Filelen("output.txt")=0 Then Report "output.txt has zero length"
If counter =0 then Report WorkingDir$+ " has docs directory and file output.txt"
End Sub
}
ExistDirAndFile
|
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
| #Maple | Maple | with(FileTools):
Exists("input.txt");
Exists("docs") and IsDirectory("docs");
Exists("/input.txt");
Exists("/docs") and IsDirectory("/docs"); |
http://rosettacode.org/wiki/Chaos_game | Chaos game | The Chaos Game is a method of generating the attractor of an iterated function system (IFS).
One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.
Task
Play the Chaos Game using the corners of an equilateral triangle as the reference points. Add a starting point at random (preferably inside the triangle). Then add the next point halfway between the starting point and one of the reference points. This reference point is chosen at random.
After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.
See also
The Game of Chaos
| #Simula | Simula | BEGIN
INTEGER U, COLUMNS, LINES;
COLUMNS := 40;
LINES := 80;
U := ININT;
BEGIN
CHARACTER ARRAY SCREEN(0:LINES, 0:COLUMNS);
INTEGER X, Y, I, VERTEX;
FOR X := 0 STEP 1 UNTIL LINES-1 DO
FOR Y := 0 STEP 1 UNTIL COLUMNS-1 DO
SCREEN(X, Y) := ' ';
X := RANDINT(0, LINES - 1, U);
Y := RANDINT(0, COLUMNS - 1, U);
FOR I := 1 STEP 1 UNTIL 5000 DO
BEGIN
VERTEX := RANDINT(1, 3, U);
IF VERTEX = 1 THEN BEGIN X := X // 2;
Y := Y // 2;
END ELSE
IF VERTEX = 2 THEN BEGIN X := LINES // 2 + (LINES // 2 - X) // 2;
Y := COLUMNS - (COLUMNS - Y) // 2;
END ELSE
IF VERTEX = 3 THEN BEGIN X := LINES - (LINES - X) // 2;
Y := Y // 2;
END ELSE ERROR("VERTEX OUT OF BOUNDS");
SCREEN(X, Y) := 'X';
END;
FOR Y := 0 STEP 1 UNTIL COLUMNS-1 DO
BEGIN
FOR X := 0 STEP 1 UNTIL LINES-1 DO
OUTCHAR(SCREEN(X, Y));
OUTIMAGE;
END;
END;
END
|
http://rosettacode.org/wiki/Chaos_game | Chaos game | The Chaos Game is a method of generating the attractor of an iterated function system (IFS).
One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.
Task
Play the Chaos Game using the corners of an equilateral triangle as the reference points. Add a starting point at random (preferably inside the triangle). Then add the next point halfway between the starting point and one of the reference points. This reference point is chosen at random.
After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.
See also
The Game of Chaos
| #Wren | Wren | import "dome" for Window
import "graphics" for Canvas, Color
import "math" for Point
import "random" for Random
import "./dynamic" for Tuple
import "./seq" for Stack
var ColoredPoint = Tuple.create("ColoredPoint", ["x", "y", "colorIndex"])
class ChaosGame {
construct new(width, height) {
Window.resize(width, height)
Canvas.resize(width, height)
Window.title = "Chaos game"
_width = width
_height = height
_stack = Stack.new()
_points = null
_colors = [Color.red, Color.green, Color.blue]
_r = Random.new()
}
init() {
Canvas.cls(Color.white)
var margin = 60
var size = _width - 2 * margin
_points = [
Point.new((_width/2).floor, margin),
Point.new(margin, size),
Point.new(margin + size, size)
]
_stack.push(ColoredPoint.new(-1, -1, 0))
}
addPoint() {
var colorIndex = _r.int(3)
var p1 = _stack.peek()
var p2 = _points[colorIndex]
_stack.push(halfwayPoint(p1, p2, colorIndex))
}
drawPoints() {
for (cp in _stack) {
var c = _colors[cp.colorIndex]
Canvas.circlefill(cp.x, cp.y, 1, c)
}
}
halfwayPoint(a, b, idx) { ColoredPoint.new(((a.x + b.x)/2).floor, ((a.y + b.y)/2).floor, idx) }
update() {
if (_stack.count < 50000) {
for (i in 0...25) addPoint()
}
}
draw(alpha) {
drawPoints()
}
}
var Game = ChaosGame.new(640, 640) |
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.
| #J | J | 4 u: 97 98 99 9786
abc☺
3 u: 7 u: 'abc☺'
97 98 99 9786 |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square 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. | #Smalltalk | Smalltalk |
FloatMatrix>>#cholesky
| l |
l := FloatMatrix zero: numRows.
1 to: numRows do: [:i |
1 to: i do: [:k | | rowSum lkk factor aki partialSum |
i = k
ifTrue: [
rowSum := (1 to: k - 1) sum: [:j | | lkj |
lkj := l at: j @ k.
lkj squared].
lkk := (self at: k @ k) - rowSum.
lkk := lkk sqrt.
l at: k @ k put: lkk]
ifFalse: [
factor := l at: k @ k.
aki := self at: k @ i.
partialSum := (1 to: k - 1) sum: [:j | | ljk lji |
lji := l at: j @ i.
ljk := l at: j @ k.
lji * ljk].
l at: k @ i put: aki - partialSum * factor reciprocal]]].
^l
|
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
| #Prolog | Prolog | % create a list
L = [a,b,c,d],
% prepend to the list
L2 = [before_a|L],
% append to the list
append(L2, ['Hello'], L3),
% delete from list
exclude(=(b), L3, L4). |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
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
| #SPAD | SPAD |
[reverse subSet(5,3,i)$SGCF for i in 0..binomial(5,3)-1]
[[0,1,2], [0,1,3], [0,2,3], [1,2,3], [0,1,4], [0,2,4], [1,2,4], [0,3,4],
[1,3,4], [2,3,4]]
Type: List(List(Integer))
|
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include 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.
| #Verilog | Verilog |
if( expr_booleana ) command1;
else command2;
|
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include 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.
| #Visual_Basic | Visual Basic | If condition Then
statement
End If
If condition Then
statement
Else
statement
End If
If condition1 Then
statement
ElseIf condition2 Then
statement
...
ElseIf conditionN Then
statement
Else
statement
End If |
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
{\displaystyle a_{2}}
,
…
{\displaystyle \dots }
,
a
k
{\displaystyle a_{k}}
, there exists an integer
x
{\displaystyle x}
solving the following system of simultaneous congruences:
x
≡
a
1
(
mod
n
1
)
x
≡
a
2
(
mod
n
2
)
⋮
x
≡
a
k
(
mod
n
k
)
{\displaystyle {\begin{aligned}x&\equiv a_{1}{\pmod {n_{1}}}\\x&\equiv a_{2}{\pmod {n_{2}}}\\&{}\ \ \vdots \\x&\equiv a_{k}{\pmod {n_{k}}}\end{aligned}}}
Furthermore, all solutions
x
{\displaystyle x}
of this system are congruent modulo the product,
N
=
n
1
n
2
…
n
k
{\displaystyle N=n_{1}n_{2}\ldots n_{k}}
.
Task
Write a program to solve a system of linear congruences by applying the Chinese Remainder Theorem.
If the system of equations cannot be solved, your program must somehow indicate this.
(It may throw an exception or return a special false value.)
Since there are infinitely many solutions, the program should return the unique solution
s
{\displaystyle s}
where
0
≤
s
≤
n
1
n
2
…
n
k
{\displaystyle 0\leq s\leq n_{1}n_{2}\ldots n_{k}}
.
Show the functionality of this program by printing the result such that the
n
{\displaystyle n}
's are
[
3
,
5
,
7
]
{\displaystyle [3,5,7]}
and the
a
{\displaystyle a}
's are
[
2
,
3
,
2
]
{\displaystyle [2,3,2]}
.
Algorithm: The following algorithm only applies if the
n
i
{\displaystyle n_{i}}
's are pairwise co-prime.
Suppose, as above, that a solution is required for the system of congruences:
x
≡
a
i
(
mod
n
i
)
f
o
r
i
=
1
,
…
,
k
{\displaystyle x\equiv a_{i}{\pmod {n_{i}}}\quad \mathrm {for} \;i=1,\ldots ,k}
Again, to begin, the product
N
=
n
1
n
2
…
n
k
{\displaystyle N=n_{1}n_{2}\ldots n_{k}}
is defined.
Then a solution
x
{\displaystyle x}
can be found as follows:
For each
i
{\displaystyle i}
, the integers
n
i
{\displaystyle n_{i}}
and
N
/
n
i
{\displaystyle N/n_{i}}
are co-prime.
Using the Extended Euclidean algorithm, we can find integers
r
i
{\displaystyle r_{i}}
and
s
i
{\displaystyle s_{i}}
such that
r
i
n
i
+
s
i
N
/
n
i
=
1
{\displaystyle r_{i}n_{i}+s_{i}N/n_{i}=1}
.
Then, one solution to the system of simultaneous congruences is:
x
=
∑
i
=
1
k
a
i
s
i
N
/
n
i
{\displaystyle x=\sum _{i=1}^{k}a_{i}s_{i}N/n_{i}}
and the minimal solution,
x
(
mod
N
)
{\displaystyle x{\pmod {N}}}
.
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function ModularMultiplicativeInverse(a As Integer, m As Integer) As Integer
Dim b = a Mod m
For x = 1 To m - 1
If (b * x) Mod m = 1 Then
Return x
End If
Next
Return 1
End Function
Function Solve(n As Integer(), a As Integer()) As Integer
Dim prod = n.Aggregate(1, Function(i, j) i * j)
Dim sm = 0
Dim p As Integer
For i = 0 To n.Length - 1
p = prod / n(i)
sm = sm + a(i) * ModularMultiplicativeInverse(p, n(i)) * p
Next
Return sm Mod prod
End Function
Sub Main()
Dim n = {3, 5, 7}
Dim a = {2, 3, 2}
Dim result = Solve(n, a)
Dim counter = 0
Dim maxCount = n.Length - 1
While counter <= maxCount
Console.WriteLine($"{result} = {a(counter)} (mod {n(counter)})")
counter = counter + 1
End While
End Sub
End Module |
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.
| #Sather | Sather | class CLASSTEST is
readonly attr x:INT; -- give a public getter, not a setter
private attr y:INT; -- no getter, no setter
attr z:INT; -- getter and setter
-- constructor
create(x, y, z:INT):CLASSTEST is
res :CLASSTEST := new; -- or res ::= new
res.x := x;
res.y := y;
res.z := z;
return res;
end;
-- a getter for the private y summed to s
getPrivateY(s:INT):INT is
-- y is not shadowed so we can write y instead of
-- self.y
return y + s;
end;
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.
| #Scala | Scala | /** This class implicitly includes a constructor which accepts an Int and
* creates "val variable1: Int" with that value.
*/
class MyClass(val myMethod: Int) { // Acts like a getter, getter automatically generated.
var variable2 = "asdf" // Another instance variable; a public var this time
def this() = this(0) // An auxilliary constructor that instantiates with a default value
}
object HelloObject {
val s = "Hello" // Not private, so getter auto-generated
}
/** Demonstrate use of our example class.
*/
object Call_an_object_method extends App {
val s = "Hello"
val m = new MyClass()
val n = new MyClass(3)
println(HelloObject.s) // prints "Hello" by object getterHelloObject
println(m.myMethod) // prints 0
println(n.myMethod) // prints 3
} |
http://rosettacode.org/wiki/Closest-pair_problem | Closest-pair problem |
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a function to find the closest two points among a set of given points in two dimensions, i.e. to solve the Closest pair of points problem in the planar case.
The straightforward solution is a O(n2) algorithm (which we can call brute-force algorithm); the pseudo-code (using indexes) could be simply:
bruteForceClosestPair of P(1), P(2), ... P(N)
if N < 2 then
return ∞
else
minDistance ← |P(1) - P(2)|
minPoints ← { P(1), P(2) }
foreach i ∈ [1, N-1]
foreach j ∈ [i+1, N]
if |P(i) - P(j)| < minDistance then
minDistance ← |P(i) - P(j)|
minPoints ← { P(i), P(j) }
endif
endfor
endfor
return minDistance, minPoints
endif
A better algorithm is based on the recursive divide&conquer approach, as explained also at Wikipedia's Closest pair of points problem, which is O(n log n); a pseudo-code could be:
closestPair of (xP, yP)
where xP is P(1) .. P(N) sorted by x coordinate, and
yP is P(1) .. P(N) sorted by y coordinate (ascending order)
if N ≤ 3 then
return closest points of xP using brute-force algorithm
else
xL ← points of xP from 1 to ⌈N/2⌉
xR ← points of xP from ⌈N/2⌉+1 to N
xm ← xP(⌈N/2⌉)x
yL ← { p ∈ yP : px ≤ xm }
yR ← { p ∈ yP : px > xm }
(dL, pairL) ← closestPair of (xL, yL)
(dR, pairR) ← closestPair of (xR, yR)
(dmin, pairMin) ← (dR, pairR)
if dL < dR then
(dmin, pairMin) ← (dL, pairL)
endif
yS ← { p ∈ yP : |xm - px| < dmin }
nS ← number of points in yS
(closest, closestPair) ← (dmin, pairMin)
for i from 1 to nS - 1
k ← i + 1
while k ≤ nS and yS(k)y - yS(i)y < dmin
if |yS(k) - yS(i)| < closest then
(closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)})
endif
k ← k + 1
endwhile
endfor
return closest, closestPair
endif
References and further readings
Closest pair of points problem
Closest Pair (McGill)
Closest Pair (UCSB)
Closest pair (WUStL)
Closest pair (IUPUI)
| #Visual_FoxPro | Visual FoxPro |
CLOSE DATABASES ALL
CREATE CURSOR pairs(id I, xcoord B(6), ycoord B(6))
INSERT INTO pairs VALUES (1, 0.654682, 0.925557)
INSERT INTO pairs VALUES (2, 0.409382, 0.619391)
INSERT INTO pairs VALUES (3, 0.891663, 0.888594)
INSERT INTO pairs VALUES (4, 0.716629, 0.996200)
INSERT INTO pairs VALUES (5, 0.477721, 0.946355)
INSERT INTO pairs VALUES (6, 0.925092, 0.818220)
INSERT INTO pairs VALUES (7, 0.624291, 0.142924)
INSERT INTO pairs VALUES (8, 0.211332, 0.221507)
INSERT INTO pairs VALUES (9, 0.293786, 0.691701)
INSERT INTO pairs VALUES (10, 0.839186, 0.728260)
SELECT p1.id As id1, p2.id As id2, ;
(p1.xcoord-p2.xcoord)^2 + (p1.ycoord-p2.ycoord)^2 As dist2 ;
FROM pairs p1 JOIN pairs p2 ON p1.id < p2.id ORDER BY 3 INTO CURSOR tmp
GO TOP
? "Closest pair is " + TRANSFORM(id1) + " and " + TRANSFORM(id2) + "."
? "Distance is " + TRANSFORM(SQRT(dist2))
|
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
| #Run_BASIC | Run BASIC |
html "<TABLE border=1>"
html "<tr bgcolor=wheat align=center><td>No.</td><td>x1</td><td>y1</td><td>x2</td><td>y2</td><td>r</td><td>cir x1</td><td>cir y1</td><td>cir x2</td><td>cir y2</td></tr>"
for i = 1 to 5
read x1, y1, x2, y2,r
html "<tr align=right><td>";i;"</td><td>";x1;"</td><td>";y1;"</td><td>";x2;"</td><td>";y2;"</td><td>";r;"</td>"
gosub [twoCircles]
next
html "</table>"
end
'p1 p2 r
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
[twoCircles]
if x1=x2 and y1=y2 then '2.If the points are coincident
if r=0 then ' unless r==0.0
html "<td colspan=4 align=left>It will be a single point (";x1;",";y1;") of radius 0</td></tr>"
RETURN
else
html "<td colspan=4 align=left>There are any number of circles via single point (";x1;",";y1;") of radius ";r;"</td></tr>"
RETURN
end if
end if
r2 = sqr((x1-x2)^2+(y1-y2)^2)/2 'half distance between points
if r<r2 then
html "<td colspan=4 align=left>Points are too far apart (";2*r2;") - there are no circles of radius ";r
RETURN
end if
'else, calculate two centers
cx=(x1+x2)/2 'middle point
cy=(y1+y2)/2
'should move from middle point along perpendicular by dd2
dd2=sqr(r^2-r2^2) 'perpendicular distance
dx1=x2-cx 'vector to middle point
dy1=y2-cy
dx = 0-dy1/r2*dd2 'perpendicular:
dy = dx1/r2*dd2 'rotate and scale
html "<td>";cx+dy;"</td><td>";cy+dx;"</td>" 'two points, with (+)
html "<td>";cx-dy;"</td><td>";cy-dx;"</td></TR>" 'and (-)
RETURN |
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Tuesday, February 1, 2022 CE (in the common Gregorian calendar) will begin the lunisolar Year of the Tiger.
The celestial stems have no one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems each belong to one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element's governance is associated with yin, the other with yang.
Thus, 2022 is also the yang year of Water. Note that since 12 is an even number, the association between animals and yin/yang doesn't change. Consecutive Years of the Rooster will cycle through the five elements, but will always be yin, despite the apparent conceptual mismatch between the specifically-male English animal name and the female aspect denoted by yin.
Task
Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.
You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).
Requisite information
The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.
The element cycle runs in this order: Wood, Fire, Earth, Metal, Water.
The yang year precedes the yin year within each element.
The current 60-year cycle began in 1984 CE; the first cycle of the Common Era began in 4 CE.
Thus, 1984 was the year of the Wood Rat (yang), 1985 was the year of the Wood Ox (yin), and 1986 the year of the Fire Tiger (yang); 2022 - which, as already noted, is the year of the Water Tiger (yang) - is the 39th year of the current cycle.
Information for optional task
The ten celestial stems are 甲 jiă, 乙 yĭ, 丙 bĭng, 丁 dīng, 戊 wù, 己 jĭ, 庚 gēng, 辛 xīn, 壬 rén, and 癸 gŭi. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3".
The twelve terrestrial branches are 子 zĭ, 丑 chŏu, 寅 yín, 卯 măo, 辰 chén, 巳 sì, 午 wŭ, 未 wèi, 申 shēn, 酉 yŏu, 戌 xū, 亥 hài. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4".
Therefore 1984 was 甲子 (jiă-zĭ, or jia3-zi3). 2022 is 壬寅 (rén-yín or ren2-yin2).
| #Yabasic | Yabasic |
dim Animals$(12) : for a = 0 to 11 : read Animals$(a) : next a
dim Elements$(5) : for a = 0 to 4 : read Elements$(a): next a
dim YinYang$(2) : for a = 0 to 1 : read YinYang$(a) : next a
dim Years(7) : for a = 0 to 6 : read Years(a) : next a
for i = 0 to arraysize(Years(),1)-1
xYear = Years(i)
yElement$ = Elements$((Mod((xYear - 4), 10)) / 2)
yAnimal$ = Animals$( Mod((xYear - 4), 12))
yYinYang$ = YinYang$( Mod(xYear, 2) )
nn = ( Mod((xYear - 4), 60)) + 1
print xYear, " is the year of the ", yElement$, " ", yAnimal$, " (", yYinYang$, ")."
next i
print
end
data "Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig"
data "Wood","Fire","Earth","Metal","Water"
data "Yang","Yin"
data 1935, 1938, 1968, 1972, 1976, 1984, 2017
|
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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | wd = NotebookDirectory[];
FileExistsQ[wd <> "input.txt"]
DirectoryQ[wd <> "docs"]
FileExistsQ["/" <> "input.txt"]
DirectoryQ["/" <> "docs"] |
http://rosettacode.org/wiki/Chaos_game | Chaos game | The Chaos Game is a method of generating the attractor of an iterated function system (IFS).
One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.
Task
Play the Chaos Game using the corners of an equilateral triangle as the reference points. Add a starting point at random (preferably inside the triangle). Then add the next point halfway between the starting point and one of the reference points. This reference point is chosen at random.
After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.
See also
The Game of Chaos
| #X86_Assembly | X86 Assembly | 1 ;Assemble with: tasm, tlink /t
2 0000 .model tiny
3 0000 .code
4 .386
5 org 100h
6 ;assume: ax=0, bx=0, cx=00FFh, dx=cs, si=0100h
7
8 0100 B0 12 start: mov al, 12h ;set 640x480x4 graphic screen
9 0102 CD 10 int 10h
10
11 0104 69 04 4E35 cha10: imul ax, [si], 4E35h ;generate random number
12 0108 40 inc ax
13 0109 89 04 mov [si], ax ;save seed
14 010B 8A C4 mov al, ah ;use high byte
15 010D D4 03 aam 3 ;al:= rem(al/3)
16 010F 8A D8 mov bl, al
17 0111 02 DB add bl, bl ;double to index words
18
19 0113 03 8F 0130r add cx, [bx+Tx] ;X:= (X+Tx(R)) /2
20 0117 D1 E9 shr cx, 1
21
22 0119 03 97 0136r add dx, [bx+Ty] ;Y:= (Y+Ty(R)) /2
23 011D D1 EA shr dx, 1
24
25 011F B8 0C02 mov ax, 0C02h ;write green (2) graphics pixel
26 0122 CD 10 int 10h ;(bh=0)
27
28 0124 B4 01 mov ah, 01h ;loop until keystroke
29 0126 CD 16 int 16h
30 0128 74 DA jz cha10
31
32 012A B8 0003 mov ax, 0003h ;restore normal text-mode screen
33 012D CD 10 int 10h
34 012F C3 ret ;return to DOS
35
36 0130 0140 002B 0255 Tx dw 320, 320-277, 320+277 ;equilateral triangle
37 0136 0000 01DF 01DF Ty dw 0, 479, 479
38 end start |
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.
| #Java | Java | public class Foo {
public static void main(String[] args) {
System.out.println((int)'a'); // prints "97"
System.out.println((char)97); // prints "a"
}
} |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square 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. | #Stata | Stata | mata
: a=25,15,-5\15,18,0\-5,0,11
: a
[symmetric]
1 2 3
+----------------+
1 | 25 |
2 | 15 18 |
3 | -5 0 11 |
+----------------+
: cholesky(a)
1 2 3
+----------------+
1 | 5 0 0 |
2 | 3 3 0 |
3 | -1 1 3 |
+----------------+
: a=18,22,54,42\22,70,86,62\54,86,174,134\42,62,134,106
: a
[symmetric]
1 2 3 4
+-------------------------+
1 | 18 |
2 | 22 70 |
3 | 54 86 174 |
4 | 42 62 134 106 |
+-------------------------+
: cholesky(a)
1 2 3 4
+---------------------------------------------------------+
1 | 4.242640687 0 0 0 |
2 | 5.185449729 6.565905201 0 0 |
3 | 12.72792206 3.046038495 1.649742248 0 |
4 | 9.899494937 1.624553864 1.849711005 1.392621248 |
+---------------------------------------------------------+ |
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
| #PureBasic | PureBasic | Dim Text.s(9)
Text(3)="Hello"
Text(7)="World!" |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
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
| #Standard_ML | Standard ML | fun comb (0, _ ) = [[]]
| comb (_, [] ) = []
| comb (m, x::xs) = map (fn y => x :: y) (comb (m-1, xs)) @
comb (m, xs)
;
comb (3, [0,1,2,3,4]); |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include 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.
| #Visual_Basic_.NET | Visual Basic .NET | Dim result As String, a As String = "pants", b As String = "glasses"
If a = b Then
result = "passed"
Else
result = "failed"
End If |
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
{\displaystyle a_{2}}
,
…
{\displaystyle \dots }
,
a
k
{\displaystyle a_{k}}
, there exists an integer
x
{\displaystyle x}
solving the following system of simultaneous congruences:
x
≡
a
1
(
mod
n
1
)
x
≡
a
2
(
mod
n
2
)
⋮
x
≡
a
k
(
mod
n
k
)
{\displaystyle {\begin{aligned}x&\equiv a_{1}{\pmod {n_{1}}}\\x&\equiv a_{2}{\pmod {n_{2}}}\\&{}\ \ \vdots \\x&\equiv a_{k}{\pmod {n_{k}}}\end{aligned}}}
Furthermore, all solutions
x
{\displaystyle x}
of this system are congruent modulo the product,
N
=
n
1
n
2
…
n
k
{\displaystyle N=n_{1}n_{2}\ldots n_{k}}
.
Task
Write a program to solve a system of linear congruences by applying the Chinese Remainder Theorem.
If the system of equations cannot be solved, your program must somehow indicate this.
(It may throw an exception or return a special false value.)
Since there are infinitely many solutions, the program should return the unique solution
s
{\displaystyle s}
where
0
≤
s
≤
n
1
n
2
…
n
k
{\displaystyle 0\leq s\leq n_{1}n_{2}\ldots n_{k}}
.
Show the functionality of this program by printing the result such that the
n
{\displaystyle n}
's are
[
3
,
5
,
7
]
{\displaystyle [3,5,7]}
and the
a
{\displaystyle a}
's are
[
2
,
3
,
2
]
{\displaystyle [2,3,2]}
.
Algorithm: The following algorithm only applies if the
n
i
{\displaystyle n_{i}}
's are pairwise co-prime.
Suppose, as above, that a solution is required for the system of congruences:
x
≡
a
i
(
mod
n
i
)
f
o
r
i
=
1
,
…
,
k
{\displaystyle x\equiv a_{i}{\pmod {n_{i}}}\quad \mathrm {for} \;i=1,\ldots ,k}
Again, to begin, the product
N
=
n
1
n
2
…
n
k
{\displaystyle N=n_{1}n_{2}\ldots n_{k}}
is defined.
Then a solution
x
{\displaystyle x}
can be found as follows:
For each
i
{\displaystyle i}
, the integers
n
i
{\displaystyle n_{i}}
and
N
/
n
i
{\displaystyle N/n_{i}}
are co-prime.
Using the Extended Euclidean algorithm, we can find integers
r
i
{\displaystyle r_{i}}
and
s
i
{\displaystyle s_{i}}
such that
r
i
n
i
+
s
i
N
/
n
i
=
1
{\displaystyle r_{i}n_{i}+s_{i}N/n_{i}=1}
.
Then, one solution to the system of simultaneous congruences is:
x
=
∑
i
=
1
k
a
i
s
i
N
/
n
i
{\displaystyle x=\sum _{i=1}^{k}a_{i}s_{i}N/n_{i}}
and the minimal solution,
x
(
mod
N
)
{\displaystyle x{\pmod {N}}}
.
| #Wren | Wren | /* returns x where (a * x) % b == 1 */
var mulInv = Fn.new { |a, b|
if (b == 1) return 1
var b0 = b
var x0 = 0
var x1 = 1
while (a > 1) {
var q = (a/b).floor
var t = b
b = a % b
a = t
t = x0
x0 = x1 - q*x0
x1 = t
}
if (x1 < 0) x1 = x1 + b0
return x1
}
var chineseRemainder = Fn.new { |n, a|
var prod = n.reduce { |acc, i| acc * i }
var sum = 0
for (i in 0...n.count) {
var p = (prod/n[i]).floor
sum = sum + a[i]*mulInv.call(p, n[i])*p
}
return sum % prod
}
var n = [3, 5, 7]
var a = [2, 3, 2]
System.print(chineseRemainder.call(n, a)) |
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.
| #Scheme | Scheme | (define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds"))
(define (deposit amount)
(set! balance (+ balance amount))
balance)
(define (dispatch m)
(cond ((eq? m 'withdraw) withdraw)
((eq? m 'deposit) deposit)
(else (error "Unknown request -- MAKE-ACCOUNT"
m))))
dispatch) |
http://rosettacode.org/wiki/Closest-pair_problem | Closest-pair problem |
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a function to find the closest two points among a set of given points in two dimensions, i.e. to solve the Closest pair of points problem in the planar case.
The straightforward solution is a O(n2) algorithm (which we can call brute-force algorithm); the pseudo-code (using indexes) could be simply:
bruteForceClosestPair of P(1), P(2), ... P(N)
if N < 2 then
return ∞
else
minDistance ← |P(1) - P(2)|
minPoints ← { P(1), P(2) }
foreach i ∈ [1, N-1]
foreach j ∈ [i+1, N]
if |P(i) - P(j)| < minDistance then
minDistance ← |P(i) - P(j)|
minPoints ← { P(i), P(j) }
endif
endfor
endfor
return minDistance, minPoints
endif
A better algorithm is based on the recursive divide&conquer approach, as explained also at Wikipedia's Closest pair of points problem, which is O(n log n); a pseudo-code could be:
closestPair of (xP, yP)
where xP is P(1) .. P(N) sorted by x coordinate, and
yP is P(1) .. P(N) sorted by y coordinate (ascending order)
if N ≤ 3 then
return closest points of xP using brute-force algorithm
else
xL ← points of xP from 1 to ⌈N/2⌉
xR ← points of xP from ⌈N/2⌉+1 to N
xm ← xP(⌈N/2⌉)x
yL ← { p ∈ yP : px ≤ xm }
yR ← { p ∈ yP : px > xm }
(dL, pairL) ← closestPair of (xL, yL)
(dR, pairR) ← closestPair of (xR, yR)
(dmin, pairMin) ← (dR, pairR)
if dL < dR then
(dmin, pairMin) ← (dL, pairL)
endif
yS ← { p ∈ yP : |xm - px| < dmin }
nS ← number of points in yS
(closest, closestPair) ← (dmin, pairMin)
for i from 1 to nS - 1
k ← i + 1
while k ≤ nS and yS(k)y - yS(i)y < dmin
if |yS(k) - yS(i)| < closest then
(closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)})
endif
k ← k + 1
endwhile
endfor
return closest, closestPair
endif
References and further readings
Closest pair of points problem
Closest Pair (McGill)
Closest Pair (UCSB)
Closest pair (WUStL)
Closest pair (IUPUI)
| #Wren | Wren | import "/math" for Math
import "/sort" for Sort
var distance = Fn.new { |p1, p2| Math.hypot(p1[0] - p2[0], p1[1] - p2[1]) }
var bruteForceClosestPair = Fn.new { |p|
var n = p.count
if (n < 2) Fiber.abort("There must be at least two points.")
var minPoints = [p[0], p[1]]
var minDistance = distance.call(p[0], p[1])
for (i in 0...n-1) {
for (j in i+1...n) {
var dist = distance.call(p[i], p[j])
if (dist < minDistance) {
minDistance = dist
minPoints = [p[i], p[j]]
}
}
}
return [minDistance, minPoints]
}
var optimizedClosestPair // recursive so pre-declare
optimizedClosestPair = Fn.new { |xP, yP|
var n = xP.count
if (n <= 3) return bruteForceClosestPair.call(xP)
var hn = (n/2).floor
var xL = xP.take(hn).toList
var xR = xP.skip(hn).toList
var xm = xP[hn-1][0]
var yL = yP.where { |p| p[0] <= xm }.toList
var yR = yP.where { |p| p[0] > xm }.toList
var ll = optimizedClosestPair.call(xL, yL)
var dL = ll[0]
var pairL = ll[1]
var rr = optimizedClosestPair.call(xR, yR)
var dR = rr[0]
var pairR = rr[1]
var dmin = dR
var pairMin = pairR
if (dL < dR) {
dmin = dL
pairMin = pairL
}
var yS = yP.where { |p| (xm - p[0]).abs < dmin }.toList
var nS = yS.count
var closest = dmin
var closestPair = pairMin
for (i in 0...nS-1) {
var k = i + 1
while (k < nS && (yS[k][1] - yS[i][1] < dmin)) {
var dist = distance.call(yS[k], yS[i])
if (dist < closest) {
closest = dist
closestPair = [yS[k], yS[i]]
}
k = k + 1
}
}
return [closest, closestPair]
}
var points = [
[ [5, 9], [9, 3], [2, 0], [8, 4], [7, 4], [9, 10], [1, 9], [8, 2], [0, 10], [9, 6] ],
[
[0.654682, 0.925557], [0.409382, 0.619391], [0.891663, 0.888594],
[0.716629, 0.996200], [0.477721, 0.946355], [0.925092, 0.818220],
[0.624291, 0.142924], [0.211332, 0.221507], [0.293786, 0.691701],
[0.839186, 0.728260]
]
]
for (p in points) {
var dp = bruteForceClosestPair.call(p)
var dist = dp[0]
var pair = dp[1]
System.print("Closest pair (brute force) is %(pair[0]) and %(pair[1]), distance %(dist)")
var xP = Sort.merge(p) { |x, y| (x[0] - y[0]).sign }
var yP = Sort.merge(p) { |x, y| (x[1] - y[1]).sign }
dp = optimizedClosestPair.call(xP, yP)
dist = dp[0]
pair = dp[1]
System.print("Closest pair (optimized) is %(pair[0]) and %(pair[1]), distance %(dist)\n")
} |
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
| #Rust | Rust | use std::fmt;
#[derive(Clone,Copy)]
struct Point {
x: f64,
y: f64
}
fn distance (p1: Point, p2: Point) -> f64 {
((p1.x - p2.x).powi(2) + (p1.y - p2.y).powi(2)).sqrt()
}
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({:.4}, {:.4})", self.x, self.y)
}
}
fn describe_circle(p1: Point, p2: Point, r: f64) {
let sep = distance(p1, p2);
if sep == 0. {
if r == 0. {
println!("No circles can be drawn through {}", p1);
} else {
println!("Infinitely many circles can be drawn through {}", p1);
}
} else if sep == 2.0 * r {
println!("Given points are opposite ends of a diameter of the circle with center ({:.4},{:.4}) and r {:.4}",
(p1.x+p2.x) / 2.0, (p1.y+p2.y) / 2.0, r);
} else if sep > 2.0 * r {
println!("Given points are farther away from each other than a diameter of a circle with r {:.4}", r);
} else {
let mirror_dist = (r.powi(2) - (sep / 2.0).powi(2)).sqrt();
println!("Two circles are possible.");
println!("Circle C1 with center ({:.4}, {:.4}), r {:.4} and Circle C2 with center ({:.4}, {:.4}), r {:.4}",
((p1.x + p2.x) / 2.0) + mirror_dist * (p1.y-p2.y)/sep, (p1.y+p2.y) / 2.0 + mirror_dist*(p2.x-p1.x)/sep,
r,
(p1.x+p2.x) / 2.0 - mirror_dist*(p1.y-p2.y)/sep, (p1.y+p2.y) / 2.0 - mirror_dist*(p2.x-p1.x)/sep, r);
}
}
fn main() {
let points: Vec<(Point, Point)> = vec![
(Point { x: 0.1234, y: 0.9876 }, Point { x: 0.8765, y: 0.2345 }),
(Point { x: 0.0000, y: 2.0000 }, Point { x: 0.0000, y: 0.0000 }),
(Point { x: 0.1234, y: 0.9876 }, Point { x: 0.1234, y: 0.9876 }),
(Point { x: 0.1234, y: 0.9876 }, Point { x: 0.8765, y: 0.2345 }),
(Point { x: 0.1234, y: 0.9876 }, Point { x: 0.1234, y: 0.9876 })
];
let radii: Vec<f64> = vec![2.0, 1.0, 2.0, 0.5, 0.0];
for (p, r) in points.into_iter().zip(radii.into_iter()) {
println!("\nPoints: ({}, {}), Radius: {:.4}", p.0, p.1, r);
describe_circle(p.0, p.1, r);
}
} |
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Tuesday, February 1, 2022 CE (in the common Gregorian calendar) will begin the lunisolar Year of the Tiger.
The celestial stems have no one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems each belong to one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element's governance is associated with yin, the other with yang.
Thus, 2022 is also the yang year of Water. Note that since 12 is an even number, the association between animals and yin/yang doesn't change. Consecutive Years of the Rooster will cycle through the five elements, but will always be yin, despite the apparent conceptual mismatch between the specifically-male English animal name and the female aspect denoted by yin.
Task
Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.
You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).
Requisite information
The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.
The element cycle runs in this order: Wood, Fire, Earth, Metal, Water.
The yang year precedes the yin year within each element.
The current 60-year cycle began in 1984 CE; the first cycle of the Common Era began in 4 CE.
Thus, 1984 was the year of the Wood Rat (yang), 1985 was the year of the Wood Ox (yin), and 1986 the year of the Fire Tiger (yang); 2022 - which, as already noted, is the year of the Water Tiger (yang) - is the 39th year of the current cycle.
Information for optional task
The ten celestial stems are 甲 jiă, 乙 yĭ, 丙 bĭng, 丁 dīng, 戊 wù, 己 jĭ, 庚 gēng, 辛 xīn, 壬 rén, and 癸 gŭi. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3".
The twelve terrestrial branches are 子 zĭ, 丑 chŏu, 寅 yín, 卯 măo, 辰 chén, 巳 sì, 午 wŭ, 未 wèi, 申 shēn, 酉 yŏu, 戌 xū, 亥 hài. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4".
Therefore 1984 was 甲子 (jiă-zĭ, or jia3-zi3). 2022 is 壬寅 (rén-yín or ren2-yin2).
| #zkl | zkl | fcn ceToChineseZodiac(ce_year){ // --> list of strings
# encoding: utf-8
var [const] pinyin=SD( // create some static variables, SD is small fixed dictionary
"甲","jiă", "乙","yĭ", "丙","bĭng", "丁","dīng", "戊","wù", "己","jĭ",
"庚","gēng", "辛","xīn", "壬","rén", "癸","gŭi",
"子","zĭ", "丑","chŏu", "寅","yín", "卯","măo", "辰","chén", "巳","sì",
"午","wŭ", "未","wèi", "申","shén","酉","yŏu", "戌","xū", "亥","hài"
),
celestial =T("甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"),
terrestrial=T("子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"),
animals =T("Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake",
"Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"),
elements =T("Wood", "Fire", "Earth", "Metal", "Water"),
aspects =T("yang","yin"),
;
const BASE=4;
cycle_year:=ce_year - BASE;
cycle_year,aspect := ce_year - BASE, aspects[cycle_year%2];
stem_number,element := cycle_year%10, elements[stem_number/2];
stem_han,stem_pinyin := celestial[stem_number], pinyin[stem_han];
branch_number,animal := cycle_year%12, animals[branch_number];
branch_han,branch_pinyin := terrestrial[branch_number], pinyin[branch_han];
return(stem_han,branch_han,
stem_pinyin,branch_pinyin, element,animal,aspect)
} |
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
| #MATLAB_.2F_Octave | MATLAB / Octave | exist('input.txt','file')
exist('/input.txt','file')
exist('docs','dir')
exist('/docs','dir') |
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an unusual filename: `Abdu'l-Bahá.txt
| #MAXScript | MAXScript | -- Here
doesFileExist "input.txt"
(getDirectories "docs").count == 1
-- Root
doesFileExist "\input.txt"
(getDirectories "C:\docs").count == 1 |
http://rosettacode.org/wiki/Chaos_game | Chaos game | The Chaos Game is a method of generating the attractor of an iterated function system (IFS).
One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.
Task
Play the Chaos Game using the corners of an equilateral triangle as the reference points. Add a starting point at random (preferably inside the triangle). Then add the next point halfway between the starting point and one of the reference points. This reference point is chosen at random.
After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.
See also
The Game of Chaos
| #XPL0 | XPL0 | int Tx, Ty, X, Y, R;
[SetVid($12); \640x480x4 graphics
Tx:= [320, 320-277, 320+277]; \equilateral triangle
Ty:= [0, 479, 479]; \277 = 480 / (2*Sin(60))
X:= Ran(640); \random starting point
Y:= Ran(480);
repeat R:= Ran(3); \select random triangle point
X:= (X+Tx(R))/2; \new point is halfway to it
Y:= (Y+Ty(R))/2;
Point(X, Y, 2\green\); \plot new point
until KeyHit;
SetVid($03); \restore normal text mode
] |
http://rosettacode.org/wiki/Chaos_game | Chaos game | The Chaos Game is a method of generating the attractor of an iterated function system (IFS).
One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.
Task
Play the Chaos Game using the corners of an equilateral triangle as the reference points. Add a starting point at random (preferably inside the triangle). Then add the next point halfway between the starting point and one of the reference points. This reference point is chosen at random.
After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.
See also
The Game of Chaos
| #Yabasic | Yabasic | width = 640 : height = 480
open window width, height
window origin "lb"
x = ran(width)
y = ran(height)
for i = 1 to 200000
vertex = int(ran(3))
if vertex = 1 then
x = width / 2 + (width / 2 - x) / 2
y = height - (height - y) / 2
elseif vertex = 2 then
x = width - (width - x) / 2
y = y / 2
else
x = x / 2
y = y / 2
end if
color 255 * (vertex = 0), 255 * (vertex = 1), 255 * (vertex = 2)
dot x, y
next |
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.
| #JavaScript | JavaScript | console.log('a'.charCodeAt(0)); // prints "97"
console.log(String.fromCharCode(97)); // prints "a" |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square 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. | #Swift | Swift | func cholesky(matrix: [Double], n: Int) -> [Double] {
var res = [Double](repeating: 0, count: matrix.count)
for i in 0..<n {
for j in 0..<i+1 {
var s = 0.0
for k in 0..<j {
s += res[i * n + k] * res[j * n + k]
}
if i == j {
res[i * n + j] = (matrix[i * n + i] - s).squareRoot()
} else {
res[i * n + j] = (1.0 / res[j * n + j] * (matrix[i * n + j] - s))
}
}
}
return res
}
func printMatrix(_ matrix: [Double], n: Int) {
for i in 0..<n {
for j in 0..<n {
print(matrix[i * n + j], terminator: " ")
}
print()
}
}
let res1 = cholesky(
matrix: [25.0, 15.0, -5.0,
15.0, 18.0, 0.0,
-5.0, 0.0, 11.0],
n: 3
)
let res2 = cholesky(
matrix: [18.0, 22.0, 54.0, 42.0,
22.0, 70.0, 86.0, 62.0,
54.0, 86.0, 174.0, 134.0,
42.0, 62.0, 134.0, 106.0],
n: 4
)
printMatrix(res1, n: 3)
print()
printMatrix(res2, n: 4) |
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
| #Python | Python | collection = [0, '1'] # Lists are mutable (editable) and can be sorted in place
x = collection[0] # accessing an item (which happens to be a numeric 0 (zero)
collection.append(2) # adding something to the end of the list
collection.insert(0, '-1') # inserting a value into the beginning
y = collection[0] # now returns a string of "-1"
collection.extend([2,'3']) # same as [collection.append(i) for i in [2,'3']] ... but faster
collection += [2,'3'] # same as previous line
collection[2:6] # a "slice" (collection of the list elements from the third up to but not including the sixth)
len(collection) # get the length of (number of elements in) the collection
collection = (0, 1) # Tuples are immutable (not editable)
collection[:] # ... slices work on these too; and this is equivalent to collection[0:len(collection)]
collection[-4:-1] # negative slices count from the end of the string
collection[::2] # slices can also specify a stride --- this returns all even elements of the collection
collection="some string" # strings are treated as sequences of characters
x = collection[::-1] # slice with negative step returns reversed sequence (string in this case).
collection[::2] == "some string"[::2] # True, literal objects don't need to be bound to name/variable to access slices or object methods
collection.__getitem__(slice(0,len(collection),2)) # same as previous expressions.
collection = {0: "zero", 1: "one"} # Dictionaries (Hash)
collection['zero'] = 2 # Dictionary members accessed using same syntax as list/array indexes.
collection = set([0, '1']) # sets (Hash) |
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
| #Stata | Stata | program combin
tempfile cp
tempvar k
gen `k'=1
quietly save "`cp'"
rename `1' `1'1
forv i=2/`2' {
joinby `k' using "`cp'"
rename `1' `1'`i'
quietly drop if `1'`i'<=`1'`=`i'-1'
}
sort `1'*
end |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include 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.
| #Vlang | Vlang | if boolean_expression {
statements
} |
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
{\displaystyle a_{2}}
,
…
{\displaystyle \dots }
,
a
k
{\displaystyle a_{k}}
, there exists an integer
x
{\displaystyle x}
solving the following system of simultaneous congruences:
x
≡
a
1
(
mod
n
1
)
x
≡
a
2
(
mod
n
2
)
⋮
x
≡
a
k
(
mod
n
k
)
{\displaystyle {\begin{aligned}x&\equiv a_{1}{\pmod {n_{1}}}\\x&\equiv a_{2}{\pmod {n_{2}}}\\&{}\ \ \vdots \\x&\equiv a_{k}{\pmod {n_{k}}}\end{aligned}}}
Furthermore, all solutions
x
{\displaystyle x}
of this system are congruent modulo the product,
N
=
n
1
n
2
…
n
k
{\displaystyle N=n_{1}n_{2}\ldots n_{k}}
.
Task
Write a program to solve a system of linear congruences by applying the Chinese Remainder Theorem.
If the system of equations cannot be solved, your program must somehow indicate this.
(It may throw an exception or return a special false value.)
Since there are infinitely many solutions, the program should return the unique solution
s
{\displaystyle s}
where
0
≤
s
≤
n
1
n
2
…
n
k
{\displaystyle 0\leq s\leq n_{1}n_{2}\ldots n_{k}}
.
Show the functionality of this program by printing the result such that the
n
{\displaystyle n}
's are
[
3
,
5
,
7
]
{\displaystyle [3,5,7]}
and the
a
{\displaystyle a}
's are
[
2
,
3
,
2
]
{\displaystyle [2,3,2]}
.
Algorithm: The following algorithm only applies if the
n
i
{\displaystyle n_{i}}
's are pairwise co-prime.
Suppose, as above, that a solution is required for the system of congruences:
x
≡
a
i
(
mod
n
i
)
f
o
r
i
=
1
,
…
,
k
{\displaystyle x\equiv a_{i}{\pmod {n_{i}}}\quad \mathrm {for} \;i=1,\ldots ,k}
Again, to begin, the product
N
=
n
1
n
2
…
n
k
{\displaystyle N=n_{1}n_{2}\ldots n_{k}}
is defined.
Then a solution
x
{\displaystyle x}
can be found as follows:
For each
i
{\displaystyle i}
, the integers
n
i
{\displaystyle n_{i}}
and
N
/
n
i
{\displaystyle N/n_{i}}
are co-prime.
Using the Extended Euclidean algorithm, we can find integers
r
i
{\displaystyle r_{i}}
and
s
i
{\displaystyle s_{i}}
such that
r
i
n
i
+
s
i
N
/
n
i
=
1
{\displaystyle r_{i}n_{i}+s_{i}N/n_{i}=1}
.
Then, one solution to the system of simultaneous congruences is:
x
=
∑
i
=
1
k
a
i
s
i
N
/
n
i
{\displaystyle x=\sum _{i=1}^{k}a_{i}s_{i}N/n_{i}}
and the minimal solution,
x
(
mod
N
)
{\displaystyle x{\pmod {N}}}
.
| #zkl | zkl | var BN=Import("zklBigNum"), one=BN(1);
fcn crt(xs,ys){
p:=xs.reduce('*,BN(1));
X:=BN(0);
foreach x,y in (xs.zip(ys)){
q:=p/x;
z,s,_:=q.gcdExt(x);
if(z!=one) throw(Exception.ValueError("%d not coprime".fmt(x)));
X+=y*s*q;
}
return(X % p);
} |
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
{\displaystyle a_{2}}
,
…
{\displaystyle \dots }
,
a
k
{\displaystyle a_{k}}
, there exists an integer
x
{\displaystyle x}
solving the following system of simultaneous congruences:
x
≡
a
1
(
mod
n
1
)
x
≡
a
2
(
mod
n
2
)
⋮
x
≡
a
k
(
mod
n
k
)
{\displaystyle {\begin{aligned}x&\equiv a_{1}{\pmod {n_{1}}}\\x&\equiv a_{2}{\pmod {n_{2}}}\\&{}\ \ \vdots \\x&\equiv a_{k}{\pmod {n_{k}}}\end{aligned}}}
Furthermore, all solutions
x
{\displaystyle x}
of this system are congruent modulo the product,
N
=
n
1
n
2
…
n
k
{\displaystyle N=n_{1}n_{2}\ldots n_{k}}
.
Task
Write a program to solve a system of linear congruences by applying the Chinese Remainder Theorem.
If the system of equations cannot be solved, your program must somehow indicate this.
(It may throw an exception or return a special false value.)
Since there are infinitely many solutions, the program should return the unique solution
s
{\displaystyle s}
where
0
≤
s
≤
n
1
n
2
…
n
k
{\displaystyle 0\leq s\leq n_{1}n_{2}\ldots n_{k}}
.
Show the functionality of this program by printing the result such that the
n
{\displaystyle n}
's are
[
3
,
5
,
7
]
{\displaystyle [3,5,7]}
and the
a
{\displaystyle a}
's are
[
2
,
3
,
2
]
{\displaystyle [2,3,2]}
.
Algorithm: The following algorithm only applies if the
n
i
{\displaystyle n_{i}}
's are pairwise co-prime.
Suppose, as above, that a solution is required for the system of congruences:
x
≡
a
i
(
mod
n
i
)
f
o
r
i
=
1
,
…
,
k
{\displaystyle x\equiv a_{i}{\pmod {n_{i}}}\quad \mathrm {for} \;i=1,\ldots ,k}
Again, to begin, the product
N
=
n
1
n
2
…
n
k
{\displaystyle N=n_{1}n_{2}\ldots n_{k}}
is defined.
Then a solution
x
{\displaystyle x}
can be found as follows:
For each
i
{\displaystyle i}
, the integers
n
i
{\displaystyle n_{i}}
and
N
/
n
i
{\displaystyle N/n_{i}}
are co-prime.
Using the Extended Euclidean algorithm, we can find integers
r
i
{\displaystyle r_{i}}
and
s
i
{\displaystyle s_{i}}
such that
r
i
n
i
+
s
i
N
/
n
i
=
1
{\displaystyle r_{i}n_{i}+s_{i}N/n_{i}=1}
.
Then, one solution to the system of simultaneous congruences is:
x
=
∑
i
=
1
k
a
i
s
i
N
/
n
i
{\displaystyle x=\sum _{i=1}^{k}a_{i}s_{i}N/n_{i}}
and the minimal solution,
x
(
mod
N
)
{\displaystyle x{\pmod {N}}}
.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 DIM n(3): DIM a(3)
20 FOR i=1 TO 3
30 READ n(i),a(i)
40 NEXT i
50 DATA 3,2,5,3,7,2
100 LET prod=1: LET sum=0
110 FOR i=1 TO 3: LET prod=prod*n(i): NEXT i
120 FOR i=1 TO 3
130 LET p=INT (prod/n(i)): LET a=p: LET b=n(i)
140 GO SUB 1000
150 LET sum=sum+a(i)*x1*p
160 NEXT i
170 PRINT FN m(sum,prod)
180 STOP
200 DEF FN m(a,b)=a-INT (a/b)*b: REM Modulus function
1000 LET b0=b: LET x0=0: LET x1=1
1010 IF b=1 THEN RETURN
1020 IF a<=1 THEN GO TO 1100
1030 LET q=INT (a/b)
1040 LET t=b: LET b=FN m(a,b): LET a=t
1050 LET t=x0: LET x0=x1-q*x0: LET x1=t
1060 GO TO 1020
1100 IF x1<0 THEN LET x1=x1+b0
1110 RETURN |
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.
| #Sidef | Sidef | class MyClass(instance_var) {
method add(num) {
instance_var += num;
}
}
var obj = MyClass(3); # `instance_var` will be set to 3
obj.add(5); # calls the add() method
say obj.instance_var; # prints the value of `instance_var`: 8 |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, 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.
| #Simula | Simula | BEGIN
CLASS MyClass(instanceVariable);
INTEGER instanceVariable;
BEGIN
PROCEDURE doMyMethod(n);
INTEGER n;
BEGIN
Outint(instanceVariable, 5);
Outtext(" + ");
Outint(n, 5);
Outtext(" = ");
Outint(instanceVariable + n, 5);
Outimage
END;
END;
REF(MyClass) myObject;
myObject :- NEW MyClass(5);
myObject.doMyMethod(2)
END |
http://rosettacode.org/wiki/Closest-pair_problem | Closest-pair problem |
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a function to find the closest two points among a set of given points in two dimensions, i.e. to solve the Closest pair of points problem in the planar case.
The straightforward solution is a O(n2) algorithm (which we can call brute-force algorithm); the pseudo-code (using indexes) could be simply:
bruteForceClosestPair of P(1), P(2), ... P(N)
if N < 2 then
return ∞
else
minDistance ← |P(1) - P(2)|
minPoints ← { P(1), P(2) }
foreach i ∈ [1, N-1]
foreach j ∈ [i+1, N]
if |P(i) - P(j)| < minDistance then
minDistance ← |P(i) - P(j)|
minPoints ← { P(i), P(j) }
endif
endfor
endfor
return minDistance, minPoints
endif
A better algorithm is based on the recursive divide&conquer approach, as explained also at Wikipedia's Closest pair of points problem, which is O(n log n); a pseudo-code could be:
closestPair of (xP, yP)
where xP is P(1) .. P(N) sorted by x coordinate, and
yP is P(1) .. P(N) sorted by y coordinate (ascending order)
if N ≤ 3 then
return closest points of xP using brute-force algorithm
else
xL ← points of xP from 1 to ⌈N/2⌉
xR ← points of xP from ⌈N/2⌉+1 to N
xm ← xP(⌈N/2⌉)x
yL ← { p ∈ yP : px ≤ xm }
yR ← { p ∈ yP : px > xm }
(dL, pairL) ← closestPair of (xL, yL)
(dR, pairR) ← closestPair of (xR, yR)
(dmin, pairMin) ← (dR, pairR)
if dL < dR then
(dmin, pairMin) ← (dL, pairL)
endif
yS ← { p ∈ yP : |xm - px| < dmin }
nS ← number of points in yS
(closest, closestPair) ← (dmin, pairMin)
for i from 1 to nS - 1
k ← i + 1
while k ≤ nS and yS(k)y - yS(i)y < dmin
if |yS(k) - yS(i)| < closest then
(closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)})
endif
k ← k + 1
endwhile
endfor
return closest, closestPair
endif
References and further readings
Closest pair of points problem
Closest Pair (McGill)
Closest Pair (UCSB)
Closest pair (WUStL)
Closest pair (IUPUI)
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
proc ClosestPair(P, N); \Show closest pair of points in array P
real P; int N;
real Dist2, MinDist2;
int I, J, SI, SJ;
[MinDist2:= 1e300;
for I:= 0 to N-2 do
[for J:= I+1 to N-1 do
[Dist2:= sq(P(I,0)-P(J,0)) + sq(P(I,1)-P(J,1));
if Dist2 < MinDist2 then \squared distances are sufficient for compares
[MinDist2:= Dist2;
SI:= I; SJ:= J;
];
];
];
IntOut(0, SI); Text(0, " -- "); IntOut(0, SJ); CrLf(0);
RlOut(0, P(SI,0)); Text(0, ","); RlOut(0, P(SI,1));
Text(0, " -- ");
RlOut(0, P(SJ,0)); Text(0, ","); RlOut(0, P(SJ,1));
CrLf(0);
];
real Data;
[Format(1, 6);
Data:= [[0.654682, 0.925557], \0 test data from BASIC examples
[0.409382, 0.619391], \1
[0.891663, 0.888594], \2
[0.716629, 0.996200], \3
[0.477721, 0.946355], \4
[0.925092, 0.818220], \5
[0.624291, 0.142924], \6
[0.211332, 0.221507], \7
[0.293786, 0.691701], \8
[0.839186, 0.728260]]; \9
ClosestPair(Data, 10);
] |
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
| #Scala | Scala | import org.scalatest.FunSuite
import math._
case class V2(x: Double, y: Double) {
val distance = hypot(x, y)
def /(other: V2) = V2((x+other.x) / 2.0, (y+other.y) / 2.0)
def -(other: V2) = V2(x-other.x,y-other.y)
override def equals(other: Any) = other match {
case p: V2 => abs(x-p.x) < 0.0001 && abs(y-p.y) < 0.0001
case _ => false
}
override def toString = f"($x%.4f, $y%.4f)"
}
case class Circle(center: V2, radius: Double)
class PointTest extends FunSuite {
println(" p1 p2 r result")
Seq(
(V2(0.1234, 0.9876), V2(0.8765, 0.2345), 2.0, Seq(Circle(V2(1.8631, 1.9742), 2.0), Circle(V2(-0.8632, -0.7521), 2.0))),
(V2(0.0000, 2.0000), V2(0.0000, 0.0000), 1.0, Seq(Circle(V2(0.0, 1.0), 1.0))),
(V2(0.1234, 0.9876), V2(0.1234, 0.9876), 2.0, "coincident points yields infinite circles"),
(V2(0.1234, 0.9876), V2(0.8765, 0.2345), 0.5, "radius is less then the distance between points"),
(V2(0.1234, 0.9876), V2(0.1234, 0.9876), 0.0, "radius of zero yields no circles")
) foreach { v =>
print(s"${v._1} ${v._2} ${v._3}: ")
circles(v._1, v._2, v._3) match {
case Right(list) => println(list mkString ",")
assert(list === v._4)
case Left(error) => println(error)
assert(error === v._4)
}
}
def circles(p1: V2, p2: V2, radius: Double) = if (radius == 0.0) {
Left("radius of zero yields no circles")
} else if (p1 == p2) {
Left("coincident points yields infinite circles")
} else if (radius * 2 < (p1-p2).distance) {
Left("radius is less then the distance between points")
} else {
Right(circlesThruPoints(p1, p2, radius))
} ensuring { result =>
result.isLeft || result.right.get.nonEmpty
}
def circlesThruPoints(p1: V2, p2: V2, radius: Double): Seq[Circle] = {
val diff = p2 - p1
val d = pow(pow(radius, 2) - pow(diff.distance / 2, 2), 0.5)
val mid = p1 / p2
Seq(
Circle(V2(mid.x - d * diff.y / diff.distance, mid.y + d * diff.x / diff.distance), abs(radius)),
Circle(V2(mid.x + d * diff.y / diff.distance, mid.y - d * diff.x / diff.distance), abs(radius))).distinct
}
} |
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
| #Modula-3 | Modula-3 | MODULE FileTest EXPORTS Main;
IMPORT IO, Fmt, FS, File, OSError, Pathname;
PROCEDURE FileExists(file: Pathname.T): BOOLEAN =
VAR status: File.Status;
BEGIN
TRY
status := FS.Status(file);
RETURN TRUE;
EXCEPT
| OSError.E => RETURN FALSE;
END;
END FileExists;
BEGIN
IO.Put(Fmt.Bool(FileExists("input.txt")) & "\n");
IO.Put(Fmt.Bool(FileExists("/input.txt")) & "\n");
IO.Put(Fmt.Bool(FileExists("docs/")) & "\n");
IO.Put(Fmt.Bool(FileExists("/docs")) & "\n");
END FileTest. |
http://rosettacode.org/wiki/Chaos_game | Chaos game | The Chaos Game is a method of generating the attractor of an iterated function system (IFS).
One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.
Task
Play the Chaos Game using the corners of an equilateral triangle as the reference points. Add a starting point at random (preferably inside the triangle). Then add the next point halfway between the starting point and one of the reference points. This reference point is chosen at random.
After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.
See also
The Game of Chaos
| #Z80_Assembly | Z80 Assembly | VREG: equ 99h ; VDP register port
VR0: equ 0F3DFh ; Copy of VDP R0 in memory
VR1: equ 0F3E0h ; Copy of VDP R1 in memory
NEWKEY: equ 0FBE5h ; MSX BIOS puts key data here
VDP: equ 98h ; VDP data port
ROM: equ 0FCC0h ; Main ROM slot
JIFFY: equ 0FCE9h ; BIOS timer
calslt: equ 1Ch ; Interslot call routine
initxt: equ 6Ch ; Switch to default text mode
org 100h
ld bc,(JIFFY) ; Initialize RNG with time
ld d,b
ld e,c
exx ; RNG state stored in alternate registers
di ; Set up the VDP for 256x192 graphics mode
ld a,(VR0) ; Get old value of R0
and 112 ; Blank out mode bits
or 6 ; Set high 3 bits = 011(0)
out (VREG),a
ld a,128 ; Store in register 0
out (VREG),a
ld a,(VR1) ; Get old value of R1
and 99 ; Blank out mode bits
out (VREG),a
ld a,129 ; Low mode bits are 0 so we can just send it
out (VREG),a
ld a,31 ; Bitmap starts at beginning of VRAM
out (VREG),a
ld a,130
out (VREG),a
xor a ; Zero out the VRAM - set address to 0
out (VREG),a
ld a,142
out (VREG),a
xor a
out (VREG),a
ld a,64 ; Tell VDP to allow writing to VRAM
out (VREG),a
xor a ; Write zeroes to the VDP
ld c,192 ; 2 pixels per byte, meaning 128*192 bytes
zero1: ld b,128
zero2: out (VDP),a
djnz zero2
dec c
jr nz,zero1
ei
genX: call random ; Generate starting X coordinate
cp 200
jr nc,genX
ld b,a ; B = X
genY: call random ; Generate starting Y coordinate
cp 173
jr nc,genY
ld c,a ; C = Y
step: call random ; Get direction
and a,3 ; Directions {0,1,2}
cp a,3
jr z,step
ld ixh,a ; Store direction in IXH for color
dec a ; Select direction
jr z,d1
dec a
jr z,d2
xor a ; X /= 2
rr b
xor a ; Y /= 2
rr c
jr plot
d1: xor a ; There's a 16-bit SBC but not a 16-bit SUB
ld hl,100 ; (16-bit math or intermediate values won't fit)
ld d,a ; DE = X
ld e,b
sbc hl,de ; 100 - X
xor a
rr h ; (100 - X) / 2
rr l
ld e,100 ; (100 - X) / 2 + 100
add hl,de
ld b,l ; -> X
xor a
ld hl,173 ; 173
ld e,c
sbc hl,de ; (173 - Y)
rr h ; (173 - Y) / 2
rr l
ex de,hl
ld l,173
xor a
sbc hl,de ; 173 - (173-Y)/2
ld c,l ; -> Y
jr plot
d2: xor a
rr c ; Y /= 2
xor a
ld hl,200
ld d,a ; DE = X
ld e,b
sbc hl,de ; 200-X
xor a
rr h ; (200-X)/2
rr l
ex de,hl
ld l,200
sbc hl,de ; 200 - (200-X)/2
ld b,l ; -> X
plot: ld d,c ; Write address = CB/2
ld e,b
xor a
rr d
rr e
ld a,d ; First control byte =
rlca ; high 2 bytes of address
rlca
and 3
ld h,a ; Keep this value, we'll need it again
di
out (VREG),a
ld a,142 ; To port 14
out (VREG),a
ld a,e ; 2nd control byte = low 8 bits
out (VREG),a
ld a,d ; 3rd control byte = middle 6 bits
and 63 ; Bit 6 off = read
out (VREG),a
nop ; Give it some processing time
nop
in a,(VDP) ; Read the two pixels there
ld l,a ; Keep this byte
ld a,h ; Now set the VDP to write to that address
out (VREG),a
ld a,142
out (VREG),a
ld a,e
out (VREG),a
ld a,d
and 63 ; Bit 6 on = write
or 64
out (VREG),a
ld a,ixh ; Get color
add a,12
ld d,b ; Left or right pixel?
rr d
jr c,wpix
rlca ; Shift left if X is even
rlca
rlca
rlca
wpix: or l ; OR with other pixel in the byte
out (VDP),a ; Write byte
ei
wkey: ld a,(NEWKEY+8)
inc a ; Check if space key pushed
jp z,step ; If not, do another step
ld iy,ROM ; Switch back to text mode and quit
ld ix,initxt
jp calslt
random: exx ; RNG state stored in alternate registers
inc b ; X++
ld a,b ; X,
xor e ; ^ C,
xor c ; ^ A,
ld c,a ; -> A
add a,d ; + B
ld d,a ; -> B
rra ; >> 1
xor c ; ^ A,
add a,e ; + C,
ld e,a ; -> C
exx
ret |
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.
| #Joy | Joy | 'a ord.
97 chr. |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #jq | jq | "a" | explode # => [ 97 ]
[97] | implode # => "a" |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square 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. | #Tcl | Tcl | proc cholesky a {
set m [llength $a]
set n [llength [lindex $a 0]]
set l [lrepeat $m [lrepeat $n 0.0]]
for {set i 0} {$i < $m} {incr i} {
for {set k 0} {$k < $i+1} {incr k} {
set sum 0.0
for {set j 0} {$j < $k} {incr j} {
set sum [expr {$sum + [lindex $l $i $j] * [lindex $l $k $j]}]
}
lset l $i $k [expr {
$i == $k
? sqrt([lindex $a $i $i] - $sum)
: (1.0 / [lindex $l $k $k] * ([lindex $a $i $k] - $sum))
}]
}
}
return $l
} |
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
| #R | R | numeric(5)
1:10
c(1, 3, 6, 10, 7 + 8, sqrt(441)) |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
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
| #Swift | Swift | func addCombo(prevCombo: [Int], var pivotList: [Int]) -> [([Int], [Int])] {
return (0..<pivotList.count)
.map {
_ -> ([Int], [Int]) in
(prevCombo + [pivotList.removeAtIndex(0)], pivotList)
}
}
func combosOfLength(n: Int, m: Int) -> [[Int]] {
return [Int](1...m)
.reduce([([Int](), [Int](0..<n))]) {
(accum, _) in
accum.flatMap(addCombo)
}.map {
$0.0
}
}
println(combosOfLength(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.
| #Vorpal | Vorpal | if(condition){
result = 'met'
}
else{
result = 'not met'
} |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, 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.
| #Slate | Slate | prototypes define: #MyPrototype &parents: {Cloneable} &slots: #(instanceVar).
MyPrototype traits addSlot: #classVar.
x@(MyPrototype traits) new
[
x clone `>> [instanceVar: 0. ]
].
x@(MyPrototype traits) someMethod
[
x instanceVar = 1 /\ (x classVar = 3)
]. |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, 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.
| #Smalltalk | Smalltalk | Object subclass: #MyClass
instanceVariableNames: 'instanceVar'
classVariableNames: 'classVar'
poolDictionaries: ''
category: 'Testing' !
!MyClass class methodsFor: 'instance creation'!
new
^self basicNew instanceVar := 0 ! !
!MyClass methodsFor: 'testing'!
someMethod
^self instanceVar = 1; classVar = 3 ! !
MyClass new someMethod! |
http://rosettacode.org/wiki/Closest-pair_problem | Closest-pair problem |
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a function to find the closest two points among a set of given points in two dimensions, i.e. to solve the Closest pair of points problem in the planar case.
The straightforward solution is a O(n2) algorithm (which we can call brute-force algorithm); the pseudo-code (using indexes) could be simply:
bruteForceClosestPair of P(1), P(2), ... P(N)
if N < 2 then
return ∞
else
minDistance ← |P(1) - P(2)|
minPoints ← { P(1), P(2) }
foreach i ∈ [1, N-1]
foreach j ∈ [i+1, N]
if |P(i) - P(j)| < minDistance then
minDistance ← |P(i) - P(j)|
minPoints ← { P(i), P(j) }
endif
endfor
endfor
return minDistance, minPoints
endif
A better algorithm is based on the recursive divide&conquer approach, as explained also at Wikipedia's Closest pair of points problem, which is O(n log n); a pseudo-code could be:
closestPair of (xP, yP)
where xP is P(1) .. P(N) sorted by x coordinate, and
yP is P(1) .. P(N) sorted by y coordinate (ascending order)
if N ≤ 3 then
return closest points of xP using brute-force algorithm
else
xL ← points of xP from 1 to ⌈N/2⌉
xR ← points of xP from ⌈N/2⌉+1 to N
xm ← xP(⌈N/2⌉)x
yL ← { p ∈ yP : px ≤ xm }
yR ← { p ∈ yP : px > xm }
(dL, pairL) ← closestPair of (xL, yL)
(dR, pairR) ← closestPair of (xR, yR)
(dmin, pairMin) ← (dR, pairR)
if dL < dR then
(dmin, pairMin) ← (dL, pairL)
endif
yS ← { p ∈ yP : |xm - px| < dmin }
nS ← number of points in yS
(closest, closestPair) ← (dmin, pairMin)
for i from 1 to nS - 1
k ← i + 1
while k ≤ nS and yS(k)y - yS(i)y < dmin
if |yS(k) - yS(i)| < closest then
(closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)})
endif
k ← k + 1
endwhile
endfor
return closest, closestPair
endif
References and further readings
Closest pair of points problem
Closest Pair (McGill)
Closest Pair (UCSB)
Closest pair (WUStL)
Closest pair (IUPUI)
| #Yabasic | Yabasic |
minDist = 1^30
dim x(9), y(9)
x(0) = 0.654682 : y(0) = 0.925557
x(1) = 0.409382 : y(1) = 0.619391
x(2) = 0.891663 : y(2) = 0.888594
x(3) = 0.716629 : y(3) = 0.996200
x(4) = 0.477721 : y(4) = 0.946355
x(5) = 0.925092 : y(5) = 0.818220
x(6) = 0.624291 : y(6) = 0.142924
x(7) = 0.211332 : y(7) = 0.221507
x(8) = 0.293786 : y(8) = 0.691701
x(9) = 0.839186 : y(9) = 0.728260
for i = 0 to 8
for j = i+1 to 9
dist = (x(i) - x(j))^2 + (y(i) - y(j))^2
if dist < minDist then
minDist = dist
mini = i
minj = j
end if
next j
next i
print "El par mas cercano es ", mini, " y ", minj, " a una distancia de ", sqr(minDist)
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
| #Scheme | Scheme |
(import (scheme base)
(scheme inexact)
(scheme write))
;; c1 and c2 are pairs (x y), r a positive radius
(define (find-circles c1 c2 r)
(define x-coord car) ; for easier to read coordinate extraction from list
(define y-coord cadr)
(define (approx= a b) (< (- a b) 0.000001)) ; equal within tolerance
(define (avg a b) (/ (+ a b) 2))
(define (distance pt1 pt2)
(sqrt (+ (square (- (x-coord pt1) (x-coord pt2)))
(square (- (y-coord pt1) (y-coord pt2))))))
(define (equal-points? pt1 pt2)
(and (approx= (x-coord pt1) (x-coord pt2))
(approx= (y-coord pt1) (y-coord pt2))))
(define (delete-duplicate pts) ; assume no more than two points in list
(if (and (= 2 (length pts))
(equal-points? (car pts) (cadr pts)))
(list (car pts)) ; keep the first only
pts))
;
(let ((d (distance c1 c2)))
(cond ((equal-points? c1 c2) ; coincident points
(if (> r 0)
'infinite ; r > 0
(list c1))) ; else r = 0
((< (* 2 r) d)
'()) ; circle cannot reach both points, as too far apart
((approx= r 0.0) ; r = 0, no circles, as points differ
'())
(else ; find up to two circles meeting c1 and c2
(let* ((mid-pt (list (avg (x-coord c1) (x-coord c2))
(avg (y-coord c1) (y-coord c2))))
(offset (sqrt (- (square r)
(square (* 0.5 d)))))
(delta-cx (/ (- (x-coord c1) (x-coord c2)) d))
(delta-cy (/ (- (y-coord c1) (y-coord c2)) d)))
(delete-duplicate
(list (list (- (x-coord mid-pt) (* offset delta-cx))
(+ (y-coord mid-pt) (* offset delta-cy)))
(list (+ (x-coord mid-pt) (* offset delta-cx))
(- (y-coord mid-pt) (* offset delta-cy))))))))))
;; work through the input examples, outputting results
(for-each
(lambda (c1 c2 r)
(let ((result (find-circles c1 c2 r)))
(display "p1: ") (display c1)
(display " p2: ") (display c2)
(display " r: ") (display (number->string r))
(display " => ")
(cond ((eq? result 'infinite)
(display "Infinite number of circles"))
((null? result)
(display "No circles"))
(else
(display result)))
(newline)))
'((0.1234 0.9876) (0.0000 2.0000) (0.1234 0.9876) (0.1234 0.9876) (0.1234 0.9876))
'((0.8765 0.2345) (0.0000 0.0000) (0.1234 0.9876) (0.8765 0.2345) (0.1234 0.9876))
'(2.0 1.0 2.0 0.5 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
| #Nanoquery | Nanoquery | import Nanoquery.IO
def exists(fname)
f = new(File, fname)
return f.exists()
end |
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an unusual filename: `Abdu'l-Bahá.txt
| #Neko | Neko | /**
Check that file/dir exists, in Neko
*/
var sys_exists = $loader.loadprim("std@sys_exists", 1)
var sys_file_type = $loader.loadprim("std@sys_file_type", 1)
var sys_command = $loader.loadprim("std@sys_command", 1)
var name = "input.txt"
$print(name, " exists as file: ", sys_exists(name), "\n")
$print(name = "docs", " exists as dir: ", sys_exists(name) && sys_file_type(name) == "dir", "\n")
$print(name = "neko", " exists as dir: ", sys_exists(name) && sys_file_type(name) == "dir", "\n")
$print(name = "/input.txt", " exists as file: ", sys_exists(name) && sys_file_type(name) == "file", "\n")
$print(name = "/docs", " exists as dir: ", sys_exists(name) && sys_file_type(name) == "dir", "\n")
$print(name = "/tmp", " exists as dir: ", sys_exists(name) && sys_file_type(name) == "dir", "\n")
/* bonus round */
name = "empty.txt"
var stat_size = $loader.loadprim("std@sys_stat", 1)(name).size
$print(name, " exists as empty file: ", sys_exists(name) && stat_size == 0, "\n")
name = "`Abdu'l-Bahá.txt"
$print(name, " exists as file: ", sys_exists(name) && sys_file_type(name) == "file", "\n") |
http://rosettacode.org/wiki/Chaos_game | Chaos game | The Chaos Game is a method of generating the attractor of an iterated function system (IFS).
One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.
Task
Play the Chaos Game using the corners of an equilateral triangle as the reference points. Add a starting point at random (preferably inside the triangle). Then add the next point halfway between the starting point and one of the reference points. This reference point is chosen at random.
After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.
See also
The Game of Chaos
| #zkl | zkl | w,h:=640,640;
bitmap:=PPM(w,h,0xFF|FF|FF); // White background
colors:=T(0xFF|00|00,0x00|FF|00,0x00|00|FF); // red,green,blue
margin,size:=60, w - 2*margin;
points:=T(T(w/2, margin), T(margin,size), T(margin + size,size) );
N,done:=Atomic.Int(0),Atomic.Bool(False);
Thread.HeartBeat('wrap(hb){ // a thread
var a=List(-1,-1);
if(N.inc()<50){
do(500){
colorIndex:=(0).random(3); // (0..2)
b,p:=points[colorIndex], halfwayPoint(a,b);
x,y:=p;
bitmap[x,y]=colors[colorIndex];
a=p;
}
bitmap.writeJPGFile("chaosGame.jpg",True);
}
else{ hb.cancel(); done.set(); } // stop thread and signal done
},2).go(); // run every 2 seconds, starting now
fcn halfwayPoint([(ax,ay)], [(bx,by)]){ T((ax + bx)/2, (ay + by)/2) }
done.wait(); // don't exit until thread is done
println("Done"); |
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.
| #Julia | Julia | println(Int('a'))
println(Char(97)) |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square 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. | #VBA | VBA | Function Cholesky(Mat As Range) As Variant
Dim A() As Double, L() As Double, sum As Double, sum2 As Double
Dim m As Byte, i As Byte, j As Byte, k As Byte
'Ensure matrix is square
If Mat.Rows.Count <> Mat.Columns.Count Then
MsgBox ("Correlation matrix is not square")
Exit Function
End If
m = Mat.Rows.Count
'Initialize and populate matrix A of values and matrix L which will be the lower Cholesky
ReDim A(0 To m - 1, 0 To m - 1)
ReDim L(0 To m - 1, 0 To m - 1)
For i = 0 To m - 1
For j = 0 To m - 1
A(i, j) = Mat(i + 1, j + 1).Value2
L(i, j) = 0
Next j
Next i
'Handle the simple cases explicitly to save time
Select Case m
Case Is = 1
L(0, 0) = Sqr(A(0, 0))
Case Is = 2
L(0, 0) = Sqr(A(0, 0))
L(1, 0) = A(1, 0) / L(0, 0)
L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0))
Case Else
L(0, 0) = Sqr(A(0, 0))
L(1, 0) = A(1, 0) / L(0, 0)
L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0))
For i = 2 To m - 1
sum2 = 0
For k = 0 To i - 1
sum = 0
For j = 0 To k
sum = sum + L(i, j) * L(k, j)
Next j
L(i, k) = (A(i, k) - sum) / L(k, k)
sum2 = sum2 + L(i, k) * L(i, k)
Next k
L(i, i) = Sqr(A(i, i) - sum2)
Next i
End Select
Cholesky = L
End Function
|
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
| #Racket | Racket |
#lang racket
;; create a list
(list 1 2 3 4)
;; create a list of size N
(make-list 100 0)
;; add an element to the front of a list (non-destructively)
(cons 1 (list 2 3 4))
|
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
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
| #Tcl | Tcl | proc comb {m n} {
set set [list]
for {set i 0} {$i < $n} {incr i} {lappend set $i}
return [combinations $set $m]
}
proc combinations {list size} {
if {$size == 0} {
return [list [list]]
}
set retval {}
for {set i 0} {($i + $size) <= [llength $list]} {incr i} {
set firstElement [lindex $list $i]
set remainingElements [lrange $list [expr {$i + 1}] end]
foreach subset [combinations $remainingElements [expr {$size - 1}]] {
lappend retval [linsert $subset 0 $firstElement]
}
}
return $retval
}
comb 3 5 ;# ==> {0 1 2} {0 1 3} {0 1 4} {0 2 3} {0 2 4} {0 3 4} {1 2 3} {1 2 4} {1 3 4} {2 3 4} |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include 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.
| #Woma | Woma | <%>condition |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, 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.
| #SuperCollider | SuperCollider |
SpecialObject {
classvar a = 42, <b = 0, <>c; // Class variables. 42 and 0 are default values.
var <>x, <>y; // Instance variables.
// Note: variables are private by default. In the above, "<" creates a getter, ">" creates a setter
*new { |value|
^super.new.init(value) // constructor is a class method. typically calls some instance method to set up, here "init"
}
init { |value|
x = value;
y = sqrt(squared(a) + squared(b))
}
// a class method
*randomizeAll {
a = 42.rand;
b = 42.rand;
c = 42.rannd;
}
// an instance method
coordinates {
^Point(x, y) // The "^" means to return the result. If not specified, then the object itself will be returned ("^this")
}
}
|
http://rosettacode.org/wiki/Closest-pair_problem | Closest-pair problem |
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a function to find the closest two points among a set of given points in two dimensions, i.e. to solve the Closest pair of points problem in the planar case.
The straightforward solution is a O(n2) algorithm (which we can call brute-force algorithm); the pseudo-code (using indexes) could be simply:
bruteForceClosestPair of P(1), P(2), ... P(N)
if N < 2 then
return ∞
else
minDistance ← |P(1) - P(2)|
minPoints ← { P(1), P(2) }
foreach i ∈ [1, N-1]
foreach j ∈ [i+1, N]
if |P(i) - P(j)| < minDistance then
minDistance ← |P(i) - P(j)|
minPoints ← { P(i), P(j) }
endif
endfor
endfor
return minDistance, minPoints
endif
A better algorithm is based on the recursive divide&conquer approach, as explained also at Wikipedia's Closest pair of points problem, which is O(n log n); a pseudo-code could be:
closestPair of (xP, yP)
where xP is P(1) .. P(N) sorted by x coordinate, and
yP is P(1) .. P(N) sorted by y coordinate (ascending order)
if N ≤ 3 then
return closest points of xP using brute-force algorithm
else
xL ← points of xP from 1 to ⌈N/2⌉
xR ← points of xP from ⌈N/2⌉+1 to N
xm ← xP(⌈N/2⌉)x
yL ← { p ∈ yP : px ≤ xm }
yR ← { p ∈ yP : px > xm }
(dL, pairL) ← closestPair of (xL, yL)
(dR, pairR) ← closestPair of (xR, yR)
(dmin, pairMin) ← (dR, pairR)
if dL < dR then
(dmin, pairMin) ← (dL, pairL)
endif
yS ← { p ∈ yP : |xm - px| < dmin }
nS ← number of points in yS
(closest, closestPair) ← (dmin, pairMin)
for i from 1 to nS - 1
k ← i + 1
while k ≤ nS and yS(k)y - yS(i)y < dmin
if |yS(k) - yS(i)| < closest then
(closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)})
endif
k ← k + 1
endwhile
endfor
return closest, closestPair
endif
References and further readings
Closest pair of points problem
Closest Pair (McGill)
Closest Pair (UCSB)
Closest pair (WUStL)
Closest pair (IUPUI)
| #zkl | zkl | class Point{
fcn init(_x,_y){ var[const] x=_x, y=_y; }
fcn distance(p){ (p.x-x).hypot(p.y-y) }
fcn toString { String("Point(",x,",",y,")") }
}
// find closest two points using brute ugly force:
// find all combinations of two points, measure distance, pick smallest
fcn closestPoints(points){
pairs:=Utils.Helpers.pickNFrom(2,points);
triples:=pairs.apply(fcn([(p1,p2)]){ T(p1,p2,p1.distance(p2)) });
triples.reduce(fcn([(_,_,d1)]p1,[(_,_,d2)]p2){
if(d1 < d2) p1 else p2
});
} |
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
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
include "math.s7i";
const type: point is new struct
var float: x is 0.0;
var float: y is 0.0;
end struct;
const func point: point (in float: x, in float: y) is func
result
var point: aPoint is point.value;
begin
aPoint.x := x;
aPoint.y := y;
end func;
const func float: distance (in point: p1, in point: p2) is
return sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2);
const proc: findCircles (in point: p1, in point: p2, in float: radius) is func
local
var float: separation is 0.0;
var float: mirrorDistance is 0.0;
begin
separation := distance(p1, p2);
if separation = 0.0 then
if radius = 0.0 then
write("Radius of zero. No circles can be drawn through (");
else
write("Infinitely many circles can be drawn through (");
end if;
writeln(p1.x digits 4 <& ", " <& p1.y digits 4 <& ")");
elsif separation = 2.0 * radius then
writeln("Given points are opposite ends of a diameter of the circle with center (" <&
(p1.x + p2.x) / 2.0 digits 4 <& ", " <& (p1.y + p2.y) / 2.0 digits 4 <& ") and radius " <&
radius digits 4);
elsif separation > 2.0 * radius then
writeln("Given points are farther away from each other than a diameter of a circle with radius " <&
radius digits 4);
else
mirrorDistance := sqrt(radius ** 2 - (separation / 2.0) ** 2);
writeln("Two circles are possible.");
writeln("Circle C1 with center (" <&
(p1.x + p2.x) / 2.0 + mirrorDistance*(p1.y - p2.y) / separation digits 4 <& ", " <&
(p1.y + p2.y) / 2.0 + mirrorDistance*(p2.x - p1.x) / separation digits 4 <& "), radius " <&
radius digits 4);
writeln("Circle C2 with center (" <&
(p1.x + p2.x) / 2.0 - mirrorDistance*(p1.y - p2.y) / separation digits 4 <& ", " <&
(p1.y + p2.y) / 2.0 - mirrorDistance*(p2.x - p1.x) / separation digits 4 <& "), radius " <&
radius digits 4);
end if;
end func;
const proc: main is func
local
const array array float: cases is [] (
[] (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));
var integer: index is 0;
begin
for index range 1 to 5 do
writeln("Case " <& index <& ":");
findCircles(point(cases[index][1], cases[index][2]),
point(cases[index][3], cases[index][4]), cases[index][5]);
end for;
end func; |
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
| #Nemerle | Nemerle | using System.Console;
using System.IO;
WriteLine(File.Exists("input.txt"));
WriteLine(File.Exists("/input.txt"));
WriteLine(Directory.Exists("docs"));
WriteLine(Directory.Exists("/docs")); |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #K | K | _ic "abcABC"
97 98 99 65 66 67
_ci 97 98 99 65 66 67
"abcABC" |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #Kotlin | Kotlin | fun main(args: Array<String>) {
var c = 'a'
var i = c.toInt()
println("$c <-> $i")
i += 2
c = i.toChar()
println("$i <-> $c")
} |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square 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. | #Vlang | Vlang | import math
// Symmetric and Lower use a packed representation that stores only
// the Lower triangle.
struct Symmetric {
order int
ele []f64
}
struct Lower {
mut:
order int
ele []f64
}
// Symmetric.print prints a square matrix from the packed representation,
// printing the upper triange as a transpose of the Lower.
fn (s Symmetric) print() {
mut row, mut diag := 1, 0
for i, e in s.ele {
print("${e:10.5f} ")
if i == diag {
for j, col := diag+row, row; col < s.order; j += col {
print("${s.ele[j]:10.5f} ")
col++
}
println('')
row++
diag += row
}
}
}
// Lower.print prints a square matrix from the packed representation,
// printing the upper triangle as all zeros.
fn (l Lower) print() {
mut row, mut diag := 1, 0
for i, e in l.ele {
print("${e:10.5f} ")
if i == diag {
for _ in row..l.order {
print("${0.0:10.5f} ")
}
println('')
row++
diag += row
}
}
}
// cholesky_lower returns the cholesky decomposition of a Symmetric real
// matrix. The matrix must be positive definite but this is not checked.
fn (a Symmetric) cholesky_lower() Lower {
mut l := Lower{a.order, []f64{len: a.ele.len}}
mut row, mut col := 1, 1
mut dr := 0 // index of diagonal element at end of row
mut dc := 0 // index of diagonal element at top of column
for i, e in a.ele {
if i < dr {
d := (e - l.ele[i]) / l.ele[dc]
l.ele[i] = d
mut ci, mut cx := col, dc
for j := i + 1; j <= dr; j++ {
cx += ci
ci++
l.ele[j] += d * l.ele[cx]
}
col++
dc += col
} else {
l.ele[i] = math.sqrt(e - l.ele[i])
row++
dr += row
col = 1
dc = 0
}
}
return l
}
fn main() {
demo(Symmetric{3, [
f64(25),
15, 18,
-5, 0, 11]})
demo(Symmetric{4, [
f64(18),
22, 70,
54, 86, 174,
42, 62, 134, 106]})
}
fn demo(a Symmetric) {
println("A:")
a.print()
println("L:")
a.cholesky_lower().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
| #Raku | Raku | # Array
my @array = 1,2,3;
@array.push: 4,5,6;
# Hash
my %hash = 'a' => 1, 'b' => 2;
%hash<c d> = 3,4;
%hash.push: 'e' => 5, 'f' => 6;
# SetHash
my $s = SetHash.new: <a b c>;
$s ∪= <d e f>;
# BagHash
my $b = BagHash.new: <b a k l a v a>;
$b ⊎= <a b c>; |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
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
| #TXR | TXR | (defun comb-n-m (n m)
(comb (range* 0 n) m))
(put-line `3 comb 5 = @(comb-n-m 5 3)`) |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include 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.
| #Wrapl | Wrapl | condition => success // failure
condition => success
condition // failure |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, 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.
| #Swift | Swift | class MyClass{
// stored property
var variable : Int
/**
* The constructor
*/
init() {
self.variable = 42
}
/**
* A method
*/
func someMethod() {
self.variable = 1
}
} |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, 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.
| #Tcl | Tcl | package require TclOO
oo::class create summation {
variable v
constructor {} {
set v 0
}
method add x {
incr v $x
}
method value {} {
return $v
}
destructor {
puts "Ended with value $v"
}
}
set sum [summation new]
puts "Start with [$sum value]"
for {set i 1} {$i <= 10} {incr i} {
puts "Add $i to get [$sum add $i]"
}
$sum destroy |
http://rosettacode.org/wiki/Closest-pair_problem | Closest-pair problem |
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a function to find the closest two points among a set of given points in two dimensions, i.e. to solve the Closest pair of points problem in the planar case.
The straightforward solution is a O(n2) algorithm (which we can call brute-force algorithm); the pseudo-code (using indexes) could be simply:
bruteForceClosestPair of P(1), P(2), ... P(N)
if N < 2 then
return ∞
else
minDistance ← |P(1) - P(2)|
minPoints ← { P(1), P(2) }
foreach i ∈ [1, N-1]
foreach j ∈ [i+1, N]
if |P(i) - P(j)| < minDistance then
minDistance ← |P(i) - P(j)|
minPoints ← { P(i), P(j) }
endif
endfor
endfor
return minDistance, minPoints
endif
A better algorithm is based on the recursive divide&conquer approach, as explained also at Wikipedia's Closest pair of points problem, which is O(n log n); a pseudo-code could be:
closestPair of (xP, yP)
where xP is P(1) .. P(N) sorted by x coordinate, and
yP is P(1) .. P(N) sorted by y coordinate (ascending order)
if N ≤ 3 then
return closest points of xP using brute-force algorithm
else
xL ← points of xP from 1 to ⌈N/2⌉
xR ← points of xP from ⌈N/2⌉+1 to N
xm ← xP(⌈N/2⌉)x
yL ← { p ∈ yP : px ≤ xm }
yR ← { p ∈ yP : px > xm }
(dL, pairL) ← closestPair of (xL, yL)
(dR, pairR) ← closestPair of (xR, yR)
(dmin, pairMin) ← (dR, pairR)
if dL < dR then
(dmin, pairMin) ← (dL, pairL)
endif
yS ← { p ∈ yP : |xm - px| < dmin }
nS ← number of points in yS
(closest, closestPair) ← (dmin, pairMin)
for i from 1 to nS - 1
k ← i + 1
while k ≤ nS and yS(k)y - yS(i)y < dmin
if |yS(k) - yS(i)| < closest then
(closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)})
endif
k ← k + 1
endwhile
endfor
return closest, closestPair
endif
References and further readings
Closest pair of points problem
Closest Pair (McGill)
Closest Pair (UCSB)
Closest pair (WUStL)
Closest pair (IUPUI)
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 DIM x(10): DIM y(10)
20 FOR i=1 TO 10
30 READ x(i),y(i)
40 NEXT i
50 LET min=1e30
60 FOR i=1 TO 9
70 FOR j=i+1 TO 10
80 LET p1=x(i)-x(j): LET p2=y(i)-y(j): LET dsq=p1*p1+p2*p2
90 IF dsq<min THEN LET min=dsq: LET mini=i: LET minj=j
100 NEXT j
110 NEXT i
120 PRINT "Closest pair is ";mini;" and ";minj;" at distance ";SQR min
130 STOP
140 DATA 0.654682,0.925557
150 DATA 0.409382,0.619391
160 DATA 0.891663,0.888594
170 DATA 0.716629,0.996200
180 DATA 0.477721,0.946355
190 DATA 0.925092,0.818220
200 DATA 0.624291,0.142924
210 DATA 0.211332,0.221507
220 DATA 0.293786,0.691701
230 DATA 0.839186,0.728260 |
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
| #Sidef | Sidef | func circles(a, b, r) {
if (a == b) {
if (r == 0) {
return ['Degenerate point']
}
else {
return ['Infinitely many share a point']
}
}
var h = (b-a)/2
if (r**2 < h.norm) {
return ['Too far apart']
}
var l = sqrt(r**2 - h.norm)
[1i, -1i].map {|i|
a + h + (l*i*h / h.abs) -> round(-16)
}
}
var input = [
[0.1234 + 0.9876i, 0.8765 + 0.2345i, 2.0],
[0.0000 + 2.0000i, 0.0000 + 0.0000i, 1.0],
[0.1234 + 0.9876i, 0.1234 + 0.9876i, 2.0],
[0.1234 + 0.9876i, 0.8765 + 0.2345i, 0.5],
[0.1234 + 0.9876i, 0.1234 + 0.9876i, 0.0],
]
input.each {|a|
say (a.join(', '), ': ', circles(a...).join(' and '))
} |
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
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols binary
runSample(arg)
return
-- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
method isExistingFile(fn) public static returns boolean
ff = File(fn)
fExists = ff.exists() & ff.isFile()
return fExists
-- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
method isExistingDirectory(fn) public static returns boolean
ff = File(fn)
fExists = ff.exists() & ff.isDirectory()
return fExists
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
parse arg files
if files = '' then files = 'input.txt F docs D /input.txt F /docs D'
loop while files.length > 0
parse files fn ft files
select case(ft.upper())
when 'F' then do
if isExistingFile(fn) then ex = 'exists'
else ex = 'does not exist'
say 'File '''fn'''' ex
end
when 'D' then do
if isExistingDirectory(fn) then ex = 'exists'
else ex = 'does not exist'
say 'Directory '''fn'''' ex
end
otherwise do
if isExistingFile(fn) then ex = 'exists'
else ex = 'does not exist'
say 'File '''fn'''' ex
end
end
end
return
|
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.
| #LabVIEW | LabVIEW | : CHAR "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[" comb
'\\ comb -1 remove append "]^_`abcdefghijklmnopqrstuvwxyz{|}~" comb append ;
: CODE 95 iota 33 + ; : comb "" split ;
: extract' rot 1 compress index subscript expand drop ;
: chr CHAR CODE extract' ;
: ord CODE CHAR extract' ;
'a ord . # 97
97 chr . # 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.
| #Lang5 | Lang5 | : CHAR "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[" comb
'\\ comb -1 remove append "]^_`abcdefghijklmnopqrstuvwxyz{|}~" comb append ;
: CODE 95 iota 33 + ; : comb "" split ;
: extract' rot 1 compress index subscript expand drop ;
: chr CHAR CODE extract' ;
: ord CODE CHAR extract' ;
'a ord . # 97
97 chr . # a |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.