task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include 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.
| #Trith | Trith | true ["yes" print] ["no" print] branch |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include 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.
| #True_BASIC | True BASIC |
! IF-ELSEIF-ELSE-END IF
! SELECT-CASE
! ON GOTO, ON GOSUB
IF expr_booleana THEN
sentencia(s)
END IF
IF expr_booleana1 THEN
sentencia(s)
ELSEIF expr_booleana2 THEN
sentencia(s)
ELSEIF expr_booleana3 THEN
sentencia(s)
ELSE
sentencia(s)
END IF
SELECT CASE expr_booleana
CASE 1
sentencia(s)
CASE 2
sentencia(s)
CASE ELSE
sentencia(s)
END SELECT
ON expresión GOTO label1, label2 ELSE label3
ON expresión Gosub label1, label2 ELSE label3
|
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}}}
.
| #REXX | REXX | /*REXX program demonstrates Sun Tzu's (or Sunzi's) Chinese Remainder Theorem. */
parse arg Ns As . /*get optional arguments from the C.L. */
if Ns=='' | Ns=="," then Ns= '3,5,7' /*Ns not specified? Then use default.*/
if As=='' | As=="," then As= '2,3,2' /*As " " " " " */
say 'Ns: ' Ns
say 'As: ' As; say
Ns= space( translate(Ns, , ',')); #= words(Ns) /*elide any superfluous blanks from N's*/
As= space( translate(As, , ',')); _= words(As) /* " " " " " A's*/
if #\==_ then do; say "size of number sets don't match."; exit 131; end
if #==0 then do; say "size of the N set isn't valid."; exit 132; end
if _==0 then do; say "size of the A set isn't valid."; exit 133; end
N= 1 /*the product─to─be for prod(n.j). */
do j=1 for # /*process each number for As and Ns. */
n.j= word(Ns, j); N= N * n.j /*get an N.j and calculate product. */
a.j= word(As, j) /* " " A.j from the As list. */
end /*j*/
do x=1 for N /*use a simple algebraic method. */
do i=1 for # /*process each N.i and A.i number.*/
if x//n.i\==a.i then iterate x /*is modulus correct for the number X ?*/
end /*i*/ /* [↑] limit solution to the product. */
say 'found a solution with X=' x /*display one possible solution. */
exit 0 /*stick a fork in it, we're all done. */
end /*x*/
say 'no solution found.' /*oops, announce that solution ¬ found.*/ |
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.
| #Processing | Processing | class ProgrammingLanguage
{
// instance variable:
private String name;
// constructor (let's use it to give the instance variable a value):
public ProgrammingLanguage(String name)
{
this.name = name;
// note use of "this" to distinguish the instance variable from the argument
}
// a method:
public void sayHello()
{
println("Hello from the programming language " + name);
// the method has no argument or local variable called "name", so we can omit the "this"
}
} |
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.
| #PureBasic | PureBasic | Interface OO_Interface ; Interface for any value of this type
Get.i()
Set(Value.i)
ToString.s()
Destroy()
EndInterface
Structure OO_Structure ; The *VTable structure
Get.i
Set.i
ToString.i
Destroy.i
EndStructure
Structure OO_Var
*VirtualTable.OO_Structure
Value.i
EndStructure
Procedure OO_Get(*Self.OO_Var)
ProcedureReturn *Self\Value
EndProcedure
Procedure OO_Set(*Self.OO_Var, n)
*Self\Value = n
EndProcedure
Procedure.s OO_ToString(*Self.OO_Var)
ProcedureReturn Str(*Self\Value)
EndProcedure
Procedure Create_OO()
*p.OO_Var=AllocateMemory(SizeOf(OO_Var))
If *p
*p\VirtualTable=?VTable
EndIf
ProcedureReturn *p
EndProcedure
Procedure OO_Destroy(*Self.OO_Var)
FreeMemory(*Self)
EndProcedure
DataSection
VTable:
Data.i @OO_Get()
Data.i @OO_Set()
Data.i @OO_ToString()
Data.i @OO_Destroy()
EndDataSection
;- Test the code
*Foo.OO_Interface = Create_OO()
*Foo\Set(341)
MessageRequester("Info", "Foo = " + *Foo\ToString() )
*Foo\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)
| #Scala | Scala | import scala.collection.mutable.ListBuffer
import scala.util.Random
object ClosestPair {
case class Point(x: Double, y: Double){
def distance(p: Point) = math.hypot(x-p.x, y-p.y)
override def toString = "(" + x + ", " + y + ")"
}
case class Pair(point1: Point, point2: Point) {
val distance: Double = point1 distance point2
override def toString = {
point1 + "-" + point2 + " : " + distance
}
}
def sortByX(points: List[Point]) = {
points.sortBy(point => point.x)
}
def sortByY(points: List[Point]) = {
points.sortBy(point => point.y)
}
def divideAndConquer(points: List[Point]): Pair = {
val pointsSortedByX = sortByX(points)
val pointsSortedByY = sortByY(points)
divideAndConquer(pointsSortedByX, pointsSortedByY)
}
def bruteForce(points: List[Point]): Pair = {
val numPoints = points.size
if (numPoints < 2)
return null
var pair = Pair(points(0), points(1))
if (numPoints > 2) {
for (i <- 0 until numPoints - 1) {
val point1 = points(i)
for (j <- i + 1 until numPoints) {
val point2 = points(j)
val distance = point1 distance point2
if (distance < pair.distance)
pair = Pair(point1, point2)
}
}
}
return pair
}
private def divideAndConquer(pointsSortedByX: List[Point], pointsSortedByY: List[Point]): Pair = {
val numPoints = pointsSortedByX.size
if(numPoints <= 3) {
return bruteForce(pointsSortedByX)
}
val dividingIndex = numPoints >>> 1
val leftOfCenter = pointsSortedByX.slice(0, dividingIndex)
val rightOfCenter = pointsSortedByX.slice(dividingIndex, numPoints)
var tempList = leftOfCenter.map(x => x)
//println(tempList)
tempList = sortByY(tempList)
var closestPair = divideAndConquer(leftOfCenter, tempList)
tempList = rightOfCenter.map(x => x)
tempList = sortByY(tempList)
val closestPairRight = divideAndConquer(rightOfCenter, tempList)
if (closestPairRight.distance < closestPair.distance)
closestPair = closestPairRight
tempList = List[Point]()
val shortestDistance = closestPair.distance
val centerX = rightOfCenter(0).x
for (point <- pointsSortedByY) {
if (Math.abs(centerX - point.x) < shortestDistance)
tempList = tempList :+ point
}
closestPair = shortestDistanceF(tempList, shortestDistance, closestPair)
closestPair
}
private def shortestDistanceF(tempList: List[Point], shortestDistance: Double, closestPair: Pair ): Pair = {
var shortest = shortestDistance
var bestResult = closestPair
for (i <- 0 until tempList.size) {
val point1 = tempList(i)
for (j <- i + 1 until tempList.size) {
val point2 = tempList(j)
if ((point2.y - point1.y) >= shortestDistance)
return closestPair
val distance = point1 distance point2
if (distance < closestPair.distance)
{
bestResult = Pair(point1, point2)
shortest = distance
}
}
}
closestPair
}
def main(args: Array[String]) {
val numPoints = if(args.length == 0) 1000 else args(0).toInt
val points = ListBuffer[Point]()
val r = new Random()
for (i <- 0 until numPoints) {
points.+=:(new Point(r.nextDouble(), r.nextDouble()))
}
println("Generated " + numPoints + " random points")
var startTime = System.currentTimeMillis()
val bruteForceClosestPair = bruteForce(points.toList)
var elapsedTime = System.currentTimeMillis() - startTime
println("Brute force (" + elapsedTime + " ms): " + bruteForceClosestPair)
startTime = System.currentTimeMillis()
val dqClosestPair = divideAndConquer(points.toList)
elapsedTime = System.currentTimeMillis() - startTime
println("Divide and conquer (" + elapsedTime + " ms): " + dqClosestPair)
if (bruteForceClosestPair.distance != dqClosestPair.distance)
println("MISMATCH")
}
}
|
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
| #PL.2FI | PL/I | twoci: Proc Options(main);
Dcl 1 *(5),
2 m1x Dec Float Init(0.1234, 0,0.1234,0.1234,0.1234),
2 m1y Dec Float Init(0.9876, 2,0.9876,0.9876,0.9876),
2 m2x Dec Float Init(0.8765, 0,0.1234,0.8765,0.1234),
2 m2y Dec Float Init(0.2345, 0,0.9876,0.2345,0.9876),
2 r Dec Float Init( 2, 1, 2,0.5 , 0);
Dcl i Bin Fixed(31);
Put Edit(' x1 y1 x2 y2 r '||
' cir1x cir1y cir2x cir2y')(Skip,a);
Put Edit(' ====== ====== ====== ====== = '||
' ====== ====== ====== ======')(Skip,a);
Do i=1 To 5;
Put Edit(m1x(i),m1y(i),m2x(i),m2y(i),r(i))
(Skip,4(f(7,4)),f(3));
Put Edit(twocircles(m1x(i),m1y(i),m2x(i),m2y(i),r(i)))(a);
End;
twoCircles: proc(m1x,m1y,m2x,m2y,r) Returns(Char(50) Var);
Dcl (m1x,m1y,m2x,m2y,r) Dec Float;
Dcl (cx,cy,bx,by,pb,x,y,x1,y1) Dec Float;
Dcl res Char(50) Var;
If r=0 then return(' radius of zero gives no circles.');
x=(m2x-m1x)/2;
y=(m2y-m1y)/2;
bx=m1x+x;
by=m1y+y;
pb=sqrt(x**2+y**2);
cx=(m2x-m1x)/2;
cy=(m2y-m1y)/2;
bx=m1x+x;
by=m1y+y;
pb=sqrt(x**2+y**2)
if pb=0 then return(' coincident points give infinite circles');
if pb>r then return(' points are too far apart for the given radius');
cb=sqrt(r**2-pb**2);
x1=y*cb/pb;
y1=x*cb/pb
Put String(res) Edit((bx-x1),(by+y1),(bx+x1),(by-y1))(4(f(8,4)));
Return(res);
End;
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).
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "console.s7i";
const array string: animals is [0] ("Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig");
const array string: elements is [0] ("Wood", "Fire", "Earth", "Metal", "Water");
const array string: animalChars is [0] ("子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥");
const array array string: elementChars is [0] ([0] ("甲", "丙", "戊", "庚", "壬"), [0] ("乙", "丁", "己", "辛", "癸"));
const proc: main is func
local
var integer: year is 0;
var integer: eIdx is 0;
var integer: aIdx is 0;
begin
OUT := STD_CONSOLE;
for year range {1935, 1938, 1968, 1972, 1976, 1984, 1985, 2017} do
eIdx := (year - 4) rem 10 div 2;
aIdx := (year - 4) rem 12;
writeln(year <& " is the year of the " <& elements[eIdx] <& " " <& animals[aIdx] <& " (" <&
([0] ("yang", "yin"))[year rem 2] <& "). " <& elementChars[year rem 2][eIdx] <& animalChars[aIdx]);
end for;
end func; |
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).
| #Sidef | Sidef | func zodiac(year) {
var animals = %w(Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog Pig)
var elements = %w(Wood Fire Earth Metal Water)
var terrestrial_han = %w(子 丑 寅 卯 辰 巳 午 未 申 酉 戌 亥)
var terrestrial_pinyin = %w(zĭ chŏu yín măo chén sì wŭ wèi shēn yŏu xū hài)
var celestial_han = %w(甲 乙 丙 丁 戊 己 庚 辛 壬 癸)
var celestial_pinyin = %w(jiă yĭ bĭng dīng wù jĭ gēng xīn rén gŭi)
var aspect = %w(yang yin)
var cycle_year = ((year-4) % 60)
var (i2, i10, i12) = (cycle_year%2, cycle_year%10, cycle_year%12)
(year,
celestial_han[i10], terrestrial_han[i12],
celestial_pinyin[i10], terrestrial_pinyin[i12],
elements[i10 >> 1], animals[i12], aspect[i2], cycle_year+1)
}
[1935, 1938, 1968, 1972, 1976, 2017].each { |year|
printf("%4d: %s%s (%s-%s) %s %s; %s - year %d of the cycle\n", zodiac(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
| #JavaScript | JavaScript | var fso = new ActiveXObject("Scripting.FileSystemObject");
fso.FileExists('input.txt');
fso.FileExists('c:/input.txt');
fso.FolderExists('docs');
fso.FolderExists('c:/docs'); |
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an unusual filename: `Abdu'l-Bahá.txt
| #Julia | Julia | @show isfile("input.txt")
@show isfile("/input.txt")
@show isdir("docs")
@show isdir("/docs")
@show isfile("")
@show isfile("`Abdu'l-Bahá.txt") |
http://rosettacode.org/wiki/Chaos_game | Chaos game | The Chaos Game is a method of generating the attractor of an iterated function system (IFS).
One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.
Task
Play the Chaos Game using the corners of an equilateral triangle as the reference points. Add a 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
| #R | R |
# Chaos Game (Sierpinski triangle) 2/15/17 aev
# pChaosGameS3(size, lim, clr, fn, ttl)
# Where: size - defines matrix and picture size; lim - limit of the dots;
# fn - file name (.ext will be added); ttl - plot title;
pChaosGameS3 <- function(size, lim, clr, fn, ttl)
{
cat(" *** START:", date(), "size=",size, "lim=",lim, "clr=",clr, "\n");
sz1=floor(size/2); sz2=floor(sz1*sqrt(3)); xf=yf=v=0;
M <- matrix(c(0), ncol=size, nrow=size, byrow=TRUE);
x <- sample(1:size, 1, replace=FALSE);
y <- sample(1:sz2, 1, replace=FALSE);
pf=paste0(fn, ".png");
for (i in 1:lim) { v <- sample(0:3, 1, replace=FALSE);
if(v==0) {x=x/2; y=y/2;}
if(v==1) {x=sz1+(sz1-x)/2; y=sz2-(sz2-y)/2;}
if(v==2) {x=size-(size-x)/2; y=y/2;}
xf=floor(x); yf=floor(y); if(xf<1||xf>size||yf<1||yf>size) {next};
M[xf,yf]=1;
}
plotmat(M, fn, clr, ttl, 0, size);
cat(" *** END:",date(),"\n");
}
pChaosGameS3(600, 30000, "red", "SierpTriR1", "Sierpinski triangle")
|
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
| #Racket | Racket | #lang racket
(require 2htdp/image)
(define SIZE 300)
(define (game-of-chaos fns WIDTH HEIGHT SIZE
#:offset-x [offset-x 0] #:offset-y [offset-y 0]
#:iters [iters 10000]
#:bg [bg 'white] #:fg [fg 'black])
(define dot (square 1 'solid fg))
(define all-choices (apply + (map first fns)))
(for/fold ([image (empty-scene WIDTH HEIGHT bg)]
[x (random)] [y (random)]
#:result image)
([i (in-range iters)])
(define picked (random all-choices))
(define fn (for/fold ([acc 0] [result #f] #:result result) ([fn (in-list fns)])
#:break (> acc picked)
(values (+ (first fn) acc) (second fn))))
(match-define (list x* y*) (fn x y))
(values (place-image dot (+ offset-x (* SIZE x*)) (+ offset-y (* SIZE y*)) image)
x* y*)))
(define (draw-triangle)
(define ((mid a b) x y) (list (/ (+ a x) 2) (/ (+ b y) 2)))
(define (triangle-height x) (* (sqrt 3) 0.5 x))
(game-of-chaos (list (list 1 (mid 0 0))
(list 1 (mid 1 0))
(list 1 (mid 0.5 (triangle-height 1))))
SIZE (triangle-height SIZE) SIZE))
(define (draw-fern)
(define (f1 x y) (list 0 (* 0.16 y)))
(define (f2 x y) (list (+ (* 0.85 x) (* 0.04 y)) (+ (* -0.04 x) (* 0.85 y) 1.6)))
(define (f3 x y) (list (+ (* 0.2 x) (* -0.26 y)) (+ (* 0.23 x) (* 0.22 y) 1.6)))
(define (f4 x y) (list (+ (* -0.15 x) (* 0.28 y)) (+ (* 0.26 x) (* 0.24 y) 0.44)))
(game-of-chaos (list (list 1 f1) (list 85 f2) (list 7 f3) (list 7 f4))
(/ SIZE 2) SIZE (/ SIZE 11) #:offset-x 70 #:offset-y 10
#:bg 'black #:fg 'white))
(define (draw-dragon)
(game-of-chaos
(list (list 1 (λ (x y) (list (+ (* 0.5 x) (* -0.5 y)) (+ (* 0.5 x) (* 0.5 y)))))
(list 1 (λ (x y) (list (+ (* -0.5 x) (* 0.5 y) 1) (+ (* -0.5 x) (* -0.5 y))))))
SIZE (* 0.8 SIZE) (/ SIZE 1.8) #:offset-x 64 #:offset-y 120))
(draw-triangle)
(draw-fern)
(draw-dragon) |
http://rosettacode.org/wiki/Chat_server | Chat server | Task
Write a server for a minimal text based chat.
People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
| #Wren | Wren | /* chat_server.wren */
class Clients {
foreign static max
foreign static count
foreign static isActive(vmi)
foreign static connfd(vmi)
foreign static uid(vmi)
foreign static name(vmi)
foreign static setName(vmi, s)
foreign static printAddr(vmi)
foreign static delete(vmi)
}
class Mutex {
foreign static clientsLock()
foreign static clientsUnlock()
foreign static topicLock()
foreign static topicUnlock()
}
class Chat {
// send message to all clients but the sender
static sendMessage(s, uid) {
Mutex.clientsLock()
for (i in 0...Clients.max) {
if (Clients.isActive(i) && Clients.uid(i) != uid) {
if (write(Clients.connfd(i), s, s.bytes.count) < 0) {
System.print("Write to descriptor %(Clients.connfd(i)) failed.")
break
}
}
}
Mutex.clientsUnlock()
}
// send message to all clients
static sendMessageAll(s) {
Mutex.clientsLock()
for (i in 0...Clients.max) {
if (Clients.isActive(i)) {
if (write(Clients.connfd(i), s, s.bytes.count) < 0) {
System.print("Write to descriptor %(Clients.connfd(i)) failed.")
break
}
}
}
Mutex.clientsUnlock()
}
// send message to sender
static sendMessageSelf(s, connfd) {
if (write(connfd, s, s.bytes.count) < 0) {
Fiber.abort("Write to descriptor %(connfd) failed.")
}
}
// send message to client
static sendMessageClient(s, uid) {
Mutex.clientsLock()
for (i in 0...Clients.max) {
if (Clients.isActive(i) && Clients.uid(i) == uid) {
if (write(Clients.connfd(i), s, s.bytes.count) < 0) {
System.print("Write to descriptor %(Clients.connfd(i)) failed.")
break
}
}
}
Mutex.clientsUnlock()
}
// send list of active clients
static sendActiveClients(connfd) {
Mutex.clientsLock()
for (i in 0...Clients.max) {
if (Clients.isActive(i)) {
var s = "<< [%(Clients.uid(i))] %(Clients.name(i))\r\n"
sendMessageSelf(s, connfd)
}
}
Mutex.clientsUnlock()
}
// handle all communication with the client
static handleClient(vmi) {
if (!Clients.isActive(vmi)) {
Fiber.abort("The client handled by VM[%(vmi)] is inactive.")
}
var connfd = Clients.connfd(vmi)
var uid = Clients.uid(vmi)
var name = Clients.name(vmi)
System.write("<< accept ")
Clients.printAddr(vmi)
System.print(" referenced by %(uid)")
var buffOut = "<< %(name) has joined\r\n"
sendMessageAll(buffOut)
Mutex.topicLock()
if (topic != "") {
buffOut = "<< topic: %(topic)\r\n"
sendMessageSelf(buffOut, connfd)
}
Mutex.topicUnlock()
sendMessageSelf("<< see /help for assistance\r\n", connfd)
/* receive input from client */
var buffIn = ""
while ((buffIn = read(connfd, bufferSize/2 - 1)) && buffIn.bytes.count > 0) {
buffOut = ""
buffIn = buffIn.trimEnd("\r\n")
/* ignore empty buffer */
if (buffIn == "") continue
/* special options */
if (buffIn[0] == "/") {
var split = buffIn.split(" ")
var command = split[0]
if (command == "/quit") {
break
} else if (command == "/ping") {
sendMessageSelf("<< pong\r\n", connfd)
} else if (command == "/topic") {
if (split.count > 0) {
Mutex.topicLock()
topic = split[1..-1].join(" ")
Mutex.topicUnlock()
buffOut = "<< topic changed to: %(topic)\r\n"
sendMessageAll(buffOut)
} else {
sendMessageSelf("<< message cannot be null\r\n", connfd)
}
} else if (command == "/nick") {
if (split.count > 0) {
var newName = split[1..-1].join(" ")
buffOut = "<< %(name) is now known as %(newName)\r\n"
Clients.setName(vmi, newName)
name = newName
sendMessageAll(buffOut)
} else {
sendMessageSelf("<< name cannot be null\r\n", connfd)
}
} else if (command == "/msg") {
if (split.count > 0) {
var toUid = Num.fromString(split[1])
if (split.count > 1) {
buffOut = "[PM][%(name)] "
buffOut = buffOut + split[2..-1].join(" ") + "\r\n"
sendMessageClient(buffOut, toUid)
} else {
sendMessageSelf("<< message cannot be null\r\n", connfd)
}
} else {
sendMessageSelf("<< reference cannot be null\r\n", connfd)
}
} else if (command == "/list") {
buffOut = "<< clients %(Clients.count)\r\n"
sendMessageSelf(buffOut, connfd)
sendActiveClients(connfd)
} else if (command == "/help") {
buffOut = ""
buffOut = buffOut + "<< /quit Quit chatroom\r\n"
buffOut = buffOut + "<< /ping Server test\r\n"
buffOut = buffOut + "<< /topic <message> Set chat topic\r\n"
buffOut = buffOut + "<< /nick <name> Change nickname\r\n"
buffOut = buffOut + "<< /msg <reference> <message> Send private message\r\n"
buffOut = buffOut + "<< /list Show active clients\r\n"
buffOut = buffOut + "<< /help Show help\r\n"
sendMessageSelf(buffOut, connfd)
} else {
sendMessageSelf("<< unknown command\r\n", connfd)
}
} else {
/* send message */
buffOut = "[%(name)] %(buffIn)\r\n"
sendMessage(buffOut, uid)
}
}
/* close connection */
buffOut = "<< [%(name)] has left\r\n"
sendMessageAll(buffOut)
close(connfd)
/* delete client from queue and yield thread (from C side) */
System.write("<< quit ")
Clients.printAddr(vmi)
System.print(" referenced by %(uid)")
Clients.delete(vmi)
}
foreign static topic
foreign static topic=(s)
foreign static bufferSize
foreign static write(connfd, buf, count)
foreign static read(connfd, count)
foreign static close(connfd)
} |
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.
| #Frink | Frink | println[char["a"]] // prints 97
println[chars["a"]] // prints [97] (an array)
println[char[97]] // prints a
println[char["Frink rules!"]] // prints [70, 114, 105, 110, 107, 32, 114, 117, 108, 101, 115, 33]
println[[70, 114, 105, 110, 107, 32, 114, 117, 108, 101, 115, 33]] // prints "Frink rules!" |
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.
| #Gambas | Gambas | Public Sub Form_Open()
Dim sChar As String
sChar = InputBox("Enter a character")
Print "Character " & sChar & " = ASCII " & Str(Asc(sChar))
sChar = InputBox("Enter a ASCII code")
Print "ASCII code " & sChar & " represents " & Chr(Val(sChar))
End |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square 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. | #REXX | REXX | /*REXX program performs the Cholesky decomposition on a square matrix & displays results*/
niner = '25 15 -5' , /*define a 3x3 matrix with elements. */
'15 18 0' ,
'-5 0 11'
call Cholesky niner
hexer = 18 22 54 42, /*define a 4x4 matrix with elements. */
22 70 86 62,
54 86 174 134,
42 62 134 106
call Cholesky hexer
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Cholesky: procedure; parse arg mat; say; say; call tell 'input array',mat
do r=1 for ord
do c=1 for r; $=0; do i=1 for c-1; $= $ + !.r.i * !.c.i; end /*i*/
if r=c then !.r.r= sqrt(!.r.r - $)
else !.r.c= 1 / !.c.c * (@.r.c - $)
end /*c*/
end /*r*/
call tell 'Cholesky factor',,!.,'─'
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
err: say; say; say '***error***!'; say; say arg(1); say; say; exit 13
/*──────────────────────────────────────────────────────────────────────────────────────*/
tell: parse arg hdr,x,y,sep; #=0; if sep=='' then sep= '═'
dPlaces= 5 /*# dec. places past the decimal point.*/
width =10 /*field width used to display elements.*/
if y=='' then !.=0
else do row=1 for ord; do col=1 for ord; x=x !.row.col; end; end
w=words(x)
do ord=1 until ord**2>=w; end /*a fast way to find the matrix's order*/
say
if ord**2\==w then call err "matrix elements don't form a square matrix."
say center(hdr, ((width + 1) * w) % ord, sep)
say
do row=1 for ord; z=
do col=1 for ord; #= # + 1
@.row.col= word(x, #)
if col<=row then !.row.col= @.row.col
z=z right( format(@.row.col, , dPlaces) / 1, width)
end /*col*/ /* ↑↑↑ */
say z /* └┴┴──◄──normalization for zero*/
end /*row*/
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); numeric digits; h=d+6
numeric form; m.=9; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_ %2
do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; return g/1 |
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
| #Perl | Perl | use strict;
my @c = (); # create an empty "array" collection
# fill it
push @c, 10, 11, 12;
push @c, 65;
# print it
print join(" ",@c) . "\n";
# create an empty hash
my %h = ();
# add some pair
$h{'one'} = 1;
$h{'two'} = 2;
# print it
foreach my $i ( keys %h ) {
print $i . " -> " . $h{$i} . "\n";
} |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
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
| #Rust | Rust |
fn comb<T: std::fmt::Default>(arr: &[T], n: uint) {
let mut incl_arr: ~[bool] = std::vec::from_elem(arr.len(), false);
comb_intern(arr, n, incl_arr, 0);
}
fn comb_intern<T: std::fmt::Default>(arr: &[T], n: uint, incl_arr: &mut [bool], index: uint) {
if (arr.len() < n + index) { return; }
if (n == 0) {
let mut it = arr.iter().zip(incl_arr.iter()).filter_map(|(val, incl)|
if (*incl) { Some(val) } else { None }
);
for val in it { print!("{} ", *val); }
print("\n");
return;
}
incl_arr[index] = true;
comb_intern(arr, n-1, incl_arr, index+1);
incl_arr[index] = false;
comb_intern(arr, n, incl_arr, index+1);
}
fn main() {
let arr1 = ~[1, 2, 3, 4, 5];
comb(arr1, 3);
let arr2 = ~["A", "B", "C", "D", "E"];
comb(arr2, 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.
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
condition="c"
IF (condition=="a") THEN
---> do something
ELSEIF (condition=="b") THEN
---> do something
ELSE
---> do something
ENDIF
|
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
{\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}}}
.
| #Ruby | Ruby |
def chinese_remainder(mods, remainders)
max = mods.inject( :* )
series = remainders.zip( mods ).map{|r,m| r.step( max, m ).to_a }
series.inject( :& ).first #returns nil when empty
end
p chinese_remainder([3,5,7], [2,3,2]) #=> 23
p chinese_remainder([10,4,9], [11,22,19]) #=> nil
|
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.
| #Python | Python | class MyClass:
name2 = 2 # Class attribute
def __init__(self):
"""
Constructor (Technically an initializer rather than a true "constructor")
"""
self.name1 = 0 # Instance attribute
def someMethod(self):
"""
Method
"""
self.name1 = 1
MyClass.name2 = 3
myclass = MyClass() # class name, invoked as a function is the constructor syntax.
class MyOtherClass:
count = 0 # Population of "MyOtherClass" objects
def __init__(self, name, gender="Male", age=None):
"""
One initializer required, others are optional (with different defaults)
"""
MyOtherClass.count += 1
self.name = name
self.gender = gender
if age is not None:
self.age = age
def __del__(self):
MyOtherClass.count -= 1
person1 = MyOtherClass("John")
print person1.name, person1.gender # "John Male"
print person1.age # Raises AttributeError exception!
person2 = MyOtherClass("Jane", "Female", 23)
print person2.name, person2.gender, person2.age # "Jane Female 23" |
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)
| #Seed7 | Seed7 | const type: point is new struct
var float: x is 0.0;
var float: y is 0.0;
end struct;
const func float: distance (in point: p1, in point: p2) is
return sqrt((p1.x-p2.x)**2+(p1.y-p2.y)**2);
const func array point: closest_pair (in array point: points) is func
result
var array point: result is 0 times point.value;
local
var float: dist is 0.0;
var float: minDistance is Infinity;
var integer: i is 0;
var integer: j is 0;
var integer: savei is 0;
var integer: savej is 0;
begin
for i range 1 to pred(length(points)) do
for j range succ(i) to length(points) do
dist := distance(points[i], points[j]);
if dist < minDistance then
minDistance := dist;
savei := i;
savej := j;
end if;
end for;
end for;
if minDistance <> Infinity then
result := [] (points[savei], points[savej]);
end if;
end func; |
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
| #PureBasic | PureBasic | DataSection
DataStart:
Data.d 0.1234, 0.9876, 0.8765, 0.2345, 2.0
Data.d 0.0000, 2.0000, 0.0000, 0.0000, 1.0
Data.d 0.1234, 0.9876, 0.1234, 0.9876, 2.0
Data.d 0.1234, 0.9876, 0.9765, 0.2345, 0.5
Data.d 0.1234, 0.9876, 0.1234, 0.9876, 0.0
DataEnd:
EndDataSection
Macro MaxRec : (?DataEnd-?DataStart)/SizeOf(P2r)-1 : EndMacro
Structure Pxy : x.d : y.d : EndStructure
Structure P2r : p1.Pxy : p2.Pxy : r.d : EndStructure
Structure PData : Prec.P2r[5] : EndStructure
Procedure.s cCenter(Rec.i)
If Rec<0 Or Rec>MaxRec : ProcedureReturn "Data set number incorrect." : EndIf
*myP.PData=?DataStart
r.d=*myP\Prec[Rec]\r
If r<=0.0 : ProcedureReturn "Illegal radius." : EndIf
r2.d=2.0*r
x1.d=*myP\Prec[Rec]\p1\x : x2.d=*myP\Prec[Rec]\p2\x
y1.d=*myP\Prec[Rec]\p1\y : y2.d=*myP\Prec[Rec]\p2\y
d.d=Sqr(Pow(x2-x1,2)+Pow(y2-y1,2))
If d=0.0 : ProcedureReturn "Identical points, infinite number of circles." : EndIf
If d>r2 : ProcedureReturn "No circles possible." : EndIf
z.d=Sqr(Pow(r,2)-Pow(d/2.0,2))
x3.d =(x1+x2)/2.0 : y3.d =(y1+y2)/2.0
cx1.d=x3+z*(y1-y2)/d : cy1.d=y3+z*(x2-x1)/d
cx2.d=x3-z*(y1-y2)/d : cy2.d=y3-z*(x2-x1)/d
If d=r2 : ProcedureReturn "Single circle at ("+StrD(cx1)+","+StrD(cy1)+")" : EndIf
ProcedureReturn "("+StrD(cx1)+","+StrD(cy1)+") and ("+StrD(cx2)+","+StrD(cy2)+")"
EndProcedure
If OpenConsole("")
For i=0 To MaxRec : PrintN(cCenter(i)) : Next : Input()
EndIf |
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).
| #tbas | tbas |
DATA "甲","乙","丙","丁","戊","己","庚","辛","壬","癸"
DECLARE celestial$(10)
MAT READ celestial$
DATA "子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"
DECLARE terrestrial$(12)
MAT READ terrestrial$
DATA "Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig"
DECLARE animals$(12)
MAT READ animals$
DATA "Wood","Fire","Earth","Metal","Water"
DECLARE elements$(5)
MAT READ elements$
DATA "yang","yin"
DECLARE aspects$(2)
MAT READ aspects$
DATA "jiă","yĭ","bĭng","dīng","wù","jĭ","gēng","xīn","rén","gŭi"
DATA "zĭ","chŏu","yín","măo","chén","sì","wŭ","wèi","shēn","yŏu","xū","hài"
DECLARE celestialpinyin$(UBOUND(celestial$(),1))
DECLARE terrestrialpinyin$(UBOUND(terrestrial$(),1))
MAT READ celestialpinyin$
MAT READ terrestrialpinyin$
DATA 1935,1938,1931,1961,1963,1991,1993,1996,2001
DECLARE years(9)
MAT READ years
DECLARE _base = 4
DECLARE _year
DECLARE cycleyear
DECLARE stemnumber
DECLARE stemhan$
DECLARE stempinyin$
DECLARE elementnumber
DECLARE element$
DECLARE branchnumber
DECLARE branchhan$
DECLARE branchpinyin$
DECLARE animal$
DECLARE aspectnumber
DECLARE aspect$
DECLARE index
DECLARE i
DECLARE top = UBOUND(years(),1)
FOR i = 1 TO top
_year = years(i)
cycleyear = _year - _base
stemnumber = MOD(cycleyear, 10)
stemhan$ = celestial$(stemnumber + 1)
stempinyin$ = celestialpinyin$(stemnumber + 1)
elementnumber = div(stemnumber, 2) + 1
element$ = elements$(elementnumber)
branchnumber = MOD(cycleyear, 12)
branchhan$ = terrestrial$(branchnumber + 1)
branchpinyin$ = terrestrialpinyin$(branchnumber + 1)
animal$ = animals$(branchnumber + 1)
aspectnumber = MOD(cycleyear, 2)
aspect$ = aspects$(aspectnumber + 1)
index = MOD(cycleyear, 60) + 1
PRINT _year;
PRINT TAB(5);stemhan$+branchhan$;
PRINT TAB(12);stempinyin$;"-";branchpinyin$;
PRINT TAB(25);element$;" ";animal$;" ("+aspect$+")";
PRINT TAB(50);"year";index;"of the cycle"
NEXT
|
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
| #Klingphix | Klingphix | include ..\Utilitys.tlhy
"foo.bar" "w" fopen
"Hallo !" over fputs
fclose
"fou.bar" "r" fopen
dup 0 < ( ["Could not open 'fou.bar' for reading" print drop] [fclose] ) if
" " input |
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an unusual filename: `Abdu'l-Bahá.txt
| #Kotlin | Kotlin | // version 1.0.6
import java.io.File
fun main(args: Array<String>) {
val filePaths = arrayOf("input.txt", "c:\\input.txt", "zero_length.txt", "`Abdu'l-Bahá.txt")
val dirPaths = arrayOf("docs", "c:\\docs")
for (filePath in filePaths) {
val f = File(filePath)
println("$filePath ${if (f.exists() && !f.isDirectory) "exists" else "does not exist"}")
}
for (dirPath in dirPaths) {
val d = File(dirPath)
println("$dirPath ${if (d.exists() && d.isDirectory) "exists" else "does not exist"}")
}
} |
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
| #Raku | Raku | use Image::PNG::Portable;
my ($w, $h) = (640, 640);
my $png = Image::PNG::Portable.new: :width($w), :height($h);
my @vertex = [0, 0], [$w, 0], [$w/2, $h];
my @xy = [0,0], [0,0], [0,0], [0,0];
# :degree must be equal to or less than @xy elements.
(^1e5).race(:4degree).map: {
my $p = ++$ % +@xy;
@xy[$p] = do given @vertex.pick -> @v { ((@xy[$p] »+« @v) »/» 2)».Int };
$png.set: |@xy[$p], 0, 255, 0;
}
$png.write: 'Chaos-game-perl6.png'; |
http://rosettacode.org/wiki/Chat_server | Chat server | Task
Write a server for a minimal text based chat.
People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
| #zkl | zkl | const PORT=23;
var users=Dictionary(); // ( handle:socket, ...)
pipe:=Thread.Pipe(); // how server tells thread to connect to user
fcn accept(pipe){ // a thread waiting for the server to send a socket
while(socket:=pipe.read()){
println("Somebody is connecting ...");
socket.read(); // telnet stuff
while(True){ // get credentials
reg name;
socket.write("Your handle: "); // bottle neck
try{ name = socket.read().text.strip() } catch(IOError){ continue }
if(users.holds(name)) socket.write("Handle is already in use.\n");
else if(name){
users[name] = socket;
chat.launch(name,socket); // thread
broadcast(name, "+++ %s arrived +++".fmt(name));
break; // wait for next connection
}
}//while
}//while
}.launch(pipe); // thread
fcn chat(name,socket){ // a thread, one per user
try{
socket.write("^D to disconnect\n");
while(True){
message:=socket.read().text.strip();
if(message=="\xff\xec") break; // ^D to disconnect.
broadcast(name, "%s> %s".fmt(name,message));
}
}catch{} // eg socket pukes
users.del(name); socket.close();
broadcast(name, "--- %s leaves ---".fmt(name));
}
// Send a message to all users from the given name.
fcn broadcast(name, message){ // called from user thread
println(message); // log message to server console
users.pump(Void,'wrap([(toName,socket)]){
if(toName != name) try{ socket.write(message + "\n") } catch(IOError){}
});
}
// Set up the server socket.
server:=Network.TCPServerSocket.open(PORT);
println("Listening on %s:%s".fmt(server.hostname,server.port));
server.listen(pipe); // Main event loop |
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.
| #GAP | GAP | # Code must be in 0 .. 255.
CharInt(65);
# 'A'
IntChar('Z');
# 90 |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #Go | Go | fmt.Println('a') // prints "97"
fmt.Println('π') // prints "960" |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square 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. | #Ring | Ring |
# Project : Cholesky decomposition
load "stdlib.ring"
decimals(5)
m1 = [[25, 15, -5],
[15, 18, 0],
[-5, 0, 11]]
cholesky(m1)
printarray(m1)
see nl
m2 = [[18, 22, 54, 42],
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106]]
cholesky(m2)
printarray(m2)
func cholesky(a)
l = newlist(len(a), len(a))
for i = 1 to len(a)
for j = 1 to i
s = 0
for k = 1 to j
s = s + l[i][k] * l[j][k]
next
if i = j
l[i][j] = sqrt(a[i][i] - s)
else
l[i][j] = (a[i][j] - s) / l[j][j]
ok
next
next
a = l
func printarray(a)
for row = 1 to len(a)
for col = 1 to len(a)
see "" + a[row][col] + " "
next
see nl
next
|
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. | #Ruby | Ruby | require 'matrix'
class Matrix
def symmetric?
return false if not square?
(0 ... row_size).each do |i|
(0 .. i).each do |j|
return false if self[i,j] != self[j,i]
end
end
true
end
def cholesky_factor
raise ArgumentError, "must provide symmetric matrix" unless symmetric?
l = Array.new(row_size) {Array.new(row_size, 0)}
(0 ... row_size).each do |k|
(0 ... row_size).each do |i|
if i == k
sum = (0 .. k-1).inject(0.0) {|sum, j| sum + l[k][j] ** 2}
val = Math.sqrt(self[k,k] - sum)
l[k][k] = val
elsif i > k
sum = (0 .. k-1).inject(0.0) {|sum, j| sum + l[i][j] * l[k][j]}
val = (self[k,i] - sum) / l[k][k]
l[i][k] = val
end
end
end
Matrix[*l]
end
end
puts Matrix[[25,15,-5],[15,18,0],[-5,0,11]].cholesky_factor
puts Matrix[[18, 22, 54, 42],
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106]].cholesky_factor |
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
| #Phix | Phix | with javascript_semantics
sequence collection = {}
collection = append(collection,"one")
collection = prepend(collection,2)
? collection -- {2,"one"}
|
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
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
| #Scala | Scala | implicit def toComb(m: Int) = new AnyRef {
def comb(n: Int) = recurse(m, List.range(0, n))
private def recurse(m: Int, l: List[Int]): List[List[Int]] = (m, l) match {
case (0, _) => List(Nil)
case (_, Nil) => Nil
case _ => (recurse(m - 1, l.tail) map (l.head :: _)) ::: recurse(m, l.tail)
}
} |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include 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.
| #TXR | TXR |
@(choose :shortest x)
@x:@y
@(or)
@x<--@y
@(or)
@x+@y
@(end) |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include 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.
| #UNIX_Shell | UNIX Shell | if test 3 -lt 5; then echo '3 is less than 5'; fi |
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
{\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}}}
.
| #Rust | Rust | fn egcd(a: i64, b: i64) -> (i64, i64, i64) {
if a == 0 {
(b, 0, 1)
} else {
let (g, x, y) = egcd(b % a, a);
(g, y - (b / a) * x, x)
}
}
fn mod_inv(x: i64, n: i64) -> Option<i64> {
let (g, x, _) = egcd(x, n);
if g == 1 {
Some((x % n + n) % n)
} else {
None
}
}
fn chinese_remainder(residues: &[i64], modulii: &[i64]) -> Option<i64> {
let prod = modulii.iter().product::<i64>();
let mut sum = 0;
for (&residue, &modulus) in residues.iter().zip(modulii) {
let p = prod / modulus;
sum += residue * mod_inv(p, modulus)? * p
}
Some(sum % prod)
}
fn main() {
let modulii = [3,5,7];
let residues = [2,3,2];
match chinese_remainder(&residues, &modulii) {
Some(sol) => println!("{}", sol),
None => println!("modulii not pairwise coprime")
}
} |
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}}}
.
| #Scala | Scala | import scala.util.{Success, Try}
object ChineseRemainderTheorem extends App {
def chineseRemainder(n: List[Int], a: List[Int]): Option[Int] = {
require(n.size == a.size)
val prod = n.product
def iter(n: List[Int], a: List[Int], sm: Int): Int = {
def mulInv(a: Int, b: Int): Int = {
def loop(a: Int, b: Int, x0: Int, x1: Int): Int = {
if (a > 1) loop(b, a % b, x1 - (a / b) * x0, x0) else x1
}
if (b == 1) 1
else {
val x1 = loop(a, b, 0, 1)
if (x1 < 0) x1 + b else x1
}
}
if (n.nonEmpty) {
val p = prod / n.head
iter(n.tail, a.tail, sm + a.head * mulInv(p, n.head) * p)
} else sm
}
Try {
iter(n, a, 0) % prod
} match {
case Success(v) => Some(v)
case _ => None
}
}
println(chineseRemainder(List(3, 5, 7), List(2, 3, 2)))
println(chineseRemainder(List(11, 12, 13), List(10, 4, 12)))
println(chineseRemainder(List(11, 22, 19), List(10, 4, 9)))
} |
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.
| #R | R | #You define a class simply by setting the class attribute of an object
circS3 <- list(radius=5.5, centre=c(3, 4.2))
class(circS3) <- "circle"
#plot is a generic function, so we can define a class specific method by naming it plot.classname
plot.circle <- function(x, ...)
{
t <- seq(0, 2*pi, length.out=200)
plot(x$centre[1] + x$radius*cos(t),
x$centre[2] + x$radius*sin(t),
type="l", ...)
}
plot(circS3) |
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)
| #Sidef | Sidef | func dist_squared(a, b) {
sqr(a[0] - b[0]) + sqr(a[1] - b[1])
}
func closest_pair_simple(arr) {
arr.len < 2 && return Inf
var (a, b, d) = (arr[0, 1], dist_squared(arr[0,1]))
arr.clone!
while (arr) {
var p = arr.pop
for l in arr {
var t = dist_squared(p, l)
if (t < d) {
(a, b, d) = (p, l, t)
}
}
}
return(a, b, d.sqrt)
}
func closest_pair_real(rx, ry) {
rx.len <= 3 && return closest_pair_simple(rx)
var N = rx.len
var midx = (ceil(N/2)-1)
var (PL, PR) = rx.part(midx)
var xm = rx[midx][0]
var yR = []
var yL = []
for item in ry {
(item[0] <= xm ? yR : yL) << item
}
var (al, bl, dL) = closest_pair_real(PL, yR)
var (ar, br, dR) = closest_pair_real(PR, yL)
al == Inf && return (ar, br, dR)
ar == Inf && return (al, bl, dL)
var (m1, m2, dmin) = (dR < dL ? [ar, br, dR]...
: [al, bl, dL]...)
var yS = ry.grep { |a| abs(xm - a[0]) < dmin }
var (w1, w2, closest) = (m1, m2, dmin)
for i in (0 ..^ yS.end) {
for k in (i+1 .. yS.end) {
yS[k][1] - yS[i][1] < dmin || break
var d = dist_squared(yS[k], yS[i]).sqrt
if (d < closest) {
(w1, w2, closest) = (yS[k], yS[i], d)
}
}
}
return (w1, w2, closest)
}
func closest_pair(r) {
var ax = r.sort_by { |a| a[0] }
var ay = r.sort_by { |a| a[1] }
return closest_pair_real(ax, ay);
}
var N = 5000
var points = N.of { [1.rand*20 - 10, 1.rand*20 - 10] }
var (af, bf, df) = closest_pair(points)
say "#{df} at (#{af.join(' ')}), (#{bf.join(' ')})" |
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
| #Python | Python | from collections import namedtuple
from math import sqrt
Pt = namedtuple('Pt', 'x, y')
Circle = Cir = namedtuple('Circle', 'x, y, r')
def circles_from_p1p2r(p1, p2, r):
'Following explanation at http://mathforum.org/library/drmath/view/53027.html'
if r == 0.0:
raise ValueError('radius of zero')
(x1, y1), (x2, y2) = p1, p2
if p1 == p2:
raise ValueError('coincident points gives infinite number of Circles')
# delta x, delta y between points
dx, dy = x2 - x1, y2 - y1
# dist between points
q = sqrt(dx**2 + dy**2)
if q > 2.0*r:
raise ValueError('separation of points > diameter')
# halfway point
x3, y3 = (x1+x2)/2, (y1+y2)/2
# distance along the mirror line
d = sqrt(r**2-(q/2)**2)
# One answer
c1 = Cir(x = x3 - d*dy/q,
y = y3 + d*dx/q,
r = abs(r))
# The other answer
c2 = Cir(x = x3 + d*dy/q,
y = y3 - d*dx/q,
r = abs(r))
return c1, c2
if __name__ == '__main__':
for p1, p2, r in [(Pt(0.1234, 0.9876), Pt(0.8765, 0.2345), 2.0),
(Pt(0.0000, 2.0000), Pt(0.0000, 0.0000), 1.0),
(Pt(0.1234, 0.9876), Pt(0.1234, 0.9876), 2.0),
(Pt(0.1234, 0.9876), Pt(0.8765, 0.2345), 0.5),
(Pt(0.1234, 0.9876), Pt(0.1234, 0.9876), 0.0)]:
print('Through points:\n %r,\n %r\n and radius %f\nYou can construct the following circles:'
% (p1, p2, r))
try:
print(' %r\n %r\n' % circles_from_p1p2r(p1, p2, r))
except ValueError as v:
print(' ERROR: %s\n' % (v.args[0],)) |
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese 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).
| #Tcl | Tcl |
proc cn_zodiac year {
set year0 [expr $year-4]
set animals {Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog Pig}
set elements {Wood Fire Earth Metal Water}
set stems {jia3 yi3 bing3 ding1 wu4 ji3 geng1 xin1 ren2 gui3}
set gan {\u7532 \u4E59 \u4E19 \u4E01 \u620A \u5DF1 \u5E9A \u8F9B \u58EC \u7678}
set branches {zi3 chou3 yin2 mao3 chen2 si4 wu3 wei4 shen1 you3 xu1 hai4}
set zhi {\u5B50 \u4E11 \u5BC5 \u536F \u8FB0 \u5DF3 \u5348 \u672A \u7533 \u9149 \u620C \u4EA5}
set m10 [expr $year0%10]
set m12 [expr $year0%12]
set res [lindex $gan $m10][lindex $zhi $m12]
lappend res [lindex $stems $m10]-[lindex $branches $m12]
lappend res [lindex $elements [expr $m10/2]]
lappend res [lindex $animals $m12] ([expr {$year0%2 ? "yin" : "yang"}])
lappend res year [expr $year0%60+1]
return $res
}
|
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
| #LabVIEW | LabVIEW | // local file
file_exists('input.txt')
// local directory
file_exists('docs')
// file in root file system (requires permissions at user OS level)
file_exists('//input.txt')
// directory in root file system (requires permissions at user OS level)
file_exists('//docs') |
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an unusual filename: `Abdu'l-Bahá.txt
| #Lasso | Lasso | // local file
file_exists('input.txt')
// local directory
file_exists('docs')
// file in root file system (requires permissions at user OS level)
file_exists('//input.txt')
// directory in root file system (requires permissions at user OS level)
file_exists('//docs') |
http://rosettacode.org/wiki/Chaos_game | Chaos game | The Chaos Game is a method of generating the attractor of an iterated function system (IFS).
One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.
Task
Play the Chaos Game using the corners of an equilateral triangle as the reference points. Add a 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
| #REXX | REXX | /*REXX pgm draws a Sierpinski triangle by running the chaos game with a million points*/
parse value scrsize() with sd sw . /*obtain the depth and width of screen.*/
sw= sw - 2 /*adjust the screen width down by two. */
sd= sd - 4 /* " " " depth " " four.*/
parse arg pts chr seed . /*obtain optional arguments from the CL*/
if pts=='' | pts=="," then pts= 1000000 /*Not specified? Then use the default.*/
if chr=='' | chr=="," then chr= '∙' /* " " " " " " */
if datatype(seed,'W') then call random ,,seed /*Is specified? " " RANDOM seed.*/
x= sw; hx= x % 2; y= sd /*define the initial starting position.*/
@.= ' ' /* " all screen points as a blank. */
do pts; ?= random(1, 3) /* [↓] draw a # of (million?) points.*/
select /*?: will be a random number: 1 ──► 3.*/
when ?==1 then parse value x%2 y%2 with x y
when ?==2 then parse value hx+(hx-x)%2 sd-(sd-y)%2 with x y
otherwise parse value sw-(sw-x)%2 y%2 with x y
end /*select*/
@.x.y= chr /*set the X, Y point to a bullet.*/
end /*pts*/ /* [↑] one million points ≡ overkill? */
/* [↓] display the points to the term.*/
do row=sd to 0 by -1; _= /*display the points, one row at a time*/
do col=0 for sw+2 /* " a row (one line) of image. */
_= _ || @.col.row /*construct a " " " " " */
end /*col*/ /*Note: display image from top──►bottom*/
/* [↑] strip trailing blanks (output).*/
say strip(_, 'T') /*display one row (line) of the image. */
end /*row*/ /*stick a fork in it, we're all 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.
| #Golfscript | Golfscript | 97[]+''+p |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #Groovy | Groovy | printf ("%d\n", ('a' as char) as int)
printf ("%c\n", 97) |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square 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. | #Rust | Rust | fn cholesky(mat: Vec<f64>, n: usize) -> Vec<f64> {
let mut res = vec![0.0; mat.len()];
for i in 0..n {
for j in 0..(i+1){
let mut s = 0.0;
for k in 0..j {
s += res[i * n + k] * res[j * n + k];
}
res[i * n + j] = if i == j { (mat[i * n + i] - s).sqrt() } else { (1.0 / res[j * n + j] * (mat[i * n + j] - s)) };
}
}
res
}
fn show_matrix(matrix: Vec<f64>, n: usize){
for i in 0..n {
for j in 0..n {
print!("{:.4}\t", matrix[i * n + j]);
}
println!("");
}
println!("");
}
fn main(){
let dimension = 3 as usize;
let m1 = vec![25.0, 15.0, -5.0,
15.0, 18.0, 0.0,
-5.0, 0.0, 11.0];
let res1 = cholesky(m1, dimension);
show_matrix(res1, dimension);
let dimension = 4 as usize;
let m2 = vec![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];
let res2 = cholesky(m2, dimension);
show_matrix(res2, dimension);
}
|
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
| #PHP | PHP | <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?> |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
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
| #Scheme | Scheme | (define (comb m lst)
(cond ((= m 0) '(()))
((null? lst) '())
(else (append (map (lambda (y) (cons (car lst) y))
(comb (- m 1) (cdr lst)))
(comb m (cdr lst))))))
(comb 3 '(0 1 2 3 4)) |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include 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.
| #Unison | Unison | factorial : Nat -> Nat
factorial x =
if x == 0 then 1
else
x * fac (Nat.drop x 1) |
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
{\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}}}
.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "bigint.s7i";
const func integer: modInverse (in integer: a, in integer: b) is
return ord(modInverse(bigInteger conv a, bigInteger conv b));
const proc: main is func
local
const array integer: n is [] (3, 5, 7);
const array integer: a is [] (2, 3, 2);
var integer: num is 0;
var integer: prod is 1;
var integer: sum is 0;
var integer: index is 0;
begin
for num range n do
prod *:= num;
end for;
for key index range a do
num := prod div n[index];
sum +:= a[index] * modInverse(num, n[index]) * num;
end for;
writeln(sum mod prod);
end func; |
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}}}
.
| #Sidef | Sidef | func chinese_remainder(*n) {
var N = n.prod
func (*a) {
n.range.sum { |i|
var p = (N / n[i])
a[i] * p.invmod(n[i]) * p
} % N
}
}
say chinese_remainder(3, 5, 7)(2, 3, 2) |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, 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.
| #Racket | Racket |
#lang racket
(define fish%
(class object%
(super-new)
;; an instance variable & constructor argument
(init-field size)
;; a new method
(define/public (eat)
(displayln "gulp!"))))
;; constructing an instance
(new fish% [size 50])
|
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, 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.
| #Raku | Raku | class Camel { has Int $.humps = 1; }
my Camel $a .= new;
say $a.humps; # Automatically generated accessor method.
my Camel $b .= new: humps => 2;
say $b.humps; |
http://rosettacode.org/wiki/Closest-pair_problem | Closest-pair problem |
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a function to find the closest two 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)
| #Smalltalk | Smalltalk | import Foundation
struct Point {
var x: Double
var y: Double
func distance(to p: Point) -> Double {
let x = pow(p.x - self.x, 2)
let y = pow(p.y - self.y, 2)
return (x + y).squareRoot()
}
}
extension Collection where Element == Point {
func closestPair() -> (Point, Point)? {
let (xP, xY) = (sorted(by: { $0.x < $1.x }), sorted(by: { $0.y < $1.y }))
return Self.closestPair(xP, xY)?.1
}
static func closestPair(_ xP: [Element], _ yP: [Element]) -> (Double, (Point, Point))? {
guard xP.count > 3 else { return xP.closestPairBruteForce() }
let half = xP.count / 2
let xl = Array(xP[..<half])
let xr = Array(xP[half...])
let xm = xl.last!.x
let (yl, yr) = yP.reduce(into: ([Element](), [Element]()), {cur, el in
if el.x > xm {
cur.1.append(el)
} else {
cur.0.append(el)
}
})
guard let (distanceL, pairL) = closestPair(xl, yl) else { return nil }
guard let (distanceR, pairR) = closestPair(xr, yr) else { return nil }
let (dMin, pairMin) = distanceL > distanceR ? (distanceR, pairR) : (distanceL, pairL)
let ys = yP.filter({ abs(xm - $0.x) < dMin })
var (closest, pairClosest) = (dMin, pairMin)
for i in 0..<ys.count {
let p1 = ys[i]
for k in i+1..<ys.count {
let p2 = ys[k]
guard abs(p2.y - p1.y) < dMin else { break }
let distance = abs(p1.distance(to: p2))
if distance < closest {
(closest, pairClosest) = (distance, (p1, p2))
}
}
}
return (closest, pairClosest)
}
func closestPairBruteForce() -> (Double, (Point, Point))? {
guard count >= 2 else { return nil }
var closestPoints = (self.first!, self[index(after: startIndex)])
var minDistance = abs(closestPoints.0.distance(to: closestPoints.1))
guard count != 2 else { return (minDistance, closestPoints) }
for i in 0..<count {
for j in i+1..<count {
let (iIndex, jIndex) = (index(startIndex, offsetBy: i), index(startIndex, offsetBy: j))
let (p1, p2) = (self[iIndex], self[jIndex])
let distance = abs(p1.distance(to: p2))
if distance < minDistance {
minDistance = distance
closestPoints = (p1, p2)
}
}
}
return (minDistance, closestPoints)
}
}
var points = [Point]()
for _ in 0..<10_000 {
points.append(Point(
x: .random(in: -10.0...10.0),
y: .random(in: -10.0...10.0)
))
}
print(points.closestPair()!) |
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
| #Racket | Racket |
#lang racket
(require plot/utils)
(define (circle-centers p1 p2 r)
(when (zero? r) (err "zero radius."))
(when (equal? p1 p2) (err "the points coinside."))
; the midle point
(define m (v/ (v+ p1 p2) 2))
; the vector connecting given points
(define d (v/ (v- p1 p2) 2))
; the distance between the center of the circle and the middle point
(define ξ (- (sqr r) (vmag^2 d)))
(when (negative? ξ) (err "given radius is less then the distance between points."))
; the unit vector orthogonal to the delta
(define n (vnormalize (orth d)))
; the shift along the direction orthogonal to the delta
(define x (v* n (sqrt ξ)))
(values (v+ m x) (v- m x)))
;; error message
(define (err m) (error "Impossible to build a circle:" m))
;; returns a vector which is orthogonal to the geven one
(define orth (match-lambda [(vector x y) (vector y (- x))]))
|
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese 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).
| #uBasic.2F4tH | uBasic/4tH | dim @y(2) ' yin or yang
dim @e(5) ' the elements
dim @a(12) ' the animals
Push Dup("yang"), Dup("yin") ' fill Ying/Yang table
For i = 1 to 0 step -1 : @y(i) = Pop() : Next i
' fill Elements table
Push Dup("Wood"), Dup("Fire"), Dup("Earth"), Dup("Metal"), Dup("Water")
For i = 4 to 0 step -1 : @e(i) = Pop() : Next i
' fill Animals table
Push Dup("Rat"), Dup("Ox"), Dup("Tiger"), Dup("Rabbit"), Dup("Dragon")
Push Dup("Snake"), Dup("Horse"), Dup("Goat"), Dup("Monkey"), Dup("Rooster")
Push Dup("Dog"), Dup("Pig")
For i = 11 to 0 step -1 : @a(i) = Pop() : Next i
' now push all the test years
Push 76543, 2186, 2020, 1984, 1861, 1801
' and process them all
Do While Used() ' until the stack is empty
Print Show(FUNC(_Chinese(Pop()))) ' call function
Loop
End
_Chinese ' compose string
Param (1)
Local (3)
b@ = a@ % 2
c@ = (a@ - 4) % 5
d@ = (a@ - 4) % 12
Return (Join(Str (a@), " is the year of the ", @e(c@), " ", @a(d@), " (", @y(b@), ")."))
|
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
| #LFE | LFE |
> (: filelib is_regular '"input.txt")
false
> (: filelib is_dir '"docs")
false
> (: filelib is_regular '"/input.txt")
false
> (: filelib is_dir '"/docs"))
false
|
http://rosettacode.org/wiki/Chaos_game | Chaos game | The Chaos Game is a method of generating the attractor of an iterated function system (IFS).
One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.
Task
Play the Chaos Game using the corners of an equilateral triangle as the reference points. Add a 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
| #Ring | Ring |
# Project : Chaos game
load "guilib.ring"
paint = null
new qapp
{
win1 = new qwidget() {
setwindowtitle("Archimedean spiral")
setgeometry(100,100,500,600)
label1 = new qlabel(win1) {
setgeometry(10,10,400,400)
settext("")
}
new qpushbutton(win1) {
setgeometry(150,500,100,30)
settext("draw")
setclickevent("draw()")
}
show()
}
exec()
}
func draw
p1 = new qpicture()
color = new qcolor() {
setrgb(0,0,255,255)
}
pen = new qpen() {
setcolor(color)
setwidth(1)
}
paint = new qpainter() {
begin(p1)
setpen(pen)
x = floor(random(10)/10 * 200)
y = floor(random(10/10) * 173)
for i = 1 to 20000
v = floor(random(10)/10 * 3) + 1
if v = 1
x = x/2
y = y/2
ok
if v = 2
x = 100 + (100-x)/2
y = 173 - (173-y)/2
ok
if v = 3
x = 200 - (200-x)/2
y = y/2
ok
drawpoint(x,y)
next
endpaint()
}
label1 {setpicture(p1) show()}
|
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.
| #Haskell | Haskell | import Data.Char
main = do
print (ord 'a') -- prints "97"
print (chr 97) -- prints "'a'"
print (ord 'π') -- prints "960"
print (chr 960) -- prints "'\960'" |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square 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. | #Scala | Scala | case class Matrix( val matrix:Array[Array[Double]] ) {
// Assuming matrix is positive-definite, symmetric and not empty...
val rows,cols = matrix.size
def getOption( r:Int, c:Int ) : Option[Double] = Pair(r,c) match {
case (r,c) if r < rows && c < rows => Some(matrix(r)(c))
case _ => None
}
def isLowerTriangle( r:Int, c:Int ) : Boolean = { c <= r }
def isDiagonal( r:Int, c:Int ) : Boolean = { r == c}
override def toString = matrix.map(_.mkString(", ")).mkString("\n")
/**
* Perform Cholesky Decomposition of this matrix
*/
lazy val cholesky : Matrix = {
val l = Array.ofDim[Double](rows*cols)
for( i <- (0 until rows); j <- (0 until cols) ) yield {
val s = (for( k <- (0 until j) ) yield { l(i*rows+k) * l(j*rows+k) }).sum
l(i*rows+j) = (i,j) match {
case (r,c) if isDiagonal(r,c) => scala.math.sqrt(matrix(i)(i) - s)
case (r,c) if isLowerTriangle(r,c) => (1.0 / l(j*rows+j) * (matrix(i)(j) - s))
case _ => 0
}
}
val m = Array.ofDim[Double](rows,cols)
for( i <- (0 until rows); j <- (0 until cols) ) m(i)(j) = l(i*rows+j)
Matrix(m)
}
}
// A little test...
val a1 = Matrix(Array[Array[Double]](Array(25,15,-5),Array(15,18,0),Array(-5,0,11)))
val a2 = Matrix(Array[Array[Double]](Array(18,22,54,42), Array(22,70,86,62), Array(54,86,174,134), Array(42,62,134,106)))
val l1 = a1.cholesky
val l2 = a2.cholesky
// Given test results
val r1 = Array[Double](5,0,0,3,3,0,-1,1,3)
val r2 = Array[Double](4.24264,0.00000,0.00000,0.00000,5.18545,6.56591,0.00000,0.00000,
12.72792,3.04604,1.64974,0.00000,9.89949,1.62455,1.84971,1.39262)
// Verify assertions
(l1.matrix.flatten.zip(r1)).foreach{ case (result,test) =>
assert(math.round( result * 100000 ) * 0.00001 == math.round( test * 100000 ) * 0.00001)
}
(l2.matrix.flatten.zip(r2)).foreach{ case (result,test) =>
assert(math.round( result * 100000 ) * 0.00001 == math.round( test * 100000 ) * 0.00001)
} |
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
| #Picat | Picat | go =>
L = [1,2,3,4],
L2 = L ++ [[5,6,7]], % adding a list
L3 = ["a string"] ++ L2, % adding a string
% Prolog way
append([0],L,[5],L4). |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
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
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const type: combinations is array array integer;
const func combinations: comb (in array integer: arr, in integer: k) is func
result
var combinations: combResult is combinations.value;
local
var integer: x is 0;
var integer: i is 0;
var array integer: suffix is 0 times 0;
begin
if k = 0 then
combResult := 1 times 0 times 0;
else
for x key i range arr do
for suffix range comb(arr[succ(i) ..], pred(k)) do
combResult &:= [] (x) & suffix;
end for;
end for;
end if;
end func;
const proc: main is func
local
var array integer: aCombination is 0 times 0;
var integer: element is 0;
begin
for aCombination range comb([] (0, 1, 2, 3, 4), 3) do
for element range aCombination do
write(element lpad 3);
end for;
writeln;
end for;
end func; |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #V | V | [true]
['is true' puts]
['is false' puts]
ifte
=is true |
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
{\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}}}
.
| #SQL | SQL | CREATE TEMPORARY TABLE inputs(remainder INT, modulus INT);
INSERT INTO inputs VALUES (2, 3), (3, 5), (2, 7);
WITH recursive
-- Multiply out the product of moduli
multiplication(idx, product) AS (
SELECT 1, 1
UNION ALL
SELECT
multiplication.idx+1,
multiplication.product * inputs.modulus
FROM
multiplication,
inputs
WHERE
inputs.rowid = multiplication.idx
),
-- Take the final value from the product table
product(final_value) AS (
SELECT MAX(product) FROM multiplication
),
-- Calculate the multiplicative inverse from each equation
multiplicative_inverse(id, a, b, x, y) AS (
SELECT
inputs.modulus,
product.final_value / inputs.modulus,
inputs.modulus,
0,
1
FROM
inputs,
product
UNION ALL
SELECT
id,
b, a%b,
y - (a/b)*x, x
FROM
multiplicative_inverse
WHERE
a>0
)
-- Combine residues into final answer
SELECT
SUM(
(y % inputs.modulus) * inputs.remainder * (product.final_value / inputs.modulus)
) % product.final_value
FROM
multiplicative_inverse, product, inputs
WHERE
a=1 AND multiplicative_inverse.id = inputs.modulus;
|
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.
| #RapidQ | RapidQ | TYPE MyClass EXTENDS QObject
Variable AS INTEGER
CONSTRUCTOR
Variable = 0
END CONSTRUCTOR
SUB someMethod
MyClass.Variable = 1
END SUB
END TYPE
' create an instance
DIM instance AS MyClass
' invoke the method
instance.someMethod |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, 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.
| #Raven | Raven | class Alpha
'I am Alpha.' as greeting
define say_hello
greeting print
class Beta extend Alpha
'I am Beta!' as greeting |
http://rosettacode.org/wiki/Closest-pair_problem | Closest-pair problem |
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a function to find the closest two 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)
| #Swift | Swift | import Foundation
struct Point {
var x: Double
var y: Double
func distance(to p: Point) -> Double {
let x = pow(p.x - self.x, 2)
let y = pow(p.y - self.y, 2)
return (x + y).squareRoot()
}
}
extension Collection where Element == Point {
func closestPair() -> (Point, Point)? {
let (xP, xY) = (sorted(by: { $0.x < $1.x }), sorted(by: { $0.y < $1.y }))
return Self.closestPair(xP, xY)?.1
}
static func closestPair(_ xP: [Element], _ yP: [Element]) -> (Double, (Point, Point))? {
guard xP.count > 3 else { return xP.closestPairBruteForce() }
let half = xP.count / 2
let xl = Array(xP[..<half])
let xr = Array(xP[half...])
let xm = xl.last!.x
let (yl, yr) = yP.reduce(into: ([Element](), [Element]()), {cur, el in
if el.x > xm {
cur.1.append(el)
} else {
cur.0.append(el)
}
})
guard let (distanceL, pairL) = closestPair(xl, yl) else { return nil }
guard let (distanceR, pairR) = closestPair(xr, yr) else { return nil }
let (dMin, pairMin) = distanceL > distanceR ? (distanceR, pairR) : (distanceL, pairL)
let ys = yP.filter({ abs(xm - $0.x) < dMin })
var (closest, pairClosest) = (dMin, pairMin)
for i in 0..<ys.count {
let p1 = ys[i]
for k in i+1..<ys.count {
let p2 = ys[k]
guard abs(p2.y - p1.y) < dMin else { break }
let distance = abs(p1.distance(to: p2))
if distance < closest {
(closest, pairClosest) = (distance, (p1, p2))
}
}
}
return (closest, pairClosest)
}
func closestPairBruteForce() -> (Double, (Point, Point))? {
guard count >= 2 else { return nil }
var closestPoints = (self.first!, self[index(after: startIndex)])
var minDistance = abs(closestPoints.0.distance(to: closestPoints.1))
guard count != 2 else { return (minDistance, closestPoints) }
for i in 0..<count {
for j in i+1..<count {
let (iIndex, jIndex) = (index(startIndex, offsetBy: i), index(startIndex, offsetBy: j))
let (p1, p2) = (self[iIndex], self[jIndex])
let distance = abs(p1.distance(to: p2))
if distance < minDistance {
minDistance = distance
closestPoints = (p1, p2)
}
}
}
return (minDistance, closestPoints)
}
}
var points = [Point]()
for _ in 0..<10_000 {
points.append(Point(
x: .random(in: -10.0...10.0),
y: .random(in: -10.0...10.0)
))
}
print(points.closestPair()!) |
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
| #Raku | Raku | multi sub circles (@A, @B where ([and] @A Z== @B), 0.0) { 'Degenerate point' }
multi sub circles (@A, @B where ([and] @A Z== @B), $) { 'Infinitely many share a point' }
multi sub circles (@A, @B, $radius) {
my @middle = (@A Z+ @B) X/ 2;
my @diff = @A Z- @B;
my $q = sqrt [+] @diff X** 2;
return 'Too far apart' if $q > $radius * 2;
my @orth = -@diff[0], @diff[1] X* sqrt($radius ** 2 - ($q / 2) ** 2) / $q;
return (@middle Z+ @orth), (@middle Z- @orth);
}
my @input =
([0.1234, 0.9876], [0.8765, 0.2345], 2.0),
([0.0000, 2.0000], [0.0000, 0.0000], 1.0),
([0.1234, 0.9876], [0.1234, 0.9876], 2.0),
([0.1234, 0.9876], [0.8765, 0.2345], 0.5),
([0.1234, 0.9876], [0.1234, 0.9876], 0.0),
;
for @input {
say .list.raku, ': ', circles(|$_).join(' and ');
} |
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).
| #UNIX_Shell | UNIX Shell | #!/usr/bin/env bash
declare -A pinyin=(
[甲]='jiă'
[乙]='yĭ'
[丙]='bĭng'
[丁]='dīng'
[戊]='wù'
[己]='jĭ'
[庚]='gēng'
[辛]='xīn'
[壬]='rén'
[癸]='gŭi'
[子]='zĭ'
[丑]='chŏu'
[寅]='yín'
[卯]='măo'
[辰]='chén'
[巳]='sì'
[午]='wŭ'
[未]='wèi'
[申]='shén'
[酉]='yŏu'
[戌]='xū'
[亥]='hài'
)
celestial=(甲 乙 丙 丁 戊 己 庚 辛 壬 癸)
terrestrial=(子 丑 寅 卯 辰 巳 午 未 申 酉 戌 亥)
animals=(Rat Ox Tiger Rabbit Dragon Snake
Horse Goat Monkey Rooster Dog Pig)
elements=(Wood Fire Earth Metal Water)
aspects=(yang yin)
BaseYear=4
function main {
if (( !$# )); then
set -- $(date +%Y)
fi
local year
for year; do
if (( $# > 1 )); then
printf '%s:' "$year"
fi
local -i cycle_year=year-BaseYear
local -i stem_number=$cycle_year%${#celestial[@]}
local stem_han=${celestial[$stem_number]}
local stem_pinyin=${pinyin[$stem_han]}
local -i element_number=stem_number/2
local element=${elements[$element_number]}
local -i branch_number=$cycle_year%${#terrestrial[@]}
local branch_han=${terrestrial[$branch_number]}
local branch_pinyin=${pinyin[$branch_han]}
local animal=${animals[$branch_number]}
local -i aspect_number=$cycle_year%${#aspects[@]}
local aspect=${aspects[$aspect_number]}
printf '%s%s' $stem_han $branch_han
printf '(%s-%s, %s %s; %s)\n' $stem_pinyin $branch_pinyin $element $animal $aspect
done
}
main "$@" |
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).
| #UTFool | UTFool |
···
http://rosettacode.org/wiki/Chinese_zodiac
···
■ ChineseZodiac
§ static
tiangan⦂ String[][]: ¤ · 10 celestial stems
¤ "甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"
¤ "jiă", "yĭ", "bĭng", "dīng", "wù", "jĭ", "gēng", "xīn", "rén", "gŭi"
dizhi⦂ String[][]: ¤ · 12 terrestrial branches
¤ "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"
¤ "zĭ", "chŏu", "yín", "măo", "chén", "sì", "wŭ", "wèi", "shēn", "yŏu", "xū", "hài"
wuxing⦂ String[][]: ¤ · 5 traditional elements
¤ "木", "火", "土", "金", "水"
¤ "mù", "huǒ", "tǔ", "jīn", "shuǐ"
¤ "wood", "fire", "earth", "metal", "water"
shengxiao⦂ String[][]: ¤ · 12 animal deities
¤ "鼠", "牛", "虎", "兔", "龍", "蛇", "馬", "羊", "猴", "鸡", "狗", "豬"
¤ "shǔ", "niú", "hǔ", "tù", "lóng", "shé", "mǎ", "yáng", "hóu", "jī", "gǒu", "zhū"
¤ "rat", "ox", "tiger", "rabbit", "dragon", "snake", "horse", "goat", "monkey", "rooster", "dog", "pig"
yinyang⦂ String[][]: ¤ · 2 fundamental principles
¤ "阳", "阴"
¤ "yáng", "yīn"
▶ main
• args⦂ String[]
for each year ∈ [1935, 1938, 1968, 1972, 1976, 1984, 1985, 1986, 2017]⦂ int
cycle⦂ int: year - 4
stem⦂ int: cycle \ 10
branch⦂ int: cycle \ 12
System.out.printf "%4s %-8s %-6s %-6s %s\n", year, tiangan[0][stem] ⊕ dizhi[0][branch],
wuxing[0][stem / 2], shengxiao[0][branch], yinyang[0][year \ 2]
System.out.printf " %-9s %-7s %-7s %s\n", tiangan[1][stem] ⊕ dizhi[1][branch],
wuxing[1][stem / 2], shengxiao[1][branch], yinyang[1][year \ 2]
System.out.printf " %-2s/60 %-7s %s\n\n", cycle \ 60 + 1,
wuxing[2][stem / 2], shengxiao[2][branch]
|
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
| #Liberty_BASIC | Liberty BASIC | 'fileExists.bas - Show how to determine if a file exists
dim info$(10,10)
input "Type a file path (ie. c:\windows\somefile.txt)?"; fpath$
if fileExists(fpath$) then
print fpath$; " exists!"
else
print fpath$; " doesn't exist!"
end if
end
'return a true if the file in fullPath$ exists, else return false
function fileExists(fullPath$)
files pathOnly$(fullPath$), filenameOnly$(fullPath$), info$()
fileExists = val(info$(0, 0)) > 0
end function
'return just the directory path from a full file path
function pathOnly$(fullPath$)
pathOnly$ = fullPath$
while right$(pathOnly$, 1) <> "\" and pathOnly$ <> ""
pathOnly$ = left$(pathOnly$, len(pathOnly$)-1)
wend
end function
'return just the filename from a full file path
function filenameOnly$(fullPath$)
pathLength = len(pathOnly$(fullPath$))
filenameOnly$ = right$(fullPath$, len(fullPath$)-pathLength)
end function |
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
| #Run_BASIC | Run BASIC | x = int(rnd(0) * 200)
y = int(rnd(0) * 173)
graphic #g, 200,200
#g color("green")
for i =1 TO 20000
v = int(rnd(0) * 3) + 1
if v = 1 then
x = x/2
y = y/2
end if
if v = 2 then
x = 100 + (100-x)/2
y = 173 - (173-y)/2
end if
if v = 3 then
x = 200 - (200-x)/2
y = y/2
end if
#g set(x,y)
next
render #g |
http://rosettacode.org/wiki/Chaos_game | Chaos game | The Chaos Game is a method of generating the attractor of an iterated function system (IFS).
One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.
Task
Play the Chaos Game using the corners of an equilateral triangle as the reference points. Add a 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
| #Rust | Rust |
extern crate image;
extern crate rand;
use rand::prelude::*;
use std::f32;
fn main() {
let max_iterations = 50_000;
let img_side = 800;
let tri_size = 400.0;
// Create a new ImgBuf
let mut imgbuf = image::ImageBuffer::new(img_side, img_side);
// Create triangle vertices
let mut vertices: [[f32; 2]; 3] = [[0.0, 0.0]; 3];
for i in 0..vertices.len() {
vertices[i][0] = (img_side as f32 / 2.0)
+ (tri_size / 2.0) * (f32::consts::PI * i as f32 * 2.0 / 3.0).cos();
vertices[i][1] = (img_side as f32 / 2.0)
+ (tri_size / 2.0) * (f32::consts::PI * i as f32 * 2.0 / 3.0).sin();
}
for v in &vertices {
imgbuf.put_pixel(v[0] as u32, v[1] as u32, image::Luma([255u8]));
}
println!("Verticies: {:?}", vertices);
// Iterate chaos game
let mut rng = rand::thread_rng();
let mut x = img_side as f32 / 2.0;
let mut y = img_side as f32 / 2.0;
for _ in 0..max_iterations {
let choice = rng.gen_range(0..vertices.len());
x = (x + vertices[choice][0]) / 2.0;
y = (y + vertices[choice][1]) / 2.0;
imgbuf.put_pixel(x as u32, y as u32, image::Luma([255u8]));
}
// Save image
imgbuf.save("fractal.png").unwrap();
}
|
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.
| #HicEst | HicEst | WRITE(Messagebox) ICHAR('a'), CHAR(97) |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #HolyC | HolyC | Print("%d\n", 'a'); /* prints "97" */
Print("%c\n", 97); /* prints "a" */ |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square 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. | #Scilab | Scilab | a = [25 15 -5; 15 18 0; -5 0 11];
chol(a)
ans =
5. 3. -1.
0. 3. 1.
0. 0. 3.
a = [18 22 54 42; 22 70 86 62;
54 86 174 134; 42 62 134 106];
chol(a)
ans =
4.2426407 5.1854497 12.727922 9.8994949
0. 6.5659052 3.0460385 1.6245539
0. 0. 1.6497422 1.849711
0. 0. 0. 1.3926212 |
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
| #PicoLisp | PicoLisp | : (setq Lst (3 4 5 6))
-> (3 4 5 6)
: (push 'Lst 2)
-> 2
: (push 'Lst 1)
-> 1
: Lst
-> (1 2 3 4 5 6)
: (insert 4 Lst 'X)
-> (1 2 3 X 4 5 6) |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
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
| #SETL | SETL | print({0..4} npow 3); |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include 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.
| #VBA | VBA |
Sub C_S_If()
Dim A$, B$
A = "Hello"
B = "World"
'test
If A = B Then Debug.Print A & " = " & B
'other syntax
If A = B Then
Debug.Print A & " = " & B
Else
Debug.Print A & " and " & B & " are differents."
End If
'other syntax
If A = B Then
Debug.Print A & " = " & B
Else: Debug.Print A & " and " & B & " are differents."
End If
'other syntax
If A = B Then Debug.Print A & " = " & B _
Else Debug.Print A & " and " & B & " are differents."
'other syntax
If A = B Then Debug.Print A & " = " & B Else Debug.Print A & " and " & B & " are differents."
If A = B Then Debug.Print A & " = " & B Else: Debug.Print A & " and " & B & " are differents."
End Sub |
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}}}
.
| #Swift | Swift | import Darwin
/*
* Function: euclid
* Usage: (r,s) = euclid(m,n)
* --------------------------
* The extended Euclidean algorithm subsequently performs
* Euclidean divisions till the remainder is zero and then
* returns the Bézout coefficients r and s.
*/
func euclid(_ m:Int, _ n:Int) -> (Int,Int) {
if m % n == 0 {
return (0,1)
} else {
let rs = euclid(n % m, m)
let r = rs.1 - rs.0 * (n / m)
let s = rs.0
return (r,s)
}
}
/*
* Function: gcd
* Usage: x = gcd(m,n)
* -------------------
* The greatest common divisor of two numbers a and b
* is expressed by ax + by = gcd(a,b) where x and y are
* the Bézout coefficients as determined by the extended
* euclidean algorithm.
*/
func gcd(_ m:Int, _ n:Int) -> Int {
let rs = euclid(m, n)
return m * rs.0 + n * rs.1
}
/*
* Function: coprime
* Usage: truth = coprime(m,n)
* ---------------------------
* If two values are coprime, their greatest common
* divisor is 1.
*/
func coprime(_ m:Int, _ n:Int) -> Bool {
return gcd(m,n) == 1 ? true : false
}
coprime(14,26)
//coprime(2,4)
/*
* Function: crt
* Usage: x = crt(a,n)
* -------------------
* The Chinese Remainder Theorem supposes that given the
* integers n_1...n_k that are pairwise co-prime, then for
* any sequence of integers a_1...a_k there exists an integer
* x that solves the system of linear congruences:
*
* x === a_1 (mod n_1)
* ...
* x === a_k (mod n_k)
*/
func crt(_ a_i:[Int], _ n_i:[Int]) -> Int {
// There is no identity operator for elements of [Int].
// The offset of the elements of an enumerated sequence
// can be used instead, to determine if two elements of the same
// array are the same.
let divs = n_i.enumerated()
// Check if elements of n_i are pairwise coprime divs.filter{ $0.0 < n.0 }
divs.forEach{
n in divs.filter{ $0.0 < n.0 }.forEach{
assert(coprime(n.1, $0.1))
}
}
// Calculate factor N
let N = n_i.map{$0}.reduce(1, *)
// Euclidean algorithm determines s_i (and r_i)
var s:[Int] = []
// Using euclidean algorithm to calculate r_i, s_i
n_i.forEach{ s += [euclid($0, N / $0).1] }
// Solve for x
var x = 0
a_i.enumerated().forEach{
x += $0.1 * s[$0.0] * N / n_i[$0.0]
}
// Return minimal solution
return x % N
}
let a = [2,3,2]
let n = [3,5,7]
let x = crt(a,n)
print(x) |
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}}}
.
| #Tcl | Tcl | proc ::tcl::mathfunc::mulinv {a b} {
if {$b == 1} {return 1}
set b0 $b; set x0 0; set x1 1
while {$a > 1} {
set x0 [expr {$x1 - ($a / $b) * [set x1 $x0]}]
set b [expr {$a % [set a $b]}]
}
incr x1 [expr {($x1 < 0) * $b0}]
}
proc chineseRemainder {nList aList} {
set sum 0; set prod [::tcl::mathop::* {*}$nList]
foreach n $nList a $aList {
set p [expr {$prod / $n}]
incr sum [expr {$a * mulinv($p, $n) * $p}]
}
expr {$sum % $prod}
}
puts [chineseRemainder {3 5 7} {2 3 2}] |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, 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.
| #REALbasic | REALbasic |
Class NumberContainer
Private TheNumber As Integer
Sub Constructor(InitialNumber As Integer)
TheNumber = InitialNumber
End Sub
Function Number() As Integer
Return TheNumber
End Function
Sub Number(Assigns NewNumber As Integer)
TheNumber = NewNumber
End Sub
End Class
|
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, 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.
| #REBOL | REBOL | rebol [
Title: "Classes"
URL: http://rosettacode.org/wiki/Classes
]
; Objects are derived from the base 'object!' type. REBOL uses a
; prototyping object system, so any object can be treated as a class,
; from which to derive others.
cowboy: make object! [
name: "Tex" ; Instance variable.
hi: does [ ; Method.
print [self/name ": Howdy!"]]
]
; I create two instances of the 'cowboy' class.
tex: make cowboy []
roy: make cowboy [
name: "Roy" ; Override 'name' property.
]
print "Say 'hello', boys:" tex/hi roy/hi
print ""
; Now I'll subclass 'cowboy'. Subclassing looks a lot like instantiation:
legend: make cowboy [
deed: "..."
boast: does [
print [self/name ": I once" self/deed "!"]]
]
; Instancing the legend:
pecos: make legend [name: "Pecos Bill" deed: "lassoed a twister"]
print "Howdy, Pecos!" pecos/hi
print "Tell us about yourself?" pecos/boast |
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)
| #Tcl | Tcl | package require Tcl 8.5
# retrieve the x-coordinate
proc x p {lindex $p 0}
# retrieve the y-coordinate
proc y p {lindex $p 1}
proc distance {p1 p2} {
expr {hypot(([x $p1]-[x $p2]), ([y $p1]-[y $p2]))}
}
proc closest_bruteforce {points} {
set n [llength $points]
set mindist Inf
set minpts {}
for {set i 0} {$i < $n - 1} {incr i} {
for {set j [expr {$i + 1}]} {$j < $n} {incr j} {
set p1 [lindex $points $i]
set p2 [lindex $points $j]
set dist [distance $p1 $p2]
if {$dist < $mindist} {
set mindist $dist
set minpts [list $p1 $p2]
}
}
}
return [list $mindist $minpts]
}
proc closest_recursive {points} {
set n [llength $points]
if {$n <= 3} {
return [closest_bruteforce $points]
}
set xP [lsort -real -increasing -index 0 $points]
set mid [expr {int(ceil($n/2.0))}]
set PL [lrange $xP 0 [expr {$mid-1}]]
set PR [lrange $xP $mid end]
set procname [lindex [info level 0] 0]
lassign [$procname $PL] dL pairL
lassign [$procname $PR] dR pairR
if {$dL < $dR} {
set dmin $dL
set dpair $pairL
} else {
set dmin $dR
set dpair $pairR
}
set xM [x [lindex $PL end]]
foreach p $xP {
if {abs($xM - [x $p]) < $dmin} {
lappend S $p
}
}
set yP [lsort -real -increasing -index 1 $S]
set closest Inf
set nP [llength $yP]
for {set i 0} {$i <= $nP-2} {incr i} {
set yPi [lindex $yP $i]
for {set k [expr {$i+1}]; set yPk [lindex $yP $k]} {
$k < $nP-1 && ([y $yPk]-[y $yPi]) < $dmin
} {incr k; set yPk [lindex $yP $k]} {
set dist [distance $yPk $yPi]
if {$dist < $closest} {
set closest $dist
set closestPair [list $yPi $yPk]
}
}
}
expr {$closest < $dmin ? [list $closest $closestPair] : [list $dmin $dpair]}
}
# testing
set N 10000
for {set i 1} {$i <= $N} {incr i} {
lappend points [list [expr {rand()*100}] [expr {rand()*100}]]
}
# instrument the number of calls to [distance] to examine the
# efficiency of the recursive solution
trace add execution distance enter comparisons
proc comparisons args {incr ::comparisons}
puts [format "%-10s %9s %9s %s" method compares time closest]
foreach method {bruteforce recursive} {
set ::comparisons 0
set time [time {set ::dist($method) [closest_$method $points]} 1]
puts [format "%-10s %9d %9d %s" $method $::comparisons [lindex $time 0] [lindex $::dist($method) 0]]
} |
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points | Circles of given radius through two points |
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
Exceptions
r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
If the points are coincident then an infinite number of circles with the point on 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
| #REXX | REXX | /*REXX pgm finds 2 circles with a specific radius given 2 (X1,Y1) and (X2,Y2) ctr points*/
@.=; @.1= 0.1234 0.9876 0.8765 0.2345 2
@.2= 0 2 0 0 1
@.3= 0.1234 0.9876 0.1234 0.9876 2
@.4= 0.1234 0.9876 0.8765 0.2345 0.5
@.5= 0.1234 0.9876 0.1234 0.9876 0
say ' x1 y1 x2 y2 radius circle1x circle1y circle2x circle2y'
say ' ════════ ════════ ════════ ════════ ══════ ════════ ════════ ════════ ════════'
do j=1 while @.j\==''; parse var @.j p1 p2 p3 p4 r /*points, radii*/
say fmt(p1) fmt(p2) fmt(p3) fmt(p4) center(r/1, 9) "───► " 2circ(@.j)
end /*j*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
2circ: procedure; parse arg px py qx qy r .; x= (qx-px)/2; y= (qy-py)/2
bx= px + x; by= py + y
pb= sqrt(x**2 + y**2)
if r = 0 then return 'radius of zero yields no circles.'
if pb==0 then return 'coincident points give infinite circles.'
if pb >r then return 'points are too far apart for the specified radius.'
cb= sqrt(r**2 - pb**2); x1= y * cb / pb; y1= x * cb / pb
return fmt(bx-x1) fmt(by+y1) fmt(bx+x1) fmt(by-y1)
/*──────────────────────────────────────────────────────────────────────────────────────*/
fmt: arg f; f= right( format(f, , 4), 9); _= f /*format # with 4 dec digits*/
if pos(.,f)>0 & pos('E',f)=0 then f= strip(f,'T',0) /*strip trailing 0s if .& ¬E*/
return left( strip(f, 'T', .), length(_) ) /*strip trailing dec point. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure; arg x; if x=0 then return 0; d=digits(); numeric digits; h=d+6; m.=9
numeric form; parse value format(x,2,1,,0) 'E0' with g "E" _ .; g=g *.5'e'_ % 2
do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; return g |
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).
| #VBScript | VBScript | ' Chinese zodiac - VBS
Animals = array( "Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig" )
Elements = array( "Wood","Fire","Earth","Metal","Water" )
YinYang = array( "Yang","Yin" )
Years = array( 1935, 1938, 1968, 1972, 1976, 1984, 2017 )
for i = LBound(Years) to UBound(Years)
xYear = Years(i)
yElement = Elements(((xYear - 4) mod 10) \ 2)
yAnimal = Animals( (xYear - 4) mod 12 )
yYinYang = YinYang( xYear mod 2 )
nn = ((xYear - 4) mod 60) + 1
msgbox xYear & " is the year of the " & yElement & " " & yAnimal & " (" & yYinYang & ").",, _
xYear & " : " & nn & "/60"
next |
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
| #Little | Little | if (exists("input.txt")) {
puts("The file \"input.txt\" exist");
}
if (exists("/input.txt")) {
puts("The file \"/input.txt\" exist");
}
if (exists("docs")) {
puts("The file \"docs\" exist");
}
if (exists("/docs")) {
puts("The file \"/docs\" exist");
} |
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an unusual filename: `Abdu'l-Bahá.txt
| #LiveCode | LiveCode | there is a file "/input.txt"
there is a file "input.txt"
there is a folder "docs"
there is a file "/docs/input.txt" |
http://rosettacode.org/wiki/Chaos_game | Chaos game | The Chaos Game is a method of generating the attractor of an iterated function system (IFS).
One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.
Task
Play the Chaos Game using the corners of an equilateral triangle as the reference points. Add a 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
| #Scala | Scala | import javax.swing._
import java.awt._
import java.awt.event.ActionEvent
import scala.collection.mutable
import scala.util.Random
object ChaosGame extends App {
SwingUtilities.invokeLater(() =>
new JFrame("Chaos Game") {
class ChaosGame extends JPanel {
private val (dim, margin)= (new Dimension(640, 640), 60)
private val sizez: Int = dim.width - 2 * margin
private val (stack, r) = (new mutable.Stack[ColoredPoint], new Random)
private val points = Seq(new Point(dim.width / 2, margin),
new Point(margin, sizez),
new Point(margin + sizez, sizez)
)
private val colors = Seq(Color.red, Color.green, Color.blue)
override def paintComponent(gg: Graphics): Unit = {
val g = gg.asInstanceOf[Graphics2D]
def drawPoints(g: Graphics2D): Unit = {
for (p <- stack) {
g.setColor(colors(p.colorIndex))
g.fillOval(p.x, p.y, 1, 1)
}
}
super.paintComponent(gg)
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
drawPoints(g)
}
private def addPoint(): Unit = {
val colorIndex = r.nextInt(3)
def halfwayPoint(a: Point, b: Point, idx: Int) =
new ColoredPoint((a.x + b.x) / 2, (a.y + b.y) / 2, idx)
stack.push(halfwayPoint(stack.top, points(colorIndex), colorIndex))
}
class ColoredPoint(x: Int, y: Int, val colorIndex: Int) extends Point(x, y)
stack.push(new ColoredPoint(-1, -1, 0))
new Timer(100, (_: ActionEvent) => {
if (stack.size < 50000) {
for (i <- 0 until 1000) addPoint()
repaint()
}
}).start()
setBackground(Color.white)
setPreferredSize(dim)
}
add(new ChaosGame, BorderLayout.CENTER)
pack()
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
setLocationRelativeTo(null)
setResizable(false)
setVisible(true)
}
)
} |
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.
| #Hoon | Hoon | |%
++ enc
|= char=@t `@ud`char
++ dec
|= code=@ud `@t`code
-- |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #i | i | software {
print(number('a'))
print(text([97]))
} |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square 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. | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
include "math.s7i";
const type: matrix is array array float;
const func matrix: cholesky (in matrix: a) is func
result
var matrix: cholesky is 0 times 0 times 0.0;
local
var integer: i is 0;
var integer: j is 0;
var integer: k is 0;
var float: sum is 0.0;
begin
cholesky := length(a) times length(a) times 0.0;
for key i range cholesky do
for j range 1 to i do
sum := 0.0;
for k range 1 to j do
sum +:= cholesky[i][k] * cholesky[j][k];
end for;
if i = j then
cholesky[i][i] := sqrt(a[i][i] - sum)
else
cholesky[i][j] := (a[i][j] - sum) / cholesky[j][j];
end if;
end for;
end for;
end func;
const proc: writeMat (in matrix: a) is func
local
var integer: i is 0;
var float: num is 0.0;
begin
for key i range a do
for num range a[i] do
write(num digits 5 lpad 8);
end for;
writeln;
end for;
end func;
const matrix: m1 is [] (
[] (25.0, 15.0, -5.0),
[] (15.0, 18.0, 0.0),
[] (-5.0, 0.0, 11.0));
const matrix: m2 is [] (
[] (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));
const proc: main is func
begin
writeMat(cholesky(m1));
writeln;
writeMat(cholesky(m2));
end func; |
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
| #PL.2FI | PL/I |
declare countries character (20) varying controlled;
allocate countries initial ('Britain');
allocate countries initial ('America');
allocate countries initial ('Argentina');
|
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
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
| #Sidef | Sidef | combinations(5, 3, {|*c| say c }) |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include 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.
| #VBScript | VBScript | If condition1 Then
statement
End If
If condition1 Then
statement
ElseIf condition2 Then
statement
...
ElseIf conditionN Then
statement
Else
statement
End If
|
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
{\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}}}
.
| #uBasic.2F4tH | uBasic/4tH | @(000) = 3 : @(001) = 5 : @(002) = 7
@(100) = 2 : @(101) = 3 : @(102) = 2
Print Func (_Chinese_Remainder (3))
' -------------------------------------
@(000) = 11 : @(001) = 12 : @(002) = 13
@(100) = 10 : @(101) = 04 : @(102) = 12
Print Func (_Chinese_Remainder (3))
' -------------------------------------
End
' returns x where (a * x) % b == 1
_Mul_Inv Param (2) ' ( a b -- n)
Local (4)
c@ = b@
d@ = 0
e@ = 1
If b@ = 1 Then Return (1)
Do While a@ > 1
f@ = a@ / b@
Push b@ : b@ = a@ % b@ : a@ = Pop()
Push d@ : d@ = e@ - f@ * d@ : e@ = Pop()
Loop
If e@ < 0 Then e@ = e@ + c@
Return (e@)
_Chinese_Remainder Param (1) ' ( len -- n)
Local (5)
b@ = 1
c@ = 0
For d@ = 0 Step 1 While d@ < a@
b@ = b@ * @(d@)
Next
For d@ = 0 Step 1 While d@ < a@
e@ = b@ / @(d@)
c@ = c@ + (@(100 + d@) * Func (_Mul_Inv (e@, @(d@))) * e@)
Next
Return (c@ % b@)
|
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.
| #Ring | Ring |
New point { x=10 y=20 z=30 print() }
Class Point x y z func print see x + nl + y + nl + z + nl
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.