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/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Visual_Basic | Visual Basic | 'comment
Rem comment
#If 0
Technically not a comment; the compiler may or may not ignore this, but the
IDE won't. Note the somewhat odd formatting seen here; the IDE will likely
just mark the entire line(s) as errors.
#End If |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Visual_Basic_.NET | Visual Basic .NET | ' This is a comment
REM This is also a comment
Dim comment as string ' You can also append comments to statements
Dim comment2 as string REM You can append comments to statements |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Visual_Objects | Visual Objects |
// This is a comment
/* This is a comment */
* This is a comment
&& This is a comment
NOTE This is a commen
* This is a comment
&& This is a comment
NOTE This is a commen
|
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The sequence is named after Sarvadaman D. S. Chowla, (22 October 1907 ──► 10 December 1995),
a London born Indian American mathematician specializing in number theory.
German mathematician Carl Friedrich Gauss (1777─1855) said:
"Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics".
Definitions
Chowla numbers can also be expressed as:
chowla(n) = sum of divisors of n excluding unity and n
chowla(n) = sum( divisors(n)) - 1 - n
chowla(n) = sum( properDivisors(n)) - 1
chowla(n) = sum(aliquotDivisors(n)) - 1
chowla(n) = aliquot(n) - 1
chowla(n) = sigma(n) - 1 - n
chowla(n) = sigmaProperDivisiors(n) - 1
chowla(a*b) = a + b, if a and b are distinct primes
if chowla(n) = 0, and n > 1, then n is prime
if chowla(n) = n - 1, and n > 1, then n is a perfect number
Task
create a chowla function that returns the chowla number for a positive integer n
Find and display (1 per line) for the 1st 37 integers:
the integer (the index)
the chowla number for that integer
For finding primes, use the chowla function to find values of zero
Find and display the count of the primes up to 100
Find and display the count of the primes up to 1,000
Find and display the count of the primes up to 10,000
Find and display the count of the primes up to 100,000
Find and display the count of the primes up to 1,000,000
Find and display the count of the primes up to 10,000,000
For finding perfect numbers, use the chowla function to find values of n - 1
Find and display all perfect numbers up to 35,000,000
use commas within appropriate numbers
show all output here
Related tasks
totient function
perfect numbers
Proper divisors
Sieve of Eratosthenes
See also
the OEIS entry for A48050 Chowla's function.
| #Ada | Ada | with Ada.Text_IO;
procedure Chowla_Numbers is
function Chowla (N : Positive) return Natural is
Sum : Natural := 0;
I : Positive := 2;
J : Positive;
begin
while I * I <= N loop
if N mod I = 0 then
J := N / I;
Sum := Sum + I + (if I = J then 0 else J);
end if;
I := I + 1;
end loop;
return Sum;
end Chowla;
procedure Put_37_First is
use Ada.Text_IO;
begin
for A in Positive range 1 .. 37 loop
Put_Line ("chowla(" & A'Image & ") = " & Chowla (A)'Image);
end loop;
end Put_37_First;
procedure Put_Prime is
use Ada.Text_IO;
Count : Natural := 0;
Power : Positive := 100;
begin
for N in Positive range 2 .. 10_000_000 loop
if Chowla (N) = 0 then
Count := Count + 1;
end if;
if N mod Power = 0 then
Put_Line ("There is " & Count'Image & " primes < " & Power'Image);
Power := Power * 10;
end if;
end loop;
end Put_Prime;
procedure Put_Perfect is
use Ada.Text_IO;
Count : Natural := 0;
Limit : constant := 350_000_000;
K : Natural := 2;
Kk : Natural := 3;
P : Natural;
begin
loop
P := K * Kk;
exit when P > Limit;
if Chowla (P) = P - 1 then
Put_Line (P'Image & " is a perfect number");
Count := Count + 1;
end if;
K := Kk + 1;
Kk := Kk + K;
end loop;
Put_Line ("There are " & Count'Image & " perfect numbers < " & Limit'Image);
end Put_Perfect;
begin
Put_37_First;
Put_Prime;
Put_Perfect;
end Chowla_Numbers; |
http://rosettacode.org/wiki/Church_numerals | Church numerals | Task
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
Church one applies its first argument f just once to its second argument x, yielding f(x)
Church two applies its first argument f twice to its second argument x, yielding f(f(x))
and each successive Church numeral applies its first argument one additional time to its second argument, f(f(f(x))), f(f(f(f(x)))) ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument.
Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals.
In your language define:
Church Zero,
a Church successor function (a function on a Church numeral which returns the next Church numeral in the series),
functions for Addition, Multiplication and Exponentiation over Church numerals,
a function to convert integers to corresponding Church numerals,
and a function to convert Church numerals to corresponding integers.
You should:
Derive Church numerals three and four in terms of Church zero and a Church successor function.
use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4,
similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function,
convert each result back to an integer, and return it or print it to the console.
| #Erlang | Erlang | -module(church).
-export([main/1, zero/1]).
zero(_) -> fun(F) -> F end.
succ(N) -> fun(F) -> fun(X) -> F((N(F))(X)) end end.
add(N,M) -> fun(F) -> fun(X) -> (M(F))((N(F))(X)) end end.
mult(N,M) -> fun(F) -> fun(X) -> (M(N(F)))(X) end end.
power(B,E) -> E(B).
to_int(C) -> CountUp = fun(I) -> I + 1 end, (C(CountUp))(0).
from_int(0) -> fun church:zero/1;
from_int(I) -> succ(from_int(I-1)).
main(_) ->
Zero = fun church:zero/1,
Three = succ(succ(succ(Zero))),
Four = from_int(4),
lists:map(fun(C) -> io:fwrite("~w~n",[to_int(C)]) end,
[add(Three,Four), mult(Three,Four),
power(Three,Four), power(Four,Three)]).
|
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.
| #Clojure | Clojure |
; You can think of this as an interface
(defprotocol Foo (getFoo [this]))
; Generates Example1 Class with foo as field, with method that returns foo.
(defrecord Example1 [foo] Foo (getFoo [this] foo))
; Create instance and invoke our method to return field value
(-> (Example1. "Hi") .getFoo)
"Hi" |
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.
| #COBOL | COBOL | IDENTIFICATION DIVISION.
CLASS-ID. my-class INHERITS base.
*> The 'INHERITS base' and the following ENVIRONMENT DIVISION
*> are optional (in Visual COBOL).
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
CLASS base.
*> There is no way (as far as I can tell) of creating a
*> constructor. However, you could wrap it with another
*> method to achieve the desired effect.
*>...
OBJECT.
*> Instance data
DATA DIVISION.
WORKING-STORAGE SECTION.
01 instance-variable PIC 9(8).
*> Properties can have getters and setters automatically
*> generated.
01 a-property PIC 9(8) PROPERTY.
PROCEDURE DIVISION.
METHOD-ID. some-method.
PROCEDURE DIVISION.
*> ...
END METHOD some-method.
END OBJECT.
END CLASS my-class.
IDENTIFICATION DIVISION.
PROGRAM-ID. example-class-use.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
*> These declarations brings the class and property into
*> scope.
CLASS my-class
PROPERTY a-property.
DATA DIVISION.
WORKING-STORAGE SECTION.
*> Declaring a my-class reference variable.
01 instance USAGE OBJECT REFERENCE my-class.
PROCEDURE DIVISION.
*> Invoking a static method or (in this case) a constructor.
INVOKE my-class "new" RETURNING instance
*> Invoking an instance method.
INVOKE instance "some-method"
*> Using the setter and getter of a-property.
MOVE 5 TO a-property OF instance
DISPLAY a-property OF instance
GOBACK
.
END PROGRAM example-class-use. |
http://rosettacode.org/wiki/Cistercian_numerals | Cistercian numerals | Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999.
How they work
All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyphs representing the digits 1 through 9 are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:
The upper-right quadrant represents the ones place.
The upper-left quadrant represents the tens place.
The lower-right quadrant represents the hundreds place.
The lower-left quadrant represents the thousands place.
Please consult the following image for examples of Cistercian numerals showing each glyph: [1]
Task
Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).
Use the routine to show the following Cistercian numerals:
0
1
20
300
4000
5555
6789
And a number of your choice!
Notes
Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed — especially for text output.
See also
Numberphile - The Forgotten Number System
dcode.fr - Online Cistercian numeral converter
| #Julia | Julia | using Gtk, Cairo
const can = GtkCanvas(800, 100)
const win = GtkWindow(can, "Canvas")
const numbers = [0, 1, 20, 300, 4000, 5555, 6789, 8123]
function drawcnum(ctx, xypairs)
move_to(ctx, xypairs[1][1], xypairs[1][2])
for p in xypairs[2:end]
line_to(ctx, p[1], p[2])
end
stroke(ctx)
end
@guarded draw(can) do widget
ctx = getgc(can)
hlen, wlen, len = height(can), width(can), length(numbers)
halfwspan, thirdcolspan, voffset = wlen ÷ (len * 2), wlen ÷ (len * 3), hlen ÷ 8
set_source_rgb(ctx, 0, 0, 2550)
for (i, n) in enumerate(numbers)
# paint vertical as width 2 rectangle
x = halfwspan * (2 * i - 1)
rectangle(ctx, x, voffset, 2, hlen - 2 * voffset)
stroke(ctx)
# determine quadrant and draw numeral lines there
dig = [(10^(i - 1), m) for (i, m) in enumerate(digits(n))]
for (d, m) in dig
y, dx, dy = (d == 1) ? (voffset, thirdcolspan, thirdcolspan) :
(d == 10) ? (voffset, -thirdcolspan, thirdcolspan) :
(d == 100) ? (hlen - voffset, thirdcolspan, -thirdcolspan) :
(hlen - voffset, -thirdcolspan, -thirdcolspan)
m == 1 && drawcnum(ctx, [[x, y], [x + dx, y]])
m == 2 && drawcnum(ctx, [[x, y + dy], [x + dx, y + dy]])
m == 3 && drawcnum(ctx, [[x, y], [x + dx, y + dy]])
m == 4 && drawcnum(ctx, [[x, y + dy], [x + dx, y]])
m == 5 && drawcnum(ctx, [[x, y + dy], [x + dx, y], [x, y]])
m == 6 && drawcnum(ctx, [[x + dx, y], [x + dx, y + dy]])
m == 7 && drawcnum(ctx, [[x, y], [x + dx, y], [x + dx, y + dy]])
m == 8 && drawcnum(ctx, [[x, y + dy], [x + dx, y + dy], [x + dx, y]])
m == 9 && drawcnum(ctx, [[x, y], [x + dx, y], [x + dx, y + dy], [x, y + dy]])
end
move_to(ctx, x - halfwspan ÷ 6, hlen - 4)
Cairo.show_text(ctx, string(n))
stroke(ctx)
end
end
function mooncipher()
draw(can)
cond = Condition()
endit(w) = notify(cond)
signal_connect(endit, win, :destroy)
show(can)
wait(cond)
end
mooncipher()
|
http://rosettacode.org/wiki/Cistercian_numerals | Cistercian numerals | Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999.
How they work
All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyphs representing the digits 1 through 9 are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:
The upper-right quadrant represents the ones place.
The upper-left quadrant represents the tens place.
The lower-right quadrant represents the hundreds place.
The lower-left quadrant represents the thousands place.
Please consult the following image for examples of Cistercian numerals showing each glyph: [1]
Task
Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).
Use the routine to show the following Cistercian numerals:
0
1
20
300
4000
5555
6789
And a number of your choice!
Notes
Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed — especially for text output.
See also
Numberphile - The Forgotten Number System
dcode.fr - Online Cistercian numeral converter
| #Kotlin | Kotlin | import java.io.StringWriter
class Cistercian() {
constructor(number: Int) : this() {
draw(number)
}
private val size = 15
private var canvas = Array(size) { Array(size) { ' ' } }
init {
initN()
}
private fun initN() {
for (row in canvas) {
row.fill(' ')
row[5] = 'x'
}
}
private fun horizontal(c1: Int, c2: Int, r: Int) {
for (c in c1..c2) {
canvas[r][c] = 'x'
}
}
private fun vertical(r1: Int, r2: Int, c: Int) {
for (r in r1..r2) {
canvas[r][c] = 'x'
}
}
private fun diagd(c1: Int, c2: Int, r: Int) {
for (c in c1..c2) {
canvas[r + c - c1][c] = 'x'
}
}
private fun diagu(c1: Int, c2: Int, r: Int) {
for (c in c1..c2) {
canvas[r - c + c1][c] = 'x'
}
}
private fun drawPart(v: Int) {
when (v) {
1 -> {
horizontal(6, 10, 0)
}
2 -> {
horizontal(6, 10, 4)
}
3 -> {
diagd(6, 10, 0)
}
4 -> {
diagu(6, 10, 4)
}
5 -> {
drawPart(1)
drawPart(4)
}
6 -> {
vertical(0, 4, 10)
}
7 -> {
drawPart(1)
drawPart(6)
}
8 -> {
drawPart(2)
drawPart(6)
}
9 -> {
drawPart(1)
drawPart(8)
}
10 -> {
horizontal(0, 4, 0)
}
20 -> {
horizontal(0, 4, 4)
}
30 -> {
diagu(0, 4, 4)
}
40 -> {
diagd(0, 4, 0)
}
50 -> {
drawPart(10)
drawPart(40)
}
60 -> {
vertical(0, 4, 0)
}
70 -> {
drawPart(10)
drawPart(60)
}
80 -> {
drawPart(20)
drawPart(60)
}
90 -> {
drawPart(10)
drawPart(80)
}
100 -> {
horizontal(6, 10, 14)
}
200 -> {
horizontal(6, 10, 10)
}
300 -> {
diagu(6, 10, 14)
}
400 -> {
diagd(6, 10, 10)
}
500 -> {
drawPart(100)
drawPart(400)
}
600 -> {
vertical(10, 14, 10)
}
700 -> {
drawPart(100)
drawPart(600)
}
800 -> {
drawPart(200)
drawPart(600)
}
900 -> {
drawPart(100)
drawPart(800)
}
1000 -> {
horizontal(0, 4, 14)
}
2000 -> {
horizontal(0, 4, 10)
}
3000 -> {
diagd(0, 4, 10)
}
4000 -> {
diagu(0, 4, 14)
}
5000 -> {
drawPart(1000)
drawPart(4000)
}
6000 -> {
vertical(10, 14, 0)
}
7000 -> {
drawPart(1000)
drawPart(6000)
}
8000 -> {
drawPart(2000)
drawPart(6000)
}
9000 -> {
drawPart(1000)
drawPart(8000)
}
}
}
private fun draw(v: Int) {
var v2 = v
val thousands = v2 / 1000
v2 %= 1000
val hundreds = v2 / 100
v2 %= 100
val tens = v2 / 10
val ones = v % 10
if (thousands > 0) {
drawPart(1000 * thousands)
}
if (hundreds > 0) {
drawPart(100 * hundreds)
}
if (tens > 0) {
drawPart(10 * tens)
}
if (ones > 0) {
drawPart(ones)
}
}
override fun toString(): String {
val sw = StringWriter()
for (row in canvas) {
for (cell in row) {
sw.append(cell)
}
sw.appendLine()
}
return sw.toString()
}
}
fun main() {
for (number in arrayOf(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {
println("$number:")
val c = Cistercian(number)
println(c)
}
} |
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)
| #D | D | import std.stdio, std.typecons, std.math, std.algorithm,
std.random, std.traits, std.range, std.complex;
auto bruteForceClosestPair(T)(in T[] points) pure nothrow @nogc {
// return pairwise(points.length.iota, points.length.iota)
// .reduce!(min!((i, j) => abs(points[i] - points[j])));
auto minD = Unqual!(typeof(T.re)).infinity;
T minI, minJ;
foreach (immutable i, const p1; points.dropBackOne)
foreach (const p2; points[i + 1 .. $]) {
immutable dist = abs(p1 - p2);
if (dist < minD) {
minD = dist;
minI = p1;
minJ = p2;
}
}
return tuple(minD, minI, minJ);
}
auto closestPair(T)(T[] points) pure nothrow {
static Tuple!(typeof(T.re), T, T) inner(in T[] xP, /*in*/ T[] yP)
pure nothrow {
if (xP.length <= 3)
return xP.bruteForceClosestPair;
const Pl = xP[0 .. $ / 2];
const Pr = xP[$ / 2 .. $];
immutable xDiv = Pl.back.re;
auto Yr = yP.partition!(p => p.re <= xDiv);
immutable dl_pairl = inner(Pl, yP[0 .. yP.length - Yr.length]);
immutable dr_pairr = inner(Pr, Yr);
immutable dm_pairm = dl_pairl[0]<dr_pairr[0] ? dl_pairl : dr_pairr;
immutable dm = dm_pairm[0];
const nextY = yP.filter!(p => abs(p.re - xDiv) < dm).array;
if (nextY.length > 1) {
auto minD = typeof(T.re).infinity;
size_t minI, minJ;
foreach (immutable i; 0 .. nextY.length - 1)
foreach (immutable j; i + 1 .. min(i + 8, nextY.length)) {
immutable double dist = abs(nextY[i] - nextY[j]);
if (dist < minD) {
minD = dist;
minI = i;
minJ = j;
}
}
return dm <= minD ? dm_pairm :
typeof(return)(minD, nextY[minI], nextY[minJ]);
} else
return dm_pairm;
}
points.sort!q{ a.re < b.re };
const xP = points.dup;
points.sort!q{ a.im < b.im };
return inner(xP, points);
}
void main() {
alias C = complex;
auto pts = [C(5,9), C(9,3), C(2), C(8,4), C(7,4), C(9,10), C(1,9),
C(8,2), C(0,10), C(9,6)];
pts.writeln;
writeln("bruteForceClosestPair: ", pts.bruteForceClosestPair);
writeln(" closestPair: ", pts.closestPair);
rndGen.seed = 1;
Complex!double[10_000] points;
foreach (ref p; points)
p = C(uniform(0.0, 1000.0) + uniform(0.0, 1000.0));
writeln("bruteForceClosestPair: ", points.bruteForceClosestPair);
writeln(" closestPair: ", points.closestPair);
} |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
Goal
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: Multiple distinct objects
| #JavaScript | JavaScript | var funcs = [];
for (var i = 0; i < 10; i++) {
funcs.push( (function(i) {
return function() { return i * i; }
})(i) );
}
window.alert(funcs[3]()); // alerts "9" |
http://rosettacode.org/wiki/Circular_primes | Circular primes | Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not.
A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1.
For example:
R(2) = 11 and R(5) = 11111 are repunits.
Task
Find the first 19 circular primes.
If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes.
(Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can.
See also
Wikipedia article - Circular primes.
Wikipedia article - Repunit.
OEIS sequence A016114 - Circular primes.
| #Pascal | Pascal |
program CircularPrimes;
//nearly the way it is done:
//http://www.worldofnumbers.com/circular.htm
//base 4 counter to create numbers with first digit is the samallest used.
//check if numbers are tested before and reduce gmp-calls by checking with prime 3,7
{$IFDEF FPC}
{$MODE DELPHI}{$OPTIMIZATION ON,ALL}
uses
Sysutils,gmp;
{$ENDIF}
{$IFDEF Delphi}
uses
System.Sysutils,?gmp?;
{$ENDIF}
{$IFDEF WINDOWS}
{$APPTYPE CONSOLE}
{$ENDIF}
const
MAXCNTOFDIGITS = 14;
MAXDGTVAL = 3;
conv : array[0..MAXDGTVAL+1] of byte = (9,7,3,1,0);
type
tDigits = array[0..23] of byte;
tUint64 = NativeUint;
var
mpz : mpz_t;
digits,
revDigits : tDigits;
CheckNum : array[0..19] of tUint64;
Found : array[0..23] of tUint64;
Pot_ten,Count,CountNumCyc,CountNumPrmTst : tUint64;
procedure CheckOne(MaxIdx:integer);
var
Num : Uint64;
i : integer;
begin
i:= MaxIdx;
repeat
inc(CountNumPrmTst);
num := CheckNum[i];
mpz_set_ui(mpz,Num);
If mpz_probab_prime_p(mpz,3)=0then
EXIT;
dec(i);
until i < 0;
Found[Count] := CheckNum[0];
inc(count);
end;
function CycleNum(MaxIdx:integer):Boolean;
//first create circular numbers to minimize prime checks
var
cycNum,First,P10 : tUint64;
i,j,cv : integer;
Begin
i:= MaxIdx;
j := 0;
First := 0;
repeat
cv := conv[digits[i]];
dec(i);
First := First*10+cv;
revDigits[j]:= cv;
inc(j);
until i < 0;
// if num is divisible by 3 then cycle numbers also divisible by 3 same sum of digits
IF First MOD 3 = 0 then
EXIT(false);
If First mod 7 = 0 then
EXIT(false);
//if one of the cycled number must have been tested before break
P10 := Pot_ten;
i := 0;
j := 0;
CheckNum[j] := First;
cycNum := First;
repeat
inc(CountNumCyc);
cv := revDigits[i];
inc(j);
cycNum := (cycNum - cv*P10)*10+cv;
//num was checked before
if cycNum < First then
EXIT(false);
if cycNum mod 7 = 0 then
EXIT(false);
CheckNum[j] := cycNum;
inc(i);
until i >= MaxIdx;
EXIT(true);
end;
var
T0: Int64;
idx,MaxIDx,dgt,MinDgt : NativeInt;
begin
T0 := GetTickCount64;
mpz_init(mpz);
fillchar(digits,Sizeof(digits),chr(MAXDGTVAL));
Count :=0;
For maxIdx := 2 to 10 do
if maxidx in[2,3,5,7] then
begin
Found[Count]:= maxIdx;
inc(count);
end;
Pot_ten := 10;
maxIdx := 1;
idx := 0;
MinDgt := MAXDGTVAL;
repeat
if CycleNum(MaxIdx) then
CheckOne(MaxIdx);
idx := 0;
repeat
dgt := digits[idx]-1;
if dgt >=0 then
break;
digits[idx] := MinDgt;
inc(idx);
until idx >MAXCNTOFDIGITS-1;
if idx > MAXCNTOFDIGITS-1 then
BREAK;
if idx<=MaxIDX then
begin
digits[idx] := dgt;
//change all to leading digit
if idx=MaxIDX then
Begin
For MinDgt := 0 to idx do
digits[MinDgt]:= dgt;
minDgt := dgt;
end;
end
else
begin
minDgt := MAXDGTVAL;
For maxidx := 0 to idx do
digits[MaxIdx] := MAXDGTVAL;
Maxidx := idx;
Pot_ten := Pot_ten*10;
writeln(idx:7,count:7,CountNumCyc:16,CountNumPrmTst:12,GetTickCount64-T0:8);
end;
until false;
writeln(idx:7,count:7,CountNumCyc:16,CountNumPrmTst:12,GetTickCount64-T0:8);
T0 := GetTickCount64-T0;
For idx := 0 to count-2 do
write(Found[idx],',');
writeln(Found[count-1]);
writeln('It took ',T0,' ms ','to check ',MAXCNTOFDIGITS,' decimals');
mpz_clear(mpz);
{$IFDEF WINDOWS}
readln;
{$ENDIF}
end.
|
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
| #COBOL | COBOL | identification division.
program-id. collections.
data division.
working-storage section.
01 sample-table.
05 sample-record occurs 1 to 3 times depending on the-index.
10 sample-alpha pic x(4).
10 filler pic x value ":".
10 sample-number pic 9(4).
10 filler pic x value space.
77 the-index usage index.
procedure division.
collections-main.
set the-index to 3
move 1234 to sample-number(1)
move "abcd" to sample-alpha(1)
move "test" to sample-alpha(2)
move 6789 to sample-number(3)
move "wxyz" to sample-alpha(3)
display "sample-table : " sample-table
display "sample-number(1): " sample-number(1)
display "sample-record(2): " sample-record(2)
display "sample-number(3): " sample-number(3)
*> abend: out of bounds subscript, -debug turns on bounds check
set the-index down by 1
display "sample-table : " sample-table
display "sample-number(3): " sample-number(3)
goback.
end program collections. |
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
| #Java | Java | import java.util.Collections;
import java.util.LinkedList;
public class Comb{
public static void main(String[] args){
System.out.println(comb(3,5));
}
public static String bitprint(int u){
String s= "";
for(int n= 0;u > 0;++n, u>>= 1)
if((u & 1) > 0) s+= n + " ";
return s;
}
public static int bitcount(int u){
int n;
for(n= 0;u > 0;++n, u&= (u - 1));//Turn the last set bit to a 0
return n;
}
public static LinkedList<String> comb(int c, int n){
LinkedList<String> s= new LinkedList<String>();
for(int u= 0;u < 1 << n;u++)
if(bitcount(u) == c) s.push(bitprint(u));
Collections.sort(s);
return s;
}
} |
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.
| #PicoLisp | PicoLisp | (if (condition) # If the condition evaluates to non-NIL
(then-do-this) # Then execute the following expression
(else-do-that) # Else execute all other expressions
(and-more) )
(ifn (condition) # If the condition evaluates to NIL
(then-do-this) # Then execute the following expression
(else-do-that) # Else execute all other expressions
(and-more) ) |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Vlang | Vlang | // This is a single line comment.
/*
This is a multiline comment.
/* It can be nested. */
*/
|
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Vorpal | Vorpal | # single line comment |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Wart | Wart | # single-line comment |
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers | Chernick's Carmichael numbers | In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1:
U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1)
is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4).
Example
U(3, m) = (6m + 1) * (12m + 1) * (18m + 1)
U(4, m) = U(3, m) * (2^2 * 9m + 1)
U(5, m) = U(4, m) * (2^3 * 9m + 1)
...
U(n, m) = U(n-1, m) * (2^(n-2) * 9m + 1)
The smallest Chernick's Carmichael number with 3 prime factors, is: U(3, 1) = 1729.
The smallest Chernick's Carmichael number with 4 prime factors, is: U(4, 1) = 63973.
The smallest Chernick's Carmichael number with 5 prime factors, is: U(5, 380) = 26641259752490421121.
For n = 5, the smallest number m that satisfy Chernick's conditions, is m = 380, therefore U(5, 380) is the smallest Chernick's Carmichael number with 5 prime factors.
U(5, 380) is a Chernick's Carmichael number because m = 380 is a multiple of 2^(n-4), where n = 5, and the factors { (6*380 + 1), (12*380 + 1), (18*380 + 1), (36*380 + 1), (72*380 + 1) } are all prime numbers.
Task
For n ≥ 3, let a(n) be the smallest Chernick's Carmichael number with n prime factors.
Compute a(n) for n = 3..9.
Optional: find a(10).
Note: it's perfectly acceptable to show the terms in factorized form:
a(3) = 7 * 13 * 19
a(4) = 7 * 13 * 19 * 37
a(5) = 2281 * 4561 * 6841 * 13681 * 27361
...
See also
Jack Chernick, On Fermat's simple theorem (PDF)
OEIS A318646: The least Chernick's "universal form" Carmichael number with n prime factors
Related tasks
Carmichael 3 strong pseudoprimes
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
typedef unsigned long long int u64;
#define TRUE 1
#define FALSE 0
int primality_pretest(u64 k) {
if (!(k % 3) || !(k % 5) || !(k % 7) || !(k % 11) || !(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)) return (k <= 23);
return TRUE;
}
int probprime(u64 k, mpz_t n) {
mpz_set_ui(n, k);
return mpz_probab_prime_p(n, 0);
}
int is_chernick(int n, u64 m, mpz_t z) {
u64 t = 9 * m;
if (primality_pretest(6 * m + 1) == FALSE) return FALSE;
if (primality_pretest(12 * m + 1) == FALSE) return FALSE;
for (int i = 1; i <= n - 2; i++) if (primality_pretest((t << i) + 1) == FALSE) return FALSE;
if (probprime(6 * m + 1, z) == FALSE) return FALSE;
if (probprime(12 * m + 1, z) == FALSE) return FALSE;
for (int i = 1; i <= n - 2; i++) if (probprime((t << i) + 1, z) == FALSE) return FALSE;
return TRUE;
}
int main(int argc, char const *argv[]) {
mpz_t z;
mpz_inits(z, NULL);
for (int n = 3; n <= 10; n ++) {
u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1;
if (n > 5) multiplier *= 5;
for (u64 k = 1; ; k++) {
u64 m = k * multiplier;
if (is_chernick(n, m, z) == TRUE) {
printf("a(%d) has m = %llu\n", n, m);
break;
}
}
}
return 0;
} |
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The sequence is named after Sarvadaman D. S. Chowla, (22 October 1907 ──► 10 December 1995),
a London born Indian American mathematician specializing in number theory.
German mathematician Carl Friedrich Gauss (1777─1855) said:
"Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics".
Definitions
Chowla numbers can also be expressed as:
chowla(n) = sum of divisors of n excluding unity and n
chowla(n) = sum( divisors(n)) - 1 - n
chowla(n) = sum( properDivisors(n)) - 1
chowla(n) = sum(aliquotDivisors(n)) - 1
chowla(n) = aliquot(n) - 1
chowla(n) = sigma(n) - 1 - n
chowla(n) = sigmaProperDivisiors(n) - 1
chowla(a*b) = a + b, if a and b are distinct primes
if chowla(n) = 0, and n > 1, then n is prime
if chowla(n) = n - 1, and n > 1, then n is a perfect number
Task
create a chowla function that returns the chowla number for a positive integer n
Find and display (1 per line) for the 1st 37 integers:
the integer (the index)
the chowla number for that integer
For finding primes, use the chowla function to find values of zero
Find and display the count of the primes up to 100
Find and display the count of the primes up to 1,000
Find and display the count of the primes up to 10,000
Find and display the count of the primes up to 100,000
Find and display the count of the primes up to 1,000,000
Find and display the count of the primes up to 10,000,000
For finding perfect numbers, use the chowla function to find values of n - 1
Find and display all perfect numbers up to 35,000,000
use commas within appropriate numbers
show all output here
Related tasks
totient function
perfect numbers
Proper divisors
Sieve of Eratosthenes
See also
the OEIS entry for A48050 Chowla's function.
| #ALGOL_68 | ALGOL 68 | BEGIN # find some Chowla numbers ( Chowla n = sum of divisors of n exclusing n and 1 ) #
# returs the Chowla number of n #
PROC chowla = ( INT n )INT:
BEGIN
INT sum := 0;
FOR i FROM 2 WHILE i * i <= n DO
IF n MOD i = 0 THEN
INT j = n OVER i;
sum +:= i + IF i = j THEN 0 ELSE j FI
FI
OD;
sum
END # chowla # ;
FOR n TO 37 DO print( ( "chowla(", whole( n, 0 ), ") = ", whole( chowla( n ), 0 ), newline ) ) OD;
INT count := 0, power := 100;
FOR n FROM 2 TO 10 000 000 DO
IF chowla( n ) = 0 THEN count +:= 1 FI;
IF n MOD power = 0 THEN
print( ( "There are ", whole( count, 0 ), " primes < ", whole( power, 0 ), newline ) );
power *:= 10
FI
OD;
count := 0;
INT limit = 350 000 000;
INT k := 2, kk := 3;
WHILE INT p = k * kk;
p <= limit
DO
IF chowla( p ) = p - 1 THEN
print( ( whole( p, 0 ), " is a perfect number", newline ) );
count +:= 1
FI;
k := kk + 1; kk +:= k
OD;
print( ( "There are ", whole( count, 0 ), " perfect numbers < ", whole( limit, 0 ), newline ) )
END |
http://rosettacode.org/wiki/Church_numerals | Church numerals | Task
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
Church one applies its first argument f just once to its second argument x, yielding f(x)
Church two applies its first argument f twice to its second argument x, yielding f(f(x))
and each successive Church numeral applies its first argument one additional time to its second argument, f(f(f(x))), f(f(f(f(x)))) ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument.
Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals.
In your language define:
Church Zero,
a Church successor function (a function on a Church numeral which returns the next Church numeral in the series),
functions for Addition, Multiplication and Exponentiation over Church numerals,
a function to convert integers to corresponding Church numerals,
and a function to convert Church numerals to corresponding integers.
You should:
Derive Church numerals three and four in terms of Church zero and a Church successor function.
use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4,
similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function,
convert each result back to an integer, and return it or print it to the console.
| #F.23 | F# | type IChurch =
abstract Apply : ('a -> 'a) -> ('a -> 'a)
let zeroChurch = { new IChurch with override __.Apply _ = id }
let oneChurch = { new IChurch with override __.Apply f = f }
let succChurch (n: IChurch) =
{ new IChurch with override __.Apply f = fun x -> f (n.Apply f x) }
let addChurch (m: IChurch) (n: IChurch) =
{ new IChurch with override __.Apply f = fun x -> m.Apply f (n.Apply f x) }
let multChurch (m: IChurch) (n: IChurch) =
{ new IChurch with override __.Apply f = m.Apply (n.Apply f) }
let expChurch (m: IChurch) (n: IChurch) =
{ new IChurch with override __.Apply f = n.Apply m.Apply f }
let iszeroChurch (n: IChurch) =
{ new IChurch with
override __.Apply f = n.Apply (fun _ -> zeroChurch.Apply) oneChurch.Apply f }
let predChurch (n: IChurch) =
{ new IChurch with
override __.Apply f = fun x -> n.Apply (fun g h -> h (g f))
(fun _ -> x) id }
let subChurch (m: IChurch) (n: IChurch) =
{ new IChurch with override __.Apply f = (n.Apply predChurch m).Apply f }
let divChurch (dvdnd: IChurch) (dvsr: IChurch) =
let rec divr (n: IChurch) (d: IChurch) =
{ new IChurch with
override __.Apply f =
((fun (v: IChurch) -> // test v for Church zeroChurch...
v.Apply (fun _ -> (succChurch (divr v d)).Apply) // if not zeroChurch
zeroChurch.Apply)(subChurch n d)) f }
divr (succChurch dvdnd) dvsr
let chtoi (ch: IChurch) = ch.Apply ((+) 1) 0
let itoch i = List.fold (>>) id (List.replicate i succChurch) zeroChurch
#nowarn "25" // skip incomplete pattern warning
[<EntryPoint>]
let main _ =
let [c3; c4; c11; c12] = List.map itoch [3; 4; 11; 12]
[ addChurch c3 c4
; multChurch c3 c4
; expChurch c3 c4
; expChurch c4 c3
; iszeroChurch zeroChurch
; iszeroChurch oneChurch
; predChurch c3
; subChurch c11 c3
; divChurch c11 c3
; divChurch c12 c3
] |> List.map chtoi |> printfn "%A"
0 // return an integer exit code |
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.
| #Coco | Coco | class Rectangle
# The constructor is defined as a bare function. This
# constructor accepts one argument and automatically assigns it
# to an instance variable.
(@width) ->
# Another instance variable.
length: 10
# A method.
area: ->
@width * @length
# Instantiate the class using the 'new' operator.
rect = new Rectangle 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.
| #CoffeeScript | CoffeeScript | # Create a basic class
class Rectangle
# Constructor that accepts one argument
constructor: (@width) ->
# An instance variable
length: 10
# A method
area: () ->
@width * @length
# Instantiate the class using the new operator
rect = new Rectangle 2 |
http://rosettacode.org/wiki/Cistercian_numerals | Cistercian numerals | Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999.
How they work
All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyphs representing the digits 1 through 9 are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:
The upper-right quadrant represents the ones place.
The upper-left quadrant represents the tens place.
The lower-right quadrant represents the hundreds place.
The lower-left quadrant represents the thousands place.
Please consult the following image for examples of Cistercian numerals showing each glyph: [1]
Task
Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).
Use the routine to show the following Cistercian numerals:
0
1
20
300
4000
5555
6789
And a number of your choice!
Notes
Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed — especially for text output.
See also
Numberphile - The Forgotten Number System
dcode.fr - Online Cistercian numeral converter
| #Lua | Lua | function initN()
local n = {}
for i=1,15 do
n[i] = {}
for j=1,11 do
n[i][j] = " "
end
n[i][6] = "x"
end
return n
end
function horiz(n, c1, c2, r)
for c=c1,c2 do
n[r+1][c+1] = "x"
end
end
function verti(n, r1, r2, c)
for r=r1,r2 do
n[r+1][c+1] = "x"
end
end
function diagd(n, c1, c2, r)
for c=c1,c2 do
n[r+c-c1+1][c+1] = "x"
end
end
function diagu(n, c1, c2, r)
for c=c1,c2 do
n[r-c+c1+1][c+1] = "x"
end
end
function initDraw()
local draw = {}
draw[1] = function(n) horiz(n, 6, 10, 0) end
draw[2] = function(n) horiz(n, 6, 10, 4) end
draw[3] = function(n) diagd(n, 6, 10, 0) end
draw[4] = function(n) diagu(n, 6, 10, 4) end
draw[5] = function(n) draw[1](n) draw[4](n) end
draw[6] = function(n) verti(n, 0, 4, 10) end
draw[7] = function(n) draw[1](n) draw[6](n) end
draw[8] = function(n) draw[2](n) draw[6](n) end
draw[9] = function(n) draw[1](n) draw[8](n) end
draw[10] = function(n) horiz(n, 0, 4, 0) end
draw[20] = function(n) horiz(n, 0, 4, 4) end
draw[30] = function(n) diagu(n, 0, 4, 4) end
draw[40] = function(n) diagd(n, 0, 4, 0) end
draw[50] = function(n) draw[10](n) draw[40](n) end
draw[60] = function(n) verti(n, 0, 4, 0) end
draw[70] = function(n) draw[10](n) draw[60](n) end
draw[80] = function(n) draw[20](n) draw[60](n) end
draw[90] = function(n) draw[10](n) draw[80](n) end
draw[100] = function(n) horiz(n, 6, 10, 14) end
draw[200] = function(n) horiz(n, 6, 10, 10) end
draw[300] = function(n) diagu(n, 6, 10, 14) end
draw[400] = function(n) diagd(n, 6, 10, 10) end
draw[500] = function(n) draw[100](n) draw[400](n) end
draw[600] = function(n) verti(n, 10, 14, 10) end
draw[700] = function(n) draw[100](n) draw[600](n) end
draw[800] = function(n) draw[200](n) draw[600](n) end
draw[900] = function(n) draw[100](n) draw[800](n) end
draw[1000] = function(n) horiz(n, 0, 4, 14) end
draw[2000] = function(n) horiz(n, 0, 4, 10) end
draw[3000] = function(n) diagd(n, 0, 4, 10) end
draw[4000] = function(n) diagu(n, 0, 4, 14) end
draw[5000] = function(n) draw[1000](n) draw[4000](n) end
draw[6000] = function(n) verti(n, 10, 14, 0) end
draw[7000] = function(n) draw[1000](n) draw[6000](n) end
draw[8000] = function(n) draw[2000](n) draw[6000](n) end
draw[9000] = function(n) draw[1000](n) draw[8000](n) end
return draw
end
function printNumeral(n)
for i,v in pairs(n) do
for j,w in pairs(v) do
io.write(w .. " ")
end
print()
end
print()
end
function main()
local draw = initDraw()
for i,number in pairs({0, 1, 20, 300, 4000, 5555, 6789, 9999}) do
local n = initN()
print(number..":")
local thousands = math.floor(number / 1000)
number = number % 1000
local hundreds = math.floor(number / 100)
number = number % 100
local tens = math.floor(number / 10)
local ones = number % 10
if thousands > 0 then
draw[thousands * 1000](n)
end
if hundreds > 0 then
draw[hundreds * 100](n)
end
if tens > 0 then
draw[tens * 10](n)
end
if ones > 0 then
draw[ones](n)
end
printNumeral(n)
end
end
main() |
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)
| #Delphi | Delphi | defmodule Closest_pair do
# brute-force algorithm:
def bruteForce([p0,p1|_] = points), do: bf_loop(points, {distance(p0, p1), {p0, p1}})
defp bf_loop([_], acc), do: acc
defp bf_loop([h|t], acc), do: bf_loop(t, bf_loop(h, t, acc))
defp bf_loop(_, [], acc), do: acc
defp bf_loop(p0, [p1|t], {minD, minP}) do
dist = distance(p0, p1)
if dist < minD, do: bf_loop(p0, t, {dist, {p0, p1}}),
else: bf_loop(p0, t, {minD, minP})
end
defp distance({p0x,p0y}, {p1x,p1y}) do
:math.sqrt( (p1x - p0x) * (p1x - p0x) + (p1y - p0y) * (p1y - p0y) )
end
# recursive divide&conquer approach:
def recursive(points) do
recursive(Enum.sort(points), Enum.sort_by(points, fn {_x,y} -> y end))
end
def recursive(xP, _yP) when length(xP) <= 3, do: bruteForce(xP)
def recursive(xP, yP) do
{xL, xR} = Enum.split(xP, div(length(xP), 2))
{xm, _} = hd(xR)
{yL, yR} = Enum.partition(yP, fn {x,_} -> x < xm end)
{dL, pairL} = recursive(xL, yL)
{dR, pairR} = recursive(xR, yR)
{dmin, pairMin} = if dL<dR, do: {dL, pairL}, else: {dR, pairR}
yS = Enum.filter(yP, fn {x,_} -> abs(xm - x) < dmin end)
merge(yS, {dmin, pairMin})
end
defp merge([_], acc), do: acc
defp merge([h|t], acc), do: merge(t, merge_loop(h, t, acc))
defp merge_loop(_, [], acc), do: acc
defp merge_loop(p0, [p1|_], {dmin,_}=acc) when dmin <= elem(p1,1) - elem(p0,1), do: acc
defp merge_loop(p0, [p1|t], {dmin, pair}) do
dist = distance(p0, p1)
if dist < dmin, do: merge_loop(p0, t, {dist, {p0, p1}}),
else: merge_loop(p0, t, {dmin, pair})
end
end
data = [{0.654682, 0.925557}, {0.409382, 0.619391}, {0.891663, 0.888594}, {0.716629, 0.996200},
{0.477721, 0.946355}, {0.925092, 0.818220}, {0.624291, 0.142924}, {0.211332, 0.221507},
{0.293786, 0.691701}, {0.839186, 0.728260}]
IO.inspect Closest_pair.bruteForce(data)
IO.inspect Closest_pair.recursive(data)
data2 = for _ <- 1..5000, do: {:rand.uniform, :rand.uniform}
IO.puts "\nBrute-force:"
IO.inspect :timer.tc(fn -> Closest_pair.bruteForce(data2) end)
IO.puts "Recursive divide&conquer:"
IO.inspect :timer.tc(fn -> Closest_pair.recursive(data2) end) |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
Goal
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: Multiple distinct objects
| #Julia | Julia | funcs = [ () -> i^2 for i = 1:10 ] |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
Goal
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: Multiple distinct objects
| #Kotlin | Kotlin | // version 1.0.6
fun main(args: Array<String>) {
// create an array of 10 anonymous functions which return the square of their index
val funcs = Array(10){ fun(): Int = it * it }
// call all but the last
(0 .. 8).forEach { println(funcs[it]()) }
} |
http://rosettacode.org/wiki/Circular_primes | Circular primes | Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not.
A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1.
For example:
R(2) = 11 and R(5) = 11111 are repunits.
Task
Find the first 19 circular primes.
If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes.
(Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can.
See also
Wikipedia article - Circular primes.
Wikipedia article - Repunit.
OEIS sequence A016114 - Circular primes.
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
use List::Util 'min';
use ntheory 'is_prime';
sub rotate { my($i,@a) = @_; join '', @a[$i .. @a-1, 0 .. $i-1] }
sub isCircular {
my ($n) = @_;
return 0 unless is_prime($n);
my @circular = split //, $n;
return 0 if min(@circular) < $circular[0];
for (1 .. scalar @circular) {
my $r = join '', rotate($_,@circular);
return 0 unless is_prime($r) and $r >= $n;
}
1
}
say "The first 19 circular primes are:";
for ( my $i = 1, my $count = 0; $count < 19; $i++ ) {
++$count and print "$i " if isCircular($i);
}
say "\n\nThe next 4 circular primes, in repunit format, are:";
for ( my $i = 7, my $count = 0; $count < 4; $i++ ) {
++$count and say "R($i)" if is_prime 1 x $i
}
say "\nRepunit testing:";
for (5003, 9887, 15073, 25031, 35317, 49081) {
say "R($_): Prime? " . (is_prime 1 x $_ ? 'True' : 'False');
} |
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
| #Common_Lisp | Common Lisp | CL-USER> (let ((list '())
(hash-table (make-hash-table)))
(push 1 list)
(push 2 list)
(push 3 list)
(format t "~S~%" (reverse list))
(setf (gethash 'foo hash-table) 42)
(setf (gethash 'bar hash-table) 69)
(maphash (lambda (key value)
(format t "~S => ~S~%" key value))
hash-table)
;; or print the hash-table in readable form
;; (inplementation-dependent)
(write hash-table :readably t)
;; or describe it
(describe hash-table)
;; describe the list as well
(describe list))
;; FORMAT on a list
(1 2 3)
;; FORMAT on a hash-table
FOO => 42
BAR => 69
;; WRITE :readably t on a hash-table
#.(SB-IMPL::%STUFF-HASH-TABLE
(MAKE-HASH-TABLE :TEST 'EQL :SIZE '16 :REHASH-SIZE '1.5
:REHASH-THRESHOLD '1.0 :WEAKNESS 'NIL)
'((BAR . 69) (FOO . 42)))
;; DESCRIBE on a hash-table
#<HASH-TABLE :TEST EQL :COUNT 2 {1002B6F391}>
[hash-table]
Occupancy: 0.1
Rehash-threshold: 1.0
Rehash-size: 1.5
Size: 16
Synchronized: no
;; DESCRIBE on a list
(3 2 1)
[list]
; No value |
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
| #JavaScript | JavaScript | function bitprint(u) {
var s="";
for (var n=0; u; ++n, u>>=1)
if (u&1) s+=n+" ";
return s;
}
function bitcount(u) {
for (var n=0; u; ++n, u=u&(u-1));
return n;
}
function comb(c,n) {
var s=[];
for (var u=0; u<1<<n; u++)
if (bitcount(u)==c)
s.push(bitprint(u))
return s.sort();
}
comb(3,5) |
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.
| #PL.2FI | PL/I | if condition_exp then unique_statement; else unique_statement;
if condition_exp then
unique_statement;
else
unique_statement;
if condition_exp
then do;
list_of_statements;
end;
else do;
list_of_statements;
end; |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Wren | Wren | // This is a line comment.
/* This is a single line block comment.*/
/* This is
a multi-line
block comment.*/
/* This is/* a nested */block comment.*/ |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #X10 | X10 | // This is a single line comment
/*
This comment spans
multiple lines
*/ |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #XLISP | XLISP | ; this is a comment |
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers | Chernick's Carmichael numbers | In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1:
U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1)
is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4).
Example
U(3, m) = (6m + 1) * (12m + 1) * (18m + 1)
U(4, m) = U(3, m) * (2^2 * 9m + 1)
U(5, m) = U(4, m) * (2^3 * 9m + 1)
...
U(n, m) = U(n-1, m) * (2^(n-2) * 9m + 1)
The smallest Chernick's Carmichael number with 3 prime factors, is: U(3, 1) = 1729.
The smallest Chernick's Carmichael number with 4 prime factors, is: U(4, 1) = 63973.
The smallest Chernick's Carmichael number with 5 prime factors, is: U(5, 380) = 26641259752490421121.
For n = 5, the smallest number m that satisfy Chernick's conditions, is m = 380, therefore U(5, 380) is the smallest Chernick's Carmichael number with 5 prime factors.
U(5, 380) is a Chernick's Carmichael number because m = 380 is a multiple of 2^(n-4), where n = 5, and the factors { (6*380 + 1), (12*380 + 1), (18*380 + 1), (36*380 + 1), (72*380 + 1) } are all prime numbers.
Task
For n ≥ 3, let a(n) be the smallest Chernick's Carmichael number with n prime factors.
Compute a(n) for n = 3..9.
Optional: find a(10).
Note: it's perfectly acceptable to show the terms in factorized form:
a(3) = 7 * 13 * 19
a(4) = 7 * 13 * 19 * 37
a(5) = 2281 * 4561 * 6841 * 13681 * 27361
...
See also
Jack Chernick, On Fermat's simple theorem (PDF)
OEIS A318646: The least Chernick's "universal form" Carmichael number with n prime factors
Related tasks
Carmichael 3 strong pseudoprimes
| #C.2B.2B | C++ | #include <gmp.h>
#include <iostream>
using namespace std;
typedef unsigned long long int u64;
bool primality_pretest(u64 k) { // for k > 23
if (!(k % 3) || !(k % 5) || !(k % 7) || !(k % 11) ||
!(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)
) {
return (k <= 23);
}
return true;
}
bool probprime(u64 k, mpz_t n) {
mpz_set_ui(n, k);
return mpz_probab_prime_p(n, 0);
}
bool is_chernick(int n, u64 m, mpz_t z) {
if (!primality_pretest(6 * m + 1)) {
return false;
}
if (!primality_pretest(12 * m + 1)) {
return false;
}
u64 t = 9 * m;
for (int i = 1; i <= n - 2; i++) {
if (!primality_pretest((t << i) + 1)) {
return false;
}
}
if (!probprime(6 * m + 1, z)) {
return false;
}
if (!probprime(12 * m + 1, z)) {
return false;
}
for (int i = 1; i <= n - 2; i++) {
if (!probprime((t << i) + 1, z)) {
return false;
}
}
return true;
}
int main() {
mpz_t z;
mpz_inits(z, NULL);
for (int n = 3; n <= 10; n++) {
// `m` is a multiple of 2^(n-4), for n > 4
u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1;
// For n > 5, m is also a multiple of 5
if (n > 5) {
multiplier *= 5;
}
for (u64 k = 1; ; k++) {
u64 m = k * multiplier;
if (is_chernick(n, m, z)) {
cout << "a(" << n << ") has m = " << m << endl;
break;
}
}
}
return 0;
} |
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The sequence is named after Sarvadaman D. S. Chowla, (22 October 1907 ──► 10 December 1995),
a London born Indian American mathematician specializing in number theory.
German mathematician Carl Friedrich Gauss (1777─1855) said:
"Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics".
Definitions
Chowla numbers can also be expressed as:
chowla(n) = sum of divisors of n excluding unity and n
chowla(n) = sum( divisors(n)) - 1 - n
chowla(n) = sum( properDivisors(n)) - 1
chowla(n) = sum(aliquotDivisors(n)) - 1
chowla(n) = aliquot(n) - 1
chowla(n) = sigma(n) - 1 - n
chowla(n) = sigmaProperDivisiors(n) - 1
chowla(a*b) = a + b, if a and b are distinct primes
if chowla(n) = 0, and n > 1, then n is prime
if chowla(n) = n - 1, and n > 1, then n is a perfect number
Task
create a chowla function that returns the chowla number for a positive integer n
Find and display (1 per line) for the 1st 37 integers:
the integer (the index)
the chowla number for that integer
For finding primes, use the chowla function to find values of zero
Find and display the count of the primes up to 100
Find and display the count of the primes up to 1,000
Find and display the count of the primes up to 10,000
Find and display the count of the primes up to 100,000
Find and display the count of the primes up to 1,000,000
Find and display the count of the primes up to 10,000,000
For finding perfect numbers, use the chowla function to find values of n - 1
Find and display all perfect numbers up to 35,000,000
use commas within appropriate numbers
show all output here
Related tasks
totient function
perfect numbers
Proper divisors
Sieve of Eratosthenes
See also
the OEIS entry for A48050 Chowla's function.
| #Arturo | Arturo | chowla: function [n]-> sum remove remove factors n 1 n
countPrimesUpTo: function [limit][
count: 1
loop 3.. .step: 2 limit 'x [
if zero? chowla x -> count: count + 1
]
return count
]
loop 1..37 'i -> print [i "=>" chowla i]
print ""
loop [100 1000 10000 100000 1000000 10000000] 'lim [
print ["primes up to" lim "=>" countPrimesUpTo lim]
]
print ""
print "perfect numbers up to 35000000:"
i: 2
while [i < 35000000][
if (chowla i) = i - 1 -> print i
i: i + 2
] |
http://rosettacode.org/wiki/Church_numerals | Church numerals | Task
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
Church one applies its first argument f just once to its second argument x, yielding f(x)
Church two applies its first argument f twice to its second argument x, yielding f(f(x))
and each successive Church numeral applies its first argument one additional time to its second argument, f(f(f(x))), f(f(f(f(x)))) ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument.
Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals.
In your language define:
Church Zero,
a Church successor function (a function on a Church numeral which returns the next Church numeral in the series),
functions for Addition, Multiplication and Exponentiation over Church numerals,
a function to convert integers to corresponding Church numerals,
and a function to convert Church numerals to corresponding integers.
You should:
Derive Church numerals three and four in terms of Church zero and a Church successor function.
use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4,
similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function,
convert each result back to an integer, and return it or print it to the console.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import "fmt"
type any = interface{}
type fn func(any) any
type church func(fn) fn
func zero(f fn) fn {
return func(x any) any {
return x
}
}
func (c church) succ() church {
return func(f fn) fn {
return func(x any) any {
return f(c(f)(x))
}
}
}
func (c church) add(d church) church {
return func(f fn) fn {
return func(x any) any {
return c(f)(d(f)(x))
}
}
}
func (c church) mul(d church) church {
return func(f fn) fn {
return func(x any) any {
return c(d(f))(x)
}
}
}
func (c church) pow(d church) church {
di := d.toInt()
prod := c
for i := 1; i < di; i++ {
prod = prod.mul(c)
}
return prod
}
func (c church) toInt() int {
return c(incr)(0).(int)
}
func intToChurch(i int) church {
if i == 0 {
return zero
} else {
return intToChurch(i - 1).succ()
}
}
func incr(i any) any {
return i.(int) + 1
}
func main() {
z := church(zero)
three := z.succ().succ().succ()
four := three.succ()
fmt.Println("three ->", three.toInt())
fmt.Println("four ->", four.toInt())
fmt.Println("three + four ->", three.add(four).toInt())
fmt.Println("three * four ->", three.mul(four).toInt())
fmt.Println("three ^ four ->", three.pow(four).toInt())
fmt.Println("four ^ three ->", four.pow(three).toInt())
fmt.Println("5 -> five ->", intToChurch(5).toInt())
} |
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.
| #Common_Lisp | Common Lisp | (defclass circle ()
((radius :initarg :radius
:initform 1.0
:type number
:reader radius)))
(defmethod area ((shape circle))
(* pi (expt (radius shape) 2)))
> (defvar *c* (make-instance 'circle :radius 2))
> (area *c*)
12.566370614359172d0 |
http://rosettacode.org/wiki/Cistercian_numerals | Cistercian numerals | Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999.
How they work
All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyphs representing the digits 1 through 9 are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:
The upper-right quadrant represents the ones place.
The upper-left quadrant represents the tens place.
The lower-right quadrant represents the hundreds place.
The lower-left quadrant represents the thousands place.
Please consult the following image for examples of Cistercian numerals showing each glyph: [1]
Task
Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).
Use the routine to show the following Cistercian numerals:
0
1
20
300
4000
5555
6789
And a number of your choice!
Notes
Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed — especially for text output.
See also
Numberphile - The Forgotten Number System
dcode.fr - Online Cistercian numeral converter
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[CistercianNumberEncodeHelper, CistercianNumberEncode]
\[Delta] = 0.25;
CistercianNumberEncodeHelper[0] := {}
CistercianNumberEncodeHelper[1] := Line[{{0, 1}, {\[Delta], 1}}]
CistercianNumberEncodeHelper[2] := Line[{{0, 1 - \[Delta]}, {\[Delta], 1 - \[Delta]}}]
CistercianNumberEncodeHelper[3] := Line[{{0, 1}, {\[Delta], 1 - \[Delta]}}]
CistercianNumberEncodeHelper[4] := Line[{{0, 1 - \[Delta]}, {\[Delta], 1}}]
CistercianNumberEncodeHelper[5] := Line[{{0, 1 - \[Delta]}, {\[Delta], 1}, {0, 1}}]
CistercianNumberEncodeHelper[6] := Line[{{\[Delta], 1 - \[Delta]}, {\[Delta], 1}}]
CistercianNumberEncodeHelper[7] := Line[{{\[Delta], 1 - \[Delta]}, {\[Delta], 1}, {0, 1}}]
CistercianNumberEncodeHelper[8] := Line[{{0, 1 - \[Delta]}, {\[Delta], 1 - \[Delta]}, {\[Delta], 1}}]
CistercianNumberEncodeHelper[9] := Line[{{0, 1}, {\[Delta], 1}, {\[Delta], 1 - \[Delta]}, {0, 1 - \[Delta]}}]
CistercianNumberEncode::nnarg = "The argument `1` should be an integer between 0 and 9999 (inclusive).";
CistercianNumberEncode[n_Integer] := Module[{digs},
If[0 <= n <= 9999,
digs = IntegerDigits[n, 10, 4];
Graphics[{Line[{{0, 0}, {0, 1}}],
CistercianNumberEncodeHelper[digs[[4]]],
GeometricTransformation[CistercianNumberEncodeHelper[digs[[3]]],
ReflectionTransform[{1, 0}]],
GeometricTransformation[CistercianNumberEncodeHelper[digs[[2]]],
ReflectionTransform[{0, 1}, {0, 1/2}]],
GeometricTransformation[CistercianNumberEncodeHelper[digs[[1]]],
RotationTransform[Pi, {0, 1/2}]]
},
PlotRange -> {{-1.5 \[Delta], 1.5 \[Delta]}, {0 - 0.5 \[Delta],
1 + 0.5 \[Delta]}},
ImageSize -> 50
]
,
Message[CistercianNumberEncode::nnarg, n]
]
]
CistercianNumberEncode[0]
CistercianNumberEncode[1]
CistercianNumberEncode[20]
CistercianNumberEncode[300]
CistercianNumberEncode[4000]
CistercianNumberEncode[5555]
CistercianNumberEncode[6789]
CistercianNumberEncode[1337] |
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)
| #Elixir | Elixir | defmodule Closest_pair do
# brute-force algorithm:
def bruteForce([p0,p1|_] = points), do: bf_loop(points, {distance(p0, p1), {p0, p1}})
defp bf_loop([_], acc), do: acc
defp bf_loop([h|t], acc), do: bf_loop(t, bf_loop(h, t, acc))
defp bf_loop(_, [], acc), do: acc
defp bf_loop(p0, [p1|t], {minD, minP}) do
dist = distance(p0, p1)
if dist < minD, do: bf_loop(p0, t, {dist, {p0, p1}}),
else: bf_loop(p0, t, {minD, minP})
end
defp distance({p0x,p0y}, {p1x,p1y}) do
:math.sqrt( (p1x - p0x) * (p1x - p0x) + (p1y - p0y) * (p1y - p0y) )
end
# recursive divide&conquer approach:
def recursive(points) do
recursive(Enum.sort(points), Enum.sort_by(points, fn {_x,y} -> y end))
end
def recursive(xP, _yP) when length(xP) <= 3, do: bruteForce(xP)
def recursive(xP, yP) do
{xL, xR} = Enum.split(xP, div(length(xP), 2))
{xm, _} = hd(xR)
{yL, yR} = Enum.partition(yP, fn {x,_} -> x < xm end)
{dL, pairL} = recursive(xL, yL)
{dR, pairR} = recursive(xR, yR)
{dmin, pairMin} = if dL<dR, do: {dL, pairL}, else: {dR, pairR}
yS = Enum.filter(yP, fn {x,_} -> abs(xm - x) < dmin end)
merge(yS, {dmin, pairMin})
end
defp merge([_], acc), do: acc
defp merge([h|t], acc), do: merge(t, merge_loop(h, t, acc))
defp merge_loop(_, [], acc), do: acc
defp merge_loop(p0, [p1|_], {dmin,_}=acc) when dmin <= elem(p1,1) - elem(p0,1), do: acc
defp merge_loop(p0, [p1|t], {dmin, pair}) do
dist = distance(p0, p1)
if dist < dmin, do: merge_loop(p0, t, {dist, {p0, p1}}),
else: merge_loop(p0, t, {dmin, pair})
end
end
data = [{0.654682, 0.925557}, {0.409382, 0.619391}, {0.891663, 0.888594}, {0.716629, 0.996200},
{0.477721, 0.946355}, {0.925092, 0.818220}, {0.624291, 0.142924}, {0.211332, 0.221507},
{0.293786, 0.691701}, {0.839186, 0.728260}]
IO.inspect Closest_pair.bruteForce(data)
IO.inspect Closest_pair.recursive(data)
data2 = for _ <- 1..5000, do: {:rand.uniform, :rand.uniform}
IO.puts "\nBrute-force:"
IO.inspect :timer.tc(fn -> Closest_pair.bruteForce(data2) end)
IO.puts "Recursive divide&conquer:"
IO.inspect :timer.tc(fn -> Closest_pair.recursive(data2) end) |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
Goal
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: Multiple distinct objects
| #Lambdatalk | Lambdatalk |
{def A
{A.new
{S.map {lambda {:x} {* :x :x}}
{S.serie 0 10}
}}}
{A.get 3 {A}} // equivalent to A[3]
-> 9
{A.get 4 {A}}
-> 16
|
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
Goal
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: Multiple distinct objects
| #Latitude | Latitude | functions := 10 times to (Array) map {
takes '[i].
proc { (i) * (i). }.
}.
functions visit { println: $1 call. }. |
http://rosettacode.org/wiki/Circular_primes | Circular primes | Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not.
A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1.
For example:
R(2) = 11 and R(5) = 11111 are repunits.
Task
Find the first 19 circular primes.
If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes.
(Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can.
See also
Wikipedia article - Circular primes.
Wikipedia article - Repunit.
OEIS sequence A016114 - Circular primes.
| #Phix | Phix | with javascript_semantics
function circular(integer p)
integer len = length(sprintf("%d",p)),
pow = power(10,len-1),
p0 = p
for i=1 to len-1 do
p = pow*remainder(p,10)+floor(p/10)
if p<p0 or not is_prime(p) then return false end if
end for
return true
end function
sequence c = {}
integer n = 1
while length(c)<19 do
integer p = get_prime(n)
if circular(p) then c &= p end if
n += 1
end while
printf(1,"The first 19 circular primes are:\n%v\n\n",{c})
include mpfr.e
procedure repunit(mpz z, integer n)
mpz_set_str(z,repeat('1',n))
end procedure
c = {}
n = 7
mpz z = mpz_init()
while length(c)<4 do
repunit(z,n)
if mpz_prime(z) then
c = append(c,sprintf("R(%d)",n))
end if
n += 1
end while
printf(1,"The next 4 circular primes, in repunit format, are:\n%s\n\n",{join(c)})
|
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
| #11l | 11l | T Circle
Float x, y, r
F String()
R ‘Circle(x=#.6, y=#.6, r=#.6)’.format(.x, .y, .r)
F (x, y, r)
.x = x
.y = y
.r = r
T Error
String msg
F (msg)
.msg = msg
F circles_from_p1p2r(p1, p2, r)
‘Following explanation at http://mathforum.org/library/drmath/view/53027.html’
I r == 0.0
X Error(‘radius of zero’)
V (x1, y1) = p1
V (x2, y2) = p2
I p1 == p2
X Error(‘coincident points gives infinite number of Circles’)
V (dx, dy) = (x2 - x1, y2 - y1)
V q = sqrt(dx ^ 2 + dy ^ 2)
I q > 2.0 * r
X Error(‘separation of points > diameter’)
V (x3, y3) = ((x1 + x2) / 2, (y1 + y2) / 2)
V d = sqrt(r ^ 2 - (q / 2) ^ 2)
V c1 = Circle(x' x3 - d * dy / q,
y' y3 + d * dx / q,
r' abs(r))
V c2 = Circle(x' x3 + d * dy / q,
y' y3 - d * dx / q,
r' abs(r))
R (c1, c2)
L(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)]
print("Through points:\n #.,\n #.\n and radius #.6\nYou can construct the following circles:".format(p1, p2, r))
X.try
V (c1, c2) = circles_from_p1p2r(p1, p2, r)
print(" #.\n #.\n".format(c1, c2))
X.catch Error v
print(" ERROR: #.\n".format(v.msg)) |
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).
| #11l | 11l | V animals = [‘Rat’, ‘Ox’, ‘Tiger’, ‘Rabbit’, ‘Dragon’, ‘Snake’, ‘Horse’, ‘Goat’, ‘Monkey’, ‘Rooster’, ‘Dog’, ‘Pig’]
V elements = [‘Wood’, ‘Fire’, ‘Earth’, ‘Metal’, ‘Water’]
F getElement(year)
R :elements[(year - 4) % 10 I/ 2]
F getAnimal(year)
R :animals[(year - 4) % 12]
F getYY(year)
I year % 2 == 0
R ‘yang’
E
R ‘yin’
L(year) [1935, 1938, 1968, 1972, 1976, 2017]
print(year‘ is the year of the ’getElement(year)‘ ’getAnimal(year)‘ (’getYY(year)‘).’) |
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. | #11l | 11l | F cholesky(A)
V l = [[0.0] * A.len] * A.len
L(i) 0 .< A.len
L(j) 0 .. i
V s = sum((0 .< j).map(k -> @l[@i][k] * @l[@j][k]))
l[i][j] = I (i == j) {sqrt(A[i][i] - s)} E (1.0 / l[j][j] * (A[i][j] - s))
R l
F pprint(m)
print(‘[’)
L(row) m
print(row)
print(‘]’)
V m1 = [[25, 15, -5],
[15, 18, 0],
[-5, 0, 11]]
print(cholesky(m1))
print()
V m2 = [[18, 22, 54, 42],
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106]]
pprint(cholesky(m2)) |
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
| #D | D | int[3] array;
array[0] = 5;
// array.length = 4; // compile-time error |
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
| #jq | jq | def combination(r):
if r > length or r < 0 then empty
elif r == length then .
else ( [.[0]] + (.[1:]|combination(r-1))),
( .[1:]|combination(r))
end;
# select r integers from the set (0 .. n-1)
def combinations(n;r): [range(0;n)] | combination(r); |
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.
| #PL.2FM | PL/M | /* IF-THEN-ELSE - THE ELSE STATEMENT; PART IS OPTIONAL */
IF COND THEN STATEMENT1; ELSE STATEMENT2;
/* CAN BE CHAINED - THE ELSE STATEMENTX; PART IS STILL OPTIONAL */
IF COND1 THEN STATEMENT1;
ELSE IF CONB2 THEN STATEMENT2;
ELSE IF CONB3 THEN STATEMENT3;
ELSE STATEMENTX; |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Xojo | Xojo |
// Comments are denoted by a preceding double slash or or single quote
' and continue to the end of the line. There are no multi-line comment blocks
Dim foo As Integer // Comments can also occupy the ends of code lines |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #XPL0 | XPL0 | Text(0, \comment\ "Hello \not a comment\ World!"); \comment |
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers | Chernick's Carmichael numbers | In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1:
U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1)
is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4).
Example
U(3, m) = (6m + 1) * (12m + 1) * (18m + 1)
U(4, m) = U(3, m) * (2^2 * 9m + 1)
U(5, m) = U(4, m) * (2^3 * 9m + 1)
...
U(n, m) = U(n-1, m) * (2^(n-2) * 9m + 1)
The smallest Chernick's Carmichael number with 3 prime factors, is: U(3, 1) = 1729.
The smallest Chernick's Carmichael number with 4 prime factors, is: U(4, 1) = 63973.
The smallest Chernick's Carmichael number with 5 prime factors, is: U(5, 380) = 26641259752490421121.
For n = 5, the smallest number m that satisfy Chernick's conditions, is m = 380, therefore U(5, 380) is the smallest Chernick's Carmichael number with 5 prime factors.
U(5, 380) is a Chernick's Carmichael number because m = 380 is a multiple of 2^(n-4), where n = 5, and the factors { (6*380 + 1), (12*380 + 1), (18*380 + 1), (36*380 + 1), (72*380 + 1) } are all prime numbers.
Task
For n ≥ 3, let a(n) be the smallest Chernick's Carmichael number with n prime factors.
Compute a(n) for n = 3..9.
Optional: find a(10).
Note: it's perfectly acceptable to show the terms in factorized form:
a(3) = 7 * 13 * 19
a(4) = 7 * 13 * 19 * 37
a(5) = 2281 * 4561 * 6841 * 13681 * 27361
...
See also
Jack Chernick, On Fermat's simple theorem (PDF)
OEIS A318646: The least Chernick's "universal form" Carmichael number with n prime factors
Related tasks
Carmichael 3 strong pseudoprimes
| #F.23 | F# |
// Generate Chernick's Carmichael numbers. Nigel Galloway: June 1st., 2019
let fMk m k=isPrime(6*m+1) && isPrime(12*m+1) && [1..k-2]|>List.forall(fun n->isPrime(9*(pown 2 n)*m+1))
let fX k=Seq.initInfinite(fun n->(n+1)*(pown 2 (k-4))) |> Seq.filter(fun n->fMk n k )
let cherCar k=let m=Seq.head(fX k) in printfn "m=%d primes -> %A " m ([6*m+1;12*m+1]@List.init(k-2)(fun n->9*(pown 2 (n+1))*m+1))
[4..9] |> Seq.iter cherCar
|
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The sequence is named after Sarvadaman D. S. Chowla, (22 October 1907 ──► 10 December 1995),
a London born Indian American mathematician specializing in number theory.
German mathematician Carl Friedrich Gauss (1777─1855) said:
"Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics".
Definitions
Chowla numbers can also be expressed as:
chowla(n) = sum of divisors of n excluding unity and n
chowla(n) = sum( divisors(n)) - 1 - n
chowla(n) = sum( properDivisors(n)) - 1
chowla(n) = sum(aliquotDivisors(n)) - 1
chowla(n) = aliquot(n) - 1
chowla(n) = sigma(n) - 1 - n
chowla(n) = sigmaProperDivisiors(n) - 1
chowla(a*b) = a + b, if a and b are distinct primes
if chowla(n) = 0, and n > 1, then n is prime
if chowla(n) = n - 1, and n > 1, then n is a perfect number
Task
create a chowla function that returns the chowla number for a positive integer n
Find and display (1 per line) for the 1st 37 integers:
the integer (the index)
the chowla number for that integer
For finding primes, use the chowla function to find values of zero
Find and display the count of the primes up to 100
Find and display the count of the primes up to 1,000
Find and display the count of the primes up to 10,000
Find and display the count of the primes up to 100,000
Find and display the count of the primes up to 1,000,000
Find and display the count of the primes up to 10,000,000
For finding perfect numbers, use the chowla function to find values of n - 1
Find and display all perfect numbers up to 35,000,000
use commas within appropriate numbers
show all output here
Related tasks
totient function
perfect numbers
Proper divisors
Sieve of Eratosthenes
See also
the OEIS entry for A48050 Chowla's function.
| #AWK | AWK |
# syntax: GAWK -f CHOWLA_NUMBERS.AWK
# converted from Go
BEGIN {
for (i=1; i<=37; i++) {
printf("chowla(%2d) = %s\n",i,chowla(i))
}
printf("\nCount of primes up to:\n")
count = 1
limit = 1e7
sieve(limit)
power = 100
for (i=3; i<limit; i+=2) {
if (!c[i]) {
count++
}
if (i == power-1) {
printf("%10s = %s\n",commatize(power),commatize(count))
power *= 10
}
}
printf("\nPerfect numbers:")
count = 0
limit = 35000000
k = 2
kk = 3
while (1) {
if ((p = k * kk) > limit) {
break
}
if (chowla(p) == p-1) {
printf(" %s",commatize(p))
count++
}
k = kk + 1
kk += k
}
printf("\nThere are %d perfect numbers <= %s\n",count,commatize(limit))
exit(0)
}
function chowla(n, i,j,sum) {
if (n < 1 || n != int(n)) {
return sprintf("%s is invalid",n)
}
for (i=2; i*i<=n; i++) {
if (n%i == 0) {
j = n / i
sum += (i == j) ? i : i + j
}
}
return(sum+0)
}
function commatize(x, num) {
if (x < 0) {
return "-" commatize(-x)
}
x = int(x)
num = sprintf("%d.",x)
while (num ~ /^[0-9][0-9][0-9][0-9]/) {
sub(/[0-9][0-9][0-9][,.]/,",&",num)
}
sub(/\.$/,"",num)
return(num)
}
function sieve(limit, i,j) {
for (i=1; i<=limit; i++) {
c[i] = 0
}
for (i=3; i*3<limit; i+=2) {
if (!c[i] && chowla(i) == 0) {
for (j=3*i; j<limit; j+=2*i) {
c[j] = 1
}
}
}
}
|
http://rosettacode.org/wiki/Church_numerals | Church numerals | Task
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
Church one applies its first argument f just once to its second argument x, yielding f(x)
Church two applies its first argument f twice to its second argument x, yielding f(f(x))
and each successive Church numeral applies its first argument one additional time to its second argument, f(f(f(x))), f(f(f(f(x)))) ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument.
Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals.
In your language define:
Church Zero,
a Church successor function (a function on a Church numeral which returns the next Church numeral in the series),
functions for Addition, Multiplication and Exponentiation over Church numerals,
a function to convert integers to corresponding Church numerals,
and a function to convert Church numerals to corresponding integers.
You should:
Derive Church numerals three and four in terms of Church zero and a Church successor function.
use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4,
similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function,
convert each result back to an integer, and return it or print it to the console.
| #Go | Go | package main
import "fmt"
type any = interface{}
type fn func(any) any
type church func(fn) fn
func zero(f fn) fn {
return func(x any) any {
return x
}
}
func (c church) succ() church {
return func(f fn) fn {
return func(x any) any {
return f(c(f)(x))
}
}
}
func (c church) add(d church) church {
return func(f fn) fn {
return func(x any) any {
return c(f)(d(f)(x))
}
}
}
func (c church) mul(d church) church {
return func(f fn) fn {
return func(x any) any {
return c(d(f))(x)
}
}
}
func (c church) pow(d church) church {
di := d.toInt()
prod := c
for i := 1; i < di; i++ {
prod = prod.mul(c)
}
return prod
}
func (c church) toInt() int {
return c(incr)(0).(int)
}
func intToChurch(i int) church {
if i == 0 {
return zero
} else {
return intToChurch(i - 1).succ()
}
}
func incr(i any) any {
return i.(int) + 1
}
func main() {
z := church(zero)
three := z.succ().succ().succ()
four := three.succ()
fmt.Println("three ->", three.toInt())
fmt.Println("four ->", four.toInt())
fmt.Println("three + four ->", three.add(four).toInt())
fmt.Println("three * four ->", three.mul(four).toInt())
fmt.Println("three ^ four ->", three.pow(four).toInt())
fmt.Println("four ^ three ->", four.pow(three).toInt())
fmt.Println("5 -> five ->", intToChurch(5).toInt())
} |
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.
| #Component_Pascal | Component Pascal |
MODULE Point;
IMPORT
Strings;
TYPE
Instance* = POINTER TO LIMITED RECORD
x-, y- : LONGINT; (* Instance variables *)
END;
PROCEDURE (self: Instance) Initialize*(x,y: LONGINT), NEW;
BEGIN
self.x := x;
self.y := y
END Initialize;
(* constructor *)
PROCEDURE New*(x, y: LONGINT): Instance;
VAR
point: Instance;
BEGIN
NEW(point);
point.Initialize(x,y);
RETURN point
END New;
(* methods *)
PROCEDURE (self: Instance) Add*(other: Instance): Instance, NEW;
BEGIN
RETURN New(self.x + other.x,self.y + other.y);
END Add;
PROCEDURE (self: Instance) ToString*(): POINTER TO ARRAY OF CHAR, NEW;
VAR
xStr,yStr: ARRAY 64 OF CHAR;
str: POINTER TO ARRAY OF CHAR;
BEGIN
Strings.IntToString(self.x,xStr);
Strings.IntToString(self.y,yStr);
NEW(str,128);str^ := "@(" +xStr$ + "," + yStr$ + ")";
RETURN str
END ToString;
END Point.
|
http://rosettacode.org/wiki/Cistercian_numerals | Cistercian numerals | Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999.
How they work
All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyphs representing the digits 1 through 9 are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:
The upper-right quadrant represents the ones place.
The upper-left quadrant represents the tens place.
The lower-right quadrant represents the hundreds place.
The lower-left quadrant represents the thousands place.
Please consult the following image for examples of Cistercian numerals showing each glyph: [1]
Task
Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).
Use the routine to show the following Cistercian numerals:
0
1
20
300
4000
5555
6789
And a number of your choice!
Notes
Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed — especially for text output.
See also
Numberphile - The Forgotten Number System
dcode.fr - Online Cistercian numeral converter
| #Nim | Nim | const Size = 15
type Canvas = array[Size, array[Size, char]]
func horizontal(canvas: var Canvas; col1, col2, row: Natural) =
for col in col1..col2:
canvas[row][col] = 'x'
func vertical(canvas: var Canvas; row1, row2, col: Natural) =
for row in row1..row2:
canvas[row][col] = 'x'
func diagd(canvas: var Canvas; col1, col2, row: Natural) =
for col in col1..col2:
canvas[row + col - col1][col] = 'x'
func diagu(canvas: var Canvas; col1, col2, row: Natural) =
for col in col1..col2:
canvas[row - col + col1][col] = 'x'
func drawPart(canvas: var Canvas; value: Natural) =
case value
of 1:
canvas.horizontal(6, 10, 0)
of 2:
canvas.horizontal(6, 10, 4)
of 3:
canvas.diagd(6, 10, 0)
of 4:
canvas.diagu(6, 10, 4)
of 5:
canvas.drawPart(1)
canvas.drawPart(4)
of 6:
canvas.vertical(0, 4, 10)
of 7:
canvas.drawPart(1)
canvas.drawPart(6)
of 8:
canvas.drawPart(2)
canvas.drawPart(6)
of 9:
canvas.drawPart(1)
canvas.drawPart(8)
of 10:
canvas.horizontal(0, 4, 0)
of 20:
canvas.horizontal(0, 4, 4)
of 30:
canvas.diagu(0, 4, 4)
of 40:
canvas.diagd(0, 4, 0)
of 50:
canvas.drawPart(10)
canvas.drawPart(40)
of 60:
canvas.vertical(0, 4, 0)
of 70:
canvas.drawPart(10)
canvas.drawPart(60)
of 80:
canvas.drawPart(20)
canvas.drawPart(60)
of 90:
canvas.drawPart(10)
canvas.drawPart(80)
of 100:
canvas.horizontal(6, 10, 14)
of 200:
canvas.horizontal(6, 10, 10)
of 300:
canvas.diagu(6, 10, 14)
of 400:
canvas.diagd(6, 10, 10)
of 500:
canvas.drawPart(100)
canvas.drawPart(400)
of 600:
canvas.vertical(10, 14, 10)
of 700:
canvas.drawPart(100)
canvas.drawPart(600)
of 800:
canvas.drawPart(200)
canvas.drawPart(600)
of 900:
canvas.drawPart(100)
canvas.drawPart(800)
of 1000:
canvas.horizontal(0, 4, 14)
of 2000:
canvas.horizontal(0, 4, 10)
of 3000:
canvas.diagd(0, 4, 10)
of 4000:
canvas.diagu(0, 4, 14)
of 5000:
canvas.drawPart(1000)
canvas.drawPart(4000)
of 6000:
canvas.vertical(10, 14, 0)
of 7000:
canvas.drawPart(1000)
canvas.drawPart(6000)
of 8000:
canvas.drawPart(2000)
canvas.drawPart(6000)
of 9000:
canvas.drawPart(1000)
canvas.drawPart(8000)
else:
raise newException(ValueError, "wrong value for 'drawPart'")
func draw(canvas: var Canvas; value: Natural) =
var val = value
let thousands = val div 1000
val = val mod 1000
let hundreds = val div 100
val = val mod 100
let tens = val div 10
let ones = val mod 10
if thousands != 0:
canvas.drawPart(1000 * thousands)
if hundreds != 0:
canvas.drawPart(100 * hundreds)
if tens != 0:
canvas.drawPart(10 * tens)
if ones != 0:
canvas.drawPart(ones)
func cistercian(n: Natural): Canvas =
for row in result.mitems:
for cell in row.mitems: cell = ' '
row[5] = 'x'
result.draw(n)
proc `$`(canvas: Canvas): string =
for row in canvas:
for cell in row:
result.add cell
result.add '\n'
when isMainModule:
for number in [0, 1, 20, 300, 4000, 5555, 6789, 9999]:
echo number, ':'
echo cistercian(number) |
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)
| #F.23 | F# |
let closest_pairs (xys: Point []) =
let n = xys.Length
seq { for i in 0..n-2 do
for j in i+1..n-1 do
yield xys.[i], xys.[j] }
|> Seq.minBy (fun (p0, p1) -> (p1 - p0).LengthSquared)
|
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
Goal
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: Multiple distinct objects
| #LFE | LFE |
> (set funcs (list-comp ((<- m (lists:seq 1 10)))
(lambda () (math:pow m 2))))
|
http://rosettacode.org/wiki/Circular_primes | Circular primes | Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not.
A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1.
For example:
R(2) = 11 and R(5) = 11111 are repunits.
Task
Find the first 19 circular primes.
If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes.
(Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can.
See also
Wikipedia article - Circular primes.
Wikipedia article - Repunit.
OEIS sequence A016114 - Circular primes.
| #Prolog | Prolog |
?- use_module(library(primality)).
circular(N) :- member(N, [2, 3, 5, 7]).
circular(N) :-
limit(15, (
candidate(N),
N > 9,
circular_prime(N))).
circular(r(K)) :-
between(6, inf, K),
N is (10**K - 1) div 9,
prime(N).
candidate(0).
candidate(N) :-
candidate(M),
member(D, [1, 3, 7, 9]),
N is 10*M + D.
circular_prime(N) :-
K is floor(log10(N)) + 1,
circular_prime(N, N, K).
circular_prime(_, _, 0) :- !.
circular_prime(P0, P, K) :-
P >= P0,
prime(P),
rotate(P, Q), succ(DecK, K),
circular_prime(P0, Q, DecK).
rotate(N, M) :-
D is floor(log10(N)),
divmod(N, 10, Q, R),
M is R*10**D + Q.
main :-
findall(P, limit(23, circular(P)), S),
format("The first 23 circular primes:~n~w~n", [S]),
halt.
?- main.
|
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points | Circles of given radius through two points |
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
Exceptions
r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.
If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language.
If the points are too far apart then no circles can be drawn.
Task detail
Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned.
Show here the output for the following inputs:
p1 p2 r
0.1234, 0.9876 0.8765, 0.2345 2.0
0.0000, 2.0000 0.0000, 0.0000 1.0
0.1234, 0.9876 0.1234, 0.9876 2.0
0.1234, 0.9876 0.8765, 0.2345 0.5
0.1234, 0.9876 0.1234, 0.9876 0.0
Related task
Total circles area.
See also
Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
| #Action.21 | Action! | INCLUDE "H6:REALMATH.ACT"
PROC Circles(CHAR ARRAY sx1,sy1,sx2,sy2,sr)
REAL x1,y1,x2,y2,r,x,y,bx,by,pb,cb,xx,yy
REAL two,tmp1,tmp2,tmp3
ValR(sx1,x1) ValR(sy1,y1)
ValR(sx2,x2) ValR(sy2,y2)
ValR(sr,r) IntToReal(2,two)
Print("p1=(") PrintR(x1) Put(32)
PrintR(y1) Print(") p2=(")
PrintR(x2) Put(32) PrintR(y2)
Print(") r=") PrintR(r) Print(" -> ")
IF RealEqual(r,rzero) THEN
PrintE("Radius is zero, no circles") PutE()
RETURN
FI
RealSub(x2,x1,tmp1) ;tmp1=x2-x1
RealDiv(tmp1,two,x) ;x=(x2-x1)/2
RealSub(y2,y1,tmp1) ;tmp1=y2-y1
RealDiv(tmp1,two,y) ;y=(y2-y1)/2
RealAdd(x1,x,bx) ;bx=x1+x
RealAdd(y1,y,by) ;bx=x1+x
RealMult(x,x,tmp1) ;tmp1=x^2
RealMult(y,y,tmp2) ;tmp2=y^2
RealAdd(tmp1,tmp2,tmp3) ;tmp3=x^2+y^2
Sqrt(tmp3,pb) ;pb=sqrt(x^2+y^2)
IF RealEqual(pb,rzero) THEN
PrintE("Infinite circles")
ELSEIF RealGreater(pb,r) THEN
PrintE("Points are too far, no circles")
ELSE
RealMult(r,r,tmp1) ;tmp1=r^2
RealMult(pb,pb,tmp2) ;tmp2=pb^2
RealSub(tmp1,tmp2,tmp3) ;tmp3=r^2-pb^2
Sqrt(tmp3,cb) ;cb=sqrt(r^2-pb^2)
RealMult(y,cb,tmp1) ;tmp1=y*cb
RealDiv(tmp1,pb,xx) ;xx=y*cb/pb
RealMult(x,cb,tmp1) ;tmp1=x*cb
RealDiv(tmp1,pb,yy) ;yy=x*cb/pb
RealSub(bx,xx,tmp1) ;tmp1=bx-xx
Print("c1=(") PrintR(tmp1) Put(32)
RealAdd(by,yy,tmp1) ;tmp1=by+yy
PrintR(tmp1) Print(") c2=(")
RealAdd(bx,xx,tmp1) ;tmp1=bx+xx
PrintR(tmp1) Put(32)
RealSub(by,yy,tmp1) ;tmp1=by-yy
PrintR(tmp1) PrintE(")")
FI
PutE()
RETURN
PROC Main()
Put(125) PutE() ;clear the screen
MathInit()
Circles("0.1234","0.9876","0.8765","0.2345","2.0")
Circles("0.0000","2.0000","0.0000","0.0000","1.0")
Circles("0.1234","0.9876","0.1234","0.9876","2.0")
Circles("0.1234","0.9876","0.8765","0.2345","0.5")
Circles("0.1234","0.9876","0.1234","0.9876","0.0")
RETURN |
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Tuesday, February 1, 2022 CE (in the common Gregorian calendar) will begin the lunisolar Year of the Tiger.
The celestial stems have no one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems each belong to one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element's governance is associated with yin, the other with yang.
Thus, 2022 is also the yang year of Water. Note that since 12 is an even number, the association between animals and yin/yang doesn't change. Consecutive Years of the Rooster will cycle through the five elements, but will always be yin, despite the apparent conceptual mismatch between the specifically-male English animal name and the female aspect denoted by yin.
Task
Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.
You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).
Requisite information
The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.
The element cycle runs in this order: Wood, Fire, Earth, Metal, Water.
The yang year precedes the yin year within each element.
The current 60-year cycle began in 1984 CE; the first cycle of the Common Era began in 4 CE.
Thus, 1984 was the year of the Wood Rat (yang), 1985 was the year of the Wood Ox (yin), and 1986 the year of the Fire Tiger (yang); 2022 - which, as already noted, is the year of the Water Tiger (yang) - is the 39th year of the current cycle.
Information for optional task
The ten celestial stems are 甲 jiă, 乙 yĭ, 丙 bĭng, 丁 dīng, 戊 wù, 己 jĭ, 庚 gēng, 辛 xīn, 壬 rén, and 癸 gŭi. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3".
The twelve terrestrial branches are 子 zĭ, 丑 chŏu, 寅 yín, 卯 măo, 辰 chén, 巳 sì, 午 wŭ, 未 wèi, 申 shēn, 酉 yŏu, 戌 xū, 亥 hài. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4".
Therefore 1984 was 甲子 (jiă-zĭ, or jia3-zi3). 2022 is 壬寅 (rén-yín or ren2-yin2).
| #360_Assembly | 360 Assembly | * Chinese zodiac 10/03/2019
CHINEZOD CSECT
USING CHINEZOD,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
LA R6,1 i=1
DO WHILE=(C,R6,LE,=A(NY)) do i=1 to hbound(years)
LR R1,R6 i
SLA R1,2 *4
L R2,YEARS-4(R1) ~
ST R2,YEAR year=years(i)
SH R2,=H'4' -4
LR R7,R2 year-4
SRDA R2,32 ~
D R2,=F'10' /10
SRA R2,1 /2
MH R2,=H'6' *6
LA R1,ELEMENTS(R2) ~
MVC ELEMENT,0(R1) element=elements(mod(year-4,10)/2+1)
LR R2,R7 year-4
SRDA R2,32 ~
D R2,=F'12' /12
SLA R2,3 *8
LA R1,ANIMALS(R2) ~
MVC ANIMAL,0(R1) animal=animals(mod(year-4,12)+1)
L R2,YEAR year
SRDA R2,32 ~
D R2,=F'2' /2
SLA R2,2 *4
LA R1,YINYANGS(R2) ~
MVC YINYANG,0(R1) yinyang=yinyangs(mod(year,2)+1)
LR R2,R7 year-4
SRDA R2,32 ~
D R2,=F'60' /60
LA R2,1(R2) nn=mod(year-4,60)+1
L R1,YEAR year
XDECO R1,XDEC edit year
MVC PG+00(4),XDEC+8 output year
MVC PG+24(6),ELEMENT output element
MVC PG+31(8),ANIMAL output animal
MVC PG+41(4),YINYANG output yinyang
XDECO R2,XDEC edit nn
MVC PG+49(2),XDEC+10 output nn
XPRNT PG,L'PG print buffer
LA R6,1(R6) i++
ENDDO , enddo i
L R13,4(0,R13) restore previous savearea pointer
RETURN (14,12),RC=0 restore registers from calling sav
NY EQU (ANIMAL-YEARS)/4
ANIMALS DC CL8'Rat',CL8'Ox',CL8'Tiger',CL8'Rabbit'
DC CL8'Dragon',CL8'Snake',CL8'Horse',CL8'Goat'
DC CL8'Monkey',CL8'Rooster',CL8'Dog',CL8'Pig'
ELEMENTS DC CL6'Wood',CL6'Fire',CL6'Earth',CL6'Metal',CL6'Water'
YINYANGS DC CL4'Yang',CL4'Yin'
YEARS DC F'1935',F'1938',F'1968',F'1972',F'1976',F'1984',F'2017'
ANIMAL DS CL8
ELEMENT DS CL6
YINYANG DS CL4
YEAR DS F
PG DC CL80':::: is the year of the :::::: :::::::: (::::). ::/60'
XDEC DS CL12 temp for xdeco
REGEQU
END CHINEZOD |
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. | #Ada | Ada | with Ada.Numerics.Generic_Real_Arrays;
generic
with package Matrix is new Ada.Numerics.Generic_Real_Arrays (<>);
package Decomposition is
-- decompose a square matrix A by A = L * Transpose (L)
procedure Decompose (A : Matrix.Real_Matrix; L : out Matrix.Real_Matrix);
end Decomposition; |
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
| #Delphi | Delphi |
// Creates and initializes a new integer Array
var
// Dynamics arrays can be initialized, if it's global variable in declaration scope
intArray: TArray<Integer> = [1, 2, 3, 4, 5];
intArray2: array of Integer = [1, 2, 3, 4, 5];
//Cann't initialize statics arrays in declaration scope
intArray3: array [0..4]of Integer;
intArray4: array [10..14]of Integer;
procedure
var
// Any arrays can't be initialized, if it's local variable in declaration scope
intArray5: TArray<Integer>;
begin
// Dynamics arrays can be full assigned in routine scope
intArray := [1,2,3];
intArray2 := [1,2,3];
// Dynamics arrays zero-based
intArray[0] := 1;
// Dynamics arrays must set size, if it not was initialized before
SetLength(intArray,5);
// Inline dynamics arrays can be created and initialized routine scope
// only for version after 10.3 Tokyo
var intArray6 := [1, 2, 3];
var intArray7: TArray<Integer> := [1, 2, 3];
end;
|
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
| #Julia | Julia | using Combinatorics
n = 4
m = 3
for i in combinations(0:n,m)
println(i')
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.
| #Pop11 | Pop11 | if condition then
;;; Action
endif; |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #XQuery | XQuery | (: This is a XQuery comment :) |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #XSLT | XSLT | <!-- Comment syntax is borrowed from XML and HTML. --> |
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}}}
.
| #11l | 11l | F mul_inv(=a, =b)
V b0 = b
V x0 = 0
V x1 = 1
I b == 1
R 1
L a > 1
V q = a I/ b
(a, b) = (b, a % b)
(x0, x1) = (x1 - q * x0, x0)
I x1 < 0
x1 += b0
R x1
F chinese_remainder(n, a)
V sum = 0
V prod = product(n)
L(n_i, a_i) zip(n, a)
V p = prod I/ n_i
sum += a_i * mul_inv(p, n_i) * p
R sum % prod
V n = [3, 5, 7]
V a = [2, 3, 2]
print(chinese_remainder(n, a)) |
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers | Chernick's Carmichael numbers | In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1:
U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1)
is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4).
Example
U(3, m) = (6m + 1) * (12m + 1) * (18m + 1)
U(4, m) = U(3, m) * (2^2 * 9m + 1)
U(5, m) = U(4, m) * (2^3 * 9m + 1)
...
U(n, m) = U(n-1, m) * (2^(n-2) * 9m + 1)
The smallest Chernick's Carmichael number with 3 prime factors, is: U(3, 1) = 1729.
The smallest Chernick's Carmichael number with 4 prime factors, is: U(4, 1) = 63973.
The smallest Chernick's Carmichael number with 5 prime factors, is: U(5, 380) = 26641259752490421121.
For n = 5, the smallest number m that satisfy Chernick's conditions, is m = 380, therefore U(5, 380) is the smallest Chernick's Carmichael number with 5 prime factors.
U(5, 380) is a Chernick's Carmichael number because m = 380 is a multiple of 2^(n-4), where n = 5, and the factors { (6*380 + 1), (12*380 + 1), (18*380 + 1), (36*380 + 1), (72*380 + 1) } are all prime numbers.
Task
For n ≥ 3, let a(n) be the smallest Chernick's Carmichael number with n prime factors.
Compute a(n) for n = 3..9.
Optional: find a(10).
Note: it's perfectly acceptable to show the terms in factorized form:
a(3) = 7 * 13 * 19
a(4) = 7 * 13 * 19 * 37
a(5) = 2281 * 4561 * 6841 * 13681 * 27361
...
See also
Jack Chernick, On Fermat's simple theorem (PDF)
OEIS A318646: The least Chernick's "universal form" Carmichael number with n prime factors
Related tasks
Carmichael 3 strong pseudoprimes
| #FreeBASIC | FreeBASIC | #include "isprime.bas"
Function PrimalityPretest(k As Integer) As Boolean
Dim As Integer ppp(1 To 8) = {3,5,7,11,13,17,19,23}
For i As Integer = 1 To Ubound(ppp)
If k Mod ppp(i) = 0 Then Return (k <= 23)
Next i
Return True
End Function
Function isChernick(n As Integer, m As Integer) As Boolean
Dim As Integer i, t = 9 * m
If Not PrimalityPretest(6 * m + 1) Then Return False
If Not PrimalityPretest(12 * m + 1) Then Return False
For i = 1 To n-1
If Not PrimalityPretest(t * (2 ^ i) + 1) Then Return False
Next i
If Not isPrime(6 * m + 1) Then Return False
If Not isPrime(12 * m + 1) Then Return False
For i = 1 To n - 2
If Not isPrime(t * (2 ^ i) + 1) Then Return False
Next i
Return True
End Function
Dim As Uinteger multiplier, k, m = 1
For n As Integer = 3 To 9
multiplier = Iif (n > 4, 2 ^ (n-4), 1)
If n > 5 Then multiplier *= 5
k = 1
Do
m = k * multiplier
If isChernick(n, m) Then
Print "a(" & n & ") has m = " & m
Exit Do
End If
k += 1
Loop
Next n
Sleep |
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The sequence is named after Sarvadaman D. S. Chowla, (22 October 1907 ──► 10 December 1995),
a London born Indian American mathematician specializing in number theory.
German mathematician Carl Friedrich Gauss (1777─1855) said:
"Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics".
Definitions
Chowla numbers can also be expressed as:
chowla(n) = sum of divisors of n excluding unity and n
chowla(n) = sum( divisors(n)) - 1 - n
chowla(n) = sum( properDivisors(n)) - 1
chowla(n) = sum(aliquotDivisors(n)) - 1
chowla(n) = aliquot(n) - 1
chowla(n) = sigma(n) - 1 - n
chowla(n) = sigmaProperDivisiors(n) - 1
chowla(a*b) = a + b, if a and b are distinct primes
if chowla(n) = 0, and n > 1, then n is prime
if chowla(n) = n - 1, and n > 1, then n is a perfect number
Task
create a chowla function that returns the chowla number for a positive integer n
Find and display (1 per line) for the 1st 37 integers:
the integer (the index)
the chowla number for that integer
For finding primes, use the chowla function to find values of zero
Find and display the count of the primes up to 100
Find and display the count of the primes up to 1,000
Find and display the count of the primes up to 10,000
Find and display the count of the primes up to 100,000
Find and display the count of the primes up to 1,000,000
Find and display the count of the primes up to 10,000,000
For finding perfect numbers, use the chowla function to find values of n - 1
Find and display all perfect numbers up to 35,000,000
use commas within appropriate numbers
show all output here
Related tasks
totient function
perfect numbers
Proper divisors
Sieve of Eratosthenes
See also
the OEIS entry for A48050 Chowla's function.
| #C | C | #include <stdio.h>
unsigned chowla(const unsigned n) {
unsigned sum = 0;
for (unsigned i = 2, j; i * i <= n; i ++) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
return sum;
}
int main(int argc, char const *argv[]) {
unsigned a;
for (unsigned n = 1; n < 38; n ++) printf("chowla(%u) = %u\n", n, chowla(n));
unsigned n, count = 0, power = 100;
for (n = 2; n < 10000001; n ++) {
if (chowla(n) == 0) count ++;
if (n % power == 0) printf("There is %u primes < %u\n", count, power), power *= 10;
}
count = 0;
unsigned limit = 350000000;
unsigned k = 2, kk = 3, p;
for ( ; ; ) {
if ((p = k * kk) > limit) break;
if (chowla(p) == p - 1) {
printf("%d is a perfect number\n", p);
count ++;
}
k = kk + 1; kk += k;
}
printf("There are %u perfect numbers < %u\n", count, limit);
return 0;
} |
http://rosettacode.org/wiki/Church_numerals | Church numerals | Task
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
Church one applies its first argument f just once to its second argument x, yielding f(x)
Church two applies its first argument f twice to its second argument x, yielding f(f(x))
and each successive Church numeral applies its first argument one additional time to its second argument, f(f(f(x))), f(f(f(f(x)))) ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument.
Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals.
In your language define:
Church Zero,
a Church successor function (a function on a Church numeral which returns the next Church numeral in the series),
functions for Addition, Multiplication and Exponentiation over Church numerals,
a function to convert integers to corresponding Church numerals,
and a function to convert Church numerals to corresponding integers.
You should:
Derive Church numerals three and four in terms of Church zero and a Church successor function.
use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4,
similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function,
convert each result back to an integer, and return it or print it to the console.
| #Groovy | Groovy | class ChurchNumerals {
static void main(args) {
def zero = { f -> { a -> a } }
def succ = { n -> { f -> { a -> f(n(f)(a)) } } }
def add = { n -> { k -> { n(succ)(k) } } }
def mult = { f -> { g -> { a -> f(g(a)) } } }
def pow = { f -> { g -> g(f) } }
def toChurchNum
toChurchNum = { n ->
n == 0 ? zero : succ(toChurchNum(n - 1))
}
def toInt = { n ->
n(x -> x + 1)(0)
}
def three = succ(succ(succ(zero)))
println toInt(three) // prints 3
def four = succ(three)
println toInt(four) // prints 4
println "3 + 4 = ${toInt(add(three)(four))}" // prints 3 + 4 = 7
println "4 + 3 = ${toInt(add(four)(three))}" // prints 4 + 3 = 7
println "3 * 4 = ${toInt(mult(three)(four))}" // prints 3 * 4 = 12
println "4 * 3 = ${toInt(mult(four)(three))}" // prints 4 * 3 = 12
println "3 ^ 4 = ${toInt(pow(three)(four))}" // prints 3 ^ 4 = 81
println "4 ^ 3 = ${toInt(pow(four)(three))}" // prints 4 ^ 3 = 64
}
}
|
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.
| #Crystal | Crystal | class MyClass
def initialize
@instance_var = 0
end
def add_1
@instance_var += 1
end
end
my_class = MyClass.new
|
http://rosettacode.org/wiki/Cistercian_numerals | Cistercian numerals | Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999.
How they work
All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyphs representing the digits 1 through 9 are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:
The upper-right quadrant represents the ones place.
The upper-left quadrant represents the tens place.
The lower-right quadrant represents the hundreds place.
The lower-left quadrant represents the thousands place.
Please consult the following image for examples of Cistercian numerals showing each glyph: [1]
Task
Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).
Use the routine to show the following Cistercian numerals:
0
1
20
300
4000
5555
6789
And a number of your choice!
Notes
Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed — especially for text output.
See also
Numberphile - The Forgotten Number System
dcode.fr - Online Cistercian numeral converter
| #Perl | Perl | #!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Cistercian_numerals
use warnings;
my @pts = ('', qw( 01 23 03 12 012 13 013 132 0132) );
my @dots = qw( 4-0 8-0 4-4 8-4 );
my @images = map { sprintf("%-9s\n", "$_:") . draw($_) }
0, 1, 20, 300, 4000, 5555, 6789, 1133;
for ( 1 .. 13 )
{
s/(.+)\n/ print " $1"; '' /e for @images;
print "\n";
}
sub draw
{
my $n = shift;
local $_ = " # \n" x 12;
my $quadrant = 0;
for my $digit ( reverse split //, sprintf "%04d", $n )
{
my ($oldx, $oldy);
for my $cell ( split //, $pts[$digit] )
{
my ($x, $y) = split /-/, $dots[$cell];
if( defined $oldx )
{
my $dirx = $x <=> $oldx;
my $diry = $y <=> $oldy;
for my $place ( 0 .. 3 )
{
substr $_, $oldx + $oldy * 10, 1, '#';
$oldx += $dirx;
$oldy += $diry;
}
}
($oldx, $oldy) = ($x, $y);
}
s/.+/ reverse $& /ge;
++$quadrant & 1 or $_ = join '', reverse /.+\n/g;
}
return $_;
} |
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)
| #Fantom | Fantom |
class Point
{
Float x
Float y
// create a random point
new make (Float x := Float.random * 10, Float y := Float.random * 10)
{
this.x = x
this.y = y
}
Float distance (Point p)
{
((x-p.x)*(x-p.x) + (y-p.y)*(y-p.y)).sqrt
}
override Str toStr () { "($x, $y)" }
}
class Main
{
// use brute force approach
static Point[] findClosestPair1 (Point[] points)
{
if (points.size < 2) return points // list too small
Point[] closestPair := [points[0], points[1]]
Float closestDistance := points[0].distance(points[1])
(1..<points.size).each |Int i|
{
((i+1)..<points.size).each |Int j|
{
Float trydistance := points[i].distance(points[j])
if (trydistance < closestDistance)
{
closestPair = [points[i], points[j]]
closestDistance = trydistance
}
}
}
return closestPair
}
// use recursive divide-and-conquer approach
static Point[] findClosestPair2 (Point[] points)
{
if (points.size <= 3) return findClosestPair1(points)
points.sort |Point a, Point b -> Int| { a.x <=> b.x }
bestLeft := findClosestPair2 (points[0..(points.size/2)])
bestRight := findClosestPair2 (points[(points.size/2)..-1])
Float minDistance
Point[] closePoints := [,]
if (bestLeft[0].distance(bestLeft[1]) < bestRight[0].distance(bestRight[1]))
{
minDistance = bestLeft[0].distance(bestLeft[1])
closePoints = bestLeft
}
else
{
minDistance = bestRight[0].distance(bestRight[1])
closePoints = bestRight
}
yPoints := points.findAll |Point p -> Bool|
{
(points.last.x - p.x).abs < minDistance
}.sort |Point a, Point b -> Int| { a.y <=> b.y }
closestPair := [,]
closestDist := Float.posInf
for (Int i := 0; i < yPoints.size - 1; ++i)
{
for (Int j := (i+1); j < yPoints.size; ++j)
{
if ((yPoints[j].y - yPoints[i].y) >= minDistance)
{
break
}
else
{
dist := yPoints[i].distance (yPoints[j])
if (dist < closestDist)
{
closestDist = dist
closestPair = [yPoints[i], yPoints[j]]
}
}
}
}
if (closestDist < minDistance)
return closestPair
else
return closePoints
}
public static Void main (Str[] args)
{
Int numPoints := 10 // default value, in case a number not given on command line
if ((args.size > 0) && (args[0].toInt(10, false) != null))
{
numPoints = args[0].toInt(10, false)
}
Point[] points := [,]
numPoints.times { points.add (Point()) }
Int t1 := Duration.now.toMillis
echo (findClosestPair1(points.dup))
Int t2 := Duration.now.toMillis
echo ("Time taken: ${(t2-t1)}ms")
echo (findClosestPair2(points.dup))
Int t3 := Duration.now.toMillis
echo ("Time taken: ${(t3-t2)}ms")
}
}
|
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
Goal
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: Multiple distinct objects
| #Lingo | Lingo | -- parent script "CallFunction"
property _code
-- if the function is supposed to return something, the code must contain a line that starts with "res="
on new (me, code)
me._code = code
return me
end
on call (me)
----------------------------------------
-- If custom arguments were passed, evaluate them in the current context.
-- Note: in the code passed to the constructor they have to be referenced
-- as arg[1], arg[2], ...
arg = []
repeat with i = 3 to the paramCount
arg[i-2] = param(i)
end repeat
----------------------------------------
res = VOID
do(me._code)
return res
end |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
Goal
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: Multiple distinct objects
| #Logtalk | Logtalk |
:- object(value_capture).
:- public(show/0).
show :-
integer::sequence(1, 10, List),
meta::map(create_closure, List, Closures),
meta::map(call_closure, List, Closures).
create_closure(Index, [Double]>>(Double is Index*Index)).
call_closure(Index, Closure) :-
call(Closure, Result),
write('Closure '), write(Index), write(' : '), write(Result), nl.
:- end_object.
|
http://rosettacode.org/wiki/Circular_primes | Circular primes | Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not.
A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1.
For example:
R(2) = 11 and R(5) = 11111 are repunits.
Task
Find the first 19 circular primes.
If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes.
(Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can.
See also
Wikipedia article - Circular primes.
Wikipedia article - Repunit.
OEIS sequence A016114 - Circular primes.
| #Python | Python |
import random
def is_Prime(n):
"""
Miller-Rabin primality test.
A return value of False means n is certainly not prime. A return value of
True means n is very likely a prime.
"""
if n!=int(n):
return False
n=int(n)
#Miller-Rabin test for prime
if n==0 or n==1 or n==4 or n==6 or n==8 or n==9:
return False
if n==2 or n==3 or n==5 or n==7:
return True
s = 0
d = n-1
while d%2==0:
d>>=1
s+=1
assert(2**s * d == n-1)
def trial_composite(a):
if pow(a, d, n) == 1:
return False
for i in range(s):
if pow(a, 2**i * d, n) == n-1:
return False
return True
for i in range(8):#number of trials
a = random.randrange(2, n)
if trial_composite(a):
return False
return True
def isPrime(n: int) -> bool:
'''
https://www.geeksforgeeks.org/python-program-to-check-whether-a-number-is-prime-or-not/
'''
# Corner cases
if (n <= 1) :
return False
if (n <= 3) :
return True
# This is checked so that we can skip
# middle five numbers in below loop
if (n % 2 == 0 or n % 3 == 0) :
return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
def rotations(n: int)-> set((int,)):
'''
>>> {123, 231, 312} == rotations(123)
True
'''
a = str(n)
return set(int(a[i:] + a[:i]) for i in range(len(a)))
def isCircular(n: int) -> bool:
'''
>>> [isCircular(n) for n in (11, 31, 47,)]
[True, True, False]
'''
return all(isPrime(int(o)) for o in rotations(n))
from itertools import product
def main():
result = [2, 3, 5, 7]
first = '137'
latter = '1379'
for i in range(1, 6):
s = set(int(''.join(a)) for a in product(first, *((latter,) * i)))
while s:
a = s.pop()
b = rotations(a)
if isCircular(a):
result.append(min(b))
s -= b
result.sort()
return result
assert [2, 3, 5, 7, 11, 13, 17, 37, 79, 113, 197, 199, 337, 1193, 3779, 11939, 19937, 193939, 199933] == main()
repunit = lambda n: int('1' * n)
def repmain(n: int) -> list:
'''
returns the first n repunit primes, probably.
'''
result = []
i = 2
while len(result) < n:
if is_Prime(repunit(i)):
result.append(i)
i += 1
return result
assert [2, 19, 23, 317, 1031] == repmain(5)
# because this Miller-Rabin test is already on rosettacode there's no good reason to test the longer repunits.
|
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
| #ALGOL_68 | ALGOL 68 | # represents a point #
MODE POINT = STRUCT( REAL x, REAL y );
# returns TRUE if p1 is the same point as p2, FALSE otherwise #
OP = = ( POINT p1, POINT p2 )BOOL: x OF p1 = x OF p2 AND y OF p1 = y OF p2;
# represents a circle with centre c and radius r #
MODE CIRCLE = STRUCT( POINT c, REAL r );
# returns the difference in x-coordinate of two points #
PRIO XDIFF = 5;
OP XDIFF = ( POINT p1, POINT p2 )REAL: x OF p1 - x OF p2;
# returns the difference in y-coordinate of two points #
PRIO YDIFF = 5;
OP YDIFF = ( POINT p1, POINT p2 )REAL: y OF p1 - y OF p2;
# returns the distance between two points #
OP - = ( POINT p1, POINT p2 )REAL:
BEGIN
REAL x diff = p1 XDIFF p2;
REAL y diff = p1 YDIFF p2;
sqrt( ( x diff * xdiff ) + ( y diff * y diff ) )
END; # - #
# generate a human-readable version of the circle c #
OP TOSTRING = ( CIRCLE c )STRING:
( "radius:"
+ fixed( r OF c, -8, 4 )
+ " @("
+ fixed( x OF c OF c, -8, 4 )
+ ", "
+ fixed( y OF c OF c, -8, 4 )
+ ")"
);
# modes to represent the results of the circles procedure ... #
# infinite number of circles #
MODE INFINITECIRCLES = STRUCT( STRING t, REAL r );
# two possible circles #
MODE TWOCIRCLES = STRUCT( CIRCLE a, CIRCLE b );
# one possible circle results in a CIRCLE #
# no possible circles #
MODE NOCIRCLES = STRUCT( STRING reason, POINT p1, POINT p2, REAL r );
# mode returned by the circles procedure #
MODE POSSIBLECIRCLES = UNION( INFINITECIRCLES, TWOCIRCLES, CIRCLE, NOCIRCLES );
# returns the circles of radius r that can be drawn through #
# points p1 and p2 #
PROC circles = ( POINT p1, POINT p2, REAL r )POSSIBLECIRCLES:
IF r < 0 THEN # negative radius - there are no circles #
NOCIRCLES( "negative radius", p1, p2, r )
ELIF p1 = p2 THEN # coincident points #
IF r = 0.0 THEN
# only one circle of radius 0 is possible #
CIRCLE( p1, 0.0 )
ELSE
# an infinite number of circles can be drawn through #
# the point #
INFINITECIRCLES( "infinite", r )
FI
ELSE # two possible circles #
REAL distance = p1 - p2;
IF distance > 2 * r THEN
# the points are too far apart #
NOCIRCLES( "points too far apart", p1, p2, r )
ELIF distance = 2 * r THEN
# the points are on the diameter of the circle #
CIRCLE( POINT( x OF p1 + ( ( p2 XDIFF p1 ) / 2 )
, y OF p1 + ( ( p2 YDIFF p1 ) / 2 )
)
, r
)
ELSE
# it is possible to draw two circles through the points #
REAL half x sum = ( x OF p1 + x OF p2 ) / 2;
REAL half y sum = ( y OF p1 + y OF p2 ) / 2;
REAL mirror distance = sqrt( ( r * r ) - ( ( distance * distance ) / 4 ) );
REAL x mirror = ( mirror distance * ( y OF p1 - y OF p2 ) ) / distance;
REAL y mirror = ( mirror distance * ( x OF p2 - x OF p1 ) ) / distance;
TWOCIRCLES( CIRCLE( POINT( half x sum + y mirror, half y sum + x mirror ), r )
, CIRCLE( POINT( half x sum - y mirror, half y sum - x mirror ), r )
)
FI
FI; # circles #
# test the circles procedure with the examples from the task #
PROC print circles = ( REAL x1, y1, x2, y2, r )VOID:
BEGIN
CASE circles( POINT( x1, y1 ), POINT( x2, y2 ), r )
IN ( NOCIRCLES n ): print( ( "No circles : ", reason OF n ) )
, ( TWOCIRCLES t ): print( ( "Two circles: "
, TOSTRING a OF t
, ", "
, TOSTRING b OF t
)
)
, ( CIRCLE c ): print( ( "One circle : ", TOSTRING c ) )
, ( INFINITECIRCLES i ): print( ( "Infinite circles" ) )
OUT BEGIN
print( ( "Unexpected circles result", newline ) );
stop
END
ESAC;
print( ( newline ) )
END; # print circles #
print circles( 0.1234, 0.9876, 0.8765, 0.2345, 2.0 );
print circles( 0.0000, 2.0000, 0.0000, 0.0000, 1.0 );
print circles( 0.1234, 0.9876, 0.1234, 0.9876, 2.0 );
print circles( 0.1234, 0.9876, 0.8765, 0.2345, 0.5 );
print circles( 0.1234, 0.9876, 0.1234, 0.9876, 0.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).
| #Action.21 | Action! | DEFINE PTR="CARD"
PTR ARRAY animals(12),elements(5),stems(10),branches(12),yinYangs(2)
PROC Init()
animals(0)="Rat" animals(1)="Ox"
animals(2)="Tiger" animals(3)="Rabbit"
animals(4)="Dragon" animals(5)="Snake"
animals(6)="Horse" animals(7)="Goat"
animals(8)="Monkey" animals(9)="Rooster"
animals(10)="Dog" animals(11)="Pig"
elements(0)="Wood" elements(1)="Fire"
elements(2)="Earth" elements(3)="Metal"
elements(4)="Water"
stems(0)="jia" stems(1)="yi"
stems(2)="bing" stems(3)="ding"
stems(4)="wu" stems(5)="ji"
stems(6)="geng" stems(7)="xin"
stems(8)="ren" stems(9)="gui"
branches(0)="zi" branches(1)="chou"
branches(2)="yin" branches(3)="mao"
branches(4)="chen" branches(5)="si"
branches(6)="wu" branches(7)="wei"
branches(8)="shen" branches(9)="you"
branches(10)="xu" branches(11)="hai"
yinYangs(0)="Yang" yinYangs(1)="Yin"
RETURN
PTR FUNC GetAnimal(INT y)
RETURN (animals((y-4) MOD 12))
PTR FUNC GetElement(INT y)
RETURN (elements(((y-4) MOD 10)/2))
PTR FUNC GetStem(INT y)
RETURN (stems((y-4) MOD 10))
PTR FUNC GetBranch(INT y)
RETURN (branches((y-4) MOD 12))
PTR FUNC GetYinYang(INT y)
RETURN (yinYangs(y MOD 2))
BYTE FUNC GetCycle(INT y)
RETURN ((y-4) MOD 60+1)
PROC Main()
INT ARRAY years=[1935 1938 1968 1972 1976 1984 2017 2021]
CHAR ARRAY s
BYTE i,c
INT y
Init()
FOR i=0 TO 7
DO
y=years(i)
PrintI(y) Print(" ")
s=GetStem(y) Print(s) Print("-")
s=GetBranch(y) Print(s) Print(" ")
s=GetElement(y) Print(s) Print(" ")
s=GetAnimal(y) Print(s) Print(" ")
s=GetYinYang(y) Print(s) Print(" ")
c=GetCycle(y) PrintB(c) Print("/60") PutE()
OD
RETURN |
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Tuesday, February 1, 2022 CE (in the common Gregorian calendar) will begin the lunisolar Year of the Tiger.
The celestial stems have no one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems each belong to one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element's governance is associated with yin, the other with yang.
Thus, 2022 is also the yang year of Water. Note that since 12 is an even number, the association between animals and yin/yang doesn't change. Consecutive Years of the Rooster will cycle through the five elements, but will always be yin, despite the apparent conceptual mismatch between the specifically-male English animal name and the female aspect denoted by yin.
Task
Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.
You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).
Requisite information
The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.
The element cycle runs in this order: Wood, Fire, Earth, Metal, Water.
The yang year precedes the yin year within each element.
The current 60-year cycle began in 1984 CE; the first cycle of the Common Era began in 4 CE.
Thus, 1984 was the year of the Wood Rat (yang), 1985 was the year of the Wood Ox (yin), and 1986 the year of the Fire Tiger (yang); 2022 - which, as already noted, is the year of the Water Tiger (yang) - is the 39th year of the current cycle.
Information for optional task
The ten celestial stems are 甲 jiă, 乙 yĭ, 丙 bĭng, 丁 dīng, 戊 wù, 己 jĭ, 庚 gēng, 辛 xīn, 壬 rén, and 癸 gŭi. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3".
The twelve terrestrial branches are 子 zĭ, 丑 chŏu, 寅 yín, 卯 măo, 辰 chén, 巳 sì, 午 wŭ, 未 wèi, 申 shēn, 酉 yŏu, 戌 xū, 亥 hài. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4".
Therefore 1984 was 甲子 (jiă-zĭ, or jia3-zi3). 2022 is 壬寅 (rén-yín or ren2-yin2).
| #Ada | Ada |
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
procedure Main is
type Element_Index is mod 5;
type Animal_Index is mod 12;
type Stem_Index is mod 10;
type Animal_Array is array(Animal_Index range <>) of Unbounded_String;
type Element_Array is array(Element_Index range <>) of Unbounded_String;
type Stem_Array is array(Stem_Index range <>) of Unbounded_String;
Ani_Arr : Animal_Array := (To_Unbounded_String ("Rat"),
To_Unbounded_String ("Ox"),
To_Unbounded_String ("Tiger"),
To_Unbounded_String ("Rabbit"),
To_Unbounded_String ("Dragon"),
To_Unbounded_String ("Snake"),
To_Unbounded_String ("Horse"),
To_Unbounded_String ("Sheep"),
To_Unbounded_String ("Monkey"),
To_Unbounded_String ("Rooster"),
To_Unbounded_String ("Dog"),
To_Unbounded_String ("Pig"));
Bra_Arr : Animal_Array := (To_Unbounded_String ("子"),
To_Unbounded_String ("丑"),
To_Unbounded_String ("寅"),
To_Unbounded_String ("卯"),
To_Unbounded_String ("辰"),
To_Unbounded_String ("巳"),
To_Unbounded_String ("午"),
To_Unbounded_String ("未"),
To_Unbounded_String ("申"),
To_Unbounded_String ("酉"),
To_Unbounded_String ("戌"),
To_Unbounded_String ("亥"));
Ele_Arr : Element_Array := (To_Unbounded_String ("Wood"),
To_Unbounded_String ("Fire"),
To_Unbounded_String ("Earth"),
To_Unbounded_String ("Metal"),
To_Unbounded_String ("Water"));
Ste_Arr : Stem_Array := (To_Unbounded_String ("甲"),
To_Unbounded_String ("乙"),
To_Unbounded_String ("丙"),
To_Unbounded_String ("丁"),
To_Unbounded_String ("戊"),
To_Unbounded_String ("己"),
To_Unbounded_String ("庚"),
To_Unbounded_String ("辛"),
To_Unbounded_String ("壬"),
To_Unbounded_String ("癸"));
procedure Sexagenary (Year : Positive) is
Base_Year : Positive := 1984;
Temp : Natural := abs (Base_Year - Year);
Temp_Float: Float := 0.0;
Ele_Idx : Element_Index := Element_Index'First;
Ani_Idx : Animal_Index := Animal_Index'First;
Ste_Idx : Stem_Index := Stem_Index'First;
Result : Unbounded_String := Null_Unbounded_String;
begin
Result := Result & Year'Image & " is the year of ";
if Year >= Base_Year then
Temp_Float := Float'Floor (Float (Temp) / Float (2));
Ele_Idx := Element_Index (Natural (Temp_Float) mod 5);
Result := Result & Ele_Arr (Ele_Idx) & " ";
Ani_Idx := Animal_Index (Temp mod 12);
Result := Result & Ani_Arr (Ani_Idx) & " ";
elsif Year < Base_Year then
Temp_Float := Float'Ceiling (Float (Temp) / Float (2));
Ele_Idx := Ele_Idx - Element_Index (Natural (Temp_Float) mod 5);
Result := Result & Ele_Arr (Ele_Idx) & " ";
Ani_Idx := Ani_Idx - Animal_Index (Temp mod 12);
Result := Result & Ani_Arr (Ani_Idx) & " ";
end if;
if Year mod 2 = 0 then
Result := Result & "(yang). ";
else
Result := Result & "(yin). ";
end if;
Ani_Idx := Animal_Index'First;
if Year >= Base_Year then
Ste_Idx := Stem_Index (Temp mod 10);
Result := Result & Ste_Arr (Ste_Idx);
Ani_Idx := Animal_Index (Temp mod 12);
Result := Result & Bra_Arr (Ani_Idx);
elsif Year < Base_Year then
Ste_Idx := Ste_Idx - Stem_Index (Temp mod 10);
Result := Result & Ste_Arr (Ste_Idx);
Ani_Idx := Ani_Idx - Animal_Index (Temp mod 12);
Result := Result & Bra_Arr (Ani_Idx);
end if;
Put (To_String (Result));
end Sexagenary;
arr : array(Positive range <>) of Positive := (1935, 1938, 1968, 1972, 1976, 1984, 1985, 2017);
begin
for I of arr loop
Sexagenary (I);
New_Line;
end loop;
end Main;
|
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. | #ALGOL_68 | ALGOL 68 | #!/usr/local/bin/a68g --script #
MODE FIELD=LONG REAL;
PROC (FIELD)FIELD field sqrt = long sqrt;
INT field prec = 5;
FORMAT field fmt = $g(-(2+1+field prec),field prec)$;
MODE MAT = [0,0]FIELD;
PROC cholesky = (MAT a) MAT:(
[UPB a, 2 UPB a]FIELD l;
FOR i FROM LWB a TO UPB a DO
FOR j FROM 2 LWB a TO i DO
FIELD s := 0;
FOR k FROM 2 LWB a TO j-1 DO
s +:= l[i,k] * l[j,k]
OD;
l[i,j] := IF i = j
THEN field sqrt(a[i,i] - s)
ELSE 1.0 / l[j,j] * (a[i,j] - s) FI
OD;
FOR j FROM i+1 TO 2 UPB a DO
l[i,j]:=0 # Not required if matrix is declared as triangular #
OD
OD;
l
);
PROC print matrix v1 =(MAT a)VOID:(
FOR i FROM LWB a TO UPB a DO
FOR j FROM 2 LWB a TO 2 UPB a DO
printf(($g(-(2+1+field prec),field prec)$, a[i,j]))
OD;
printf($l$)
OD
);
PROC print matrix =(MAT a)VOID:(
FORMAT vector fmt = $"("f(field fmt)n(2 UPB a-2 LWB a)(", " f(field fmt))")"$;
FORMAT matrix fmt = $"("f(vector fmt)n( UPB a- LWB a)(","lxf(vector fmt))")"$;
printf((matrix fmt, a))
);
main: (
MAT m1 = ((25, 15, -5),
(15, 18, 0),
(-5, 0, 11));
MAT c1 = cholesky(m1);
print matrix(c1);
printf($l$);
MAT m2 = ((18, 22, 54, 42),
(22, 70, 86, 62),
(54, 86, 174, 134),
(42, 62, 134, 106));
MAT c2 = cholesky(m2);
print matrix(c2)
) |
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
| #E | E | ? def constList := [1,2,3,4,5]
# value: [1, 2, 3, 4, 5]
? constList.with(6)
# value: [1, 2, 3, 4, 5, 6]
? def flexList := constList.diverge()
# value: [1, 2, 3, 4, 5].diverge()
? flexList.push(6)
? flexList
# value: [1, 2, 3, 4, 5, 6].diverge()
? constList
# value: [1, 2, 3, 4, 5]
? def constMap := [1 => 2, 3 => 4]
# value: [1 => 2, 3 => 4]
? constMap[1]
# value: 2
? def constSet := [1, 2, 3, 2].asSet()
# value: [1, 2, 3].asSet()
? constSet.contains(3)
# value: true |
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
| #K | K | comb:{[n;k]
f:{:[k=#x; :,x; :,/_f' x,'(1+*|x) _ !n]}
:,/f' !n
} |
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.
| #PostScript | PostScript | 9 10 lt {(9 is less than 10) show} if |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #XUL | XUL | <!-- Comment syntax is borrowed from XML and HTML. --> |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Yacas | Yacas | // This is a single line comment
/*
This comment spans
multiple lines
*/ |
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}}}
.
| #360_Assembly | 360 Assembly | * Chinese remainder theorem 06/09/2015
CHINESE CSECT
USING CHINESE,R12 base addr
LR R12,R15
BEGIN LA R9,1 m=1
LA R6,1 j=1
LOOPJ C R6,NN do j=1 to nn
BH ELOOPJ
LR R1,R6 j
SLA R1,2 j*4
M R8,N-4(R1) m=m*n(j)
LA R6,1(R6) j=j+1
B LOOPJ
ELOOPJ LA R6,1 x=1
LOOPX CR R6,R9 do x=1 to m
BH ELOOPX
LA R7,1 i=1
LOOPI C R7,NN do i=1 to nn
BH ELOOPI
LR R1,R7 i
SLA R1,2 i*4
LR R5,R6 x
LA R4,0
D R4,N-4(R1) x//n(i)
C R4,A-4(R1) if x//n(i)^=a(i)
BNE ITERX then iterate x
LA R7,1(R7) i=i+1
B LOOPI
ELOOPI MVC PG(2),=C'x='
XDECO R6,PG+2 edit x
XPRNT PG,14 print buffer
B RETURN
ITERX LA R6,1(R6) x=x+1
B LOOPX
ELOOPX XPRNT NOSOL,17 print
RETURN XR R15,R15 rc=0
BR R14
NN DC F'3'
N DC F'3',F'5',F'7'
A DC F'2',F'3',F'2'
PG DS CL80
NOSOL DC CL17'no solution found'
YREGS
END CHINESE |
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}}}
.
| #Action.21 | Action! | INT FUNC MulInv(INT a,b)
INT b0,x0,x1,q,tmp
IF b=1 THEN RETURN (1) FI
b0=b x0=0 x1=1
WHILE a>1
DO
q=a/b
tmp=b
b=a MOD b
a=tmp
tmp=x0
x0=x1-q*x0
x1=tmp
OD
IF x1<0 THEN
x1==+b0
FI
RETURN (x1)
INT FUNC ChineseRemainder(BYTE ARRAY n,a BYTE len)
INT prod,sum,p,m
BYTE i
prod=1 sum=0
FOR i=0 TO len-1
DO
prod==*n(i)
OD
FOR i=0 TO len-1
DO
p=prod/n(i)
m=MulInv(p,n(i))
sum==+a(i)*m*p
OD
RETURN (sum MOD prod)
PROC Main()
BYTE ARRAY n=[3 5 7],a=[2 3 2]
INT res
res=ChineseRemainder(n,a,3)
PrintI(res)
RETURN |
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers | Chernick's Carmichael numbers | In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1:
U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1)
is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4).
Example
U(3, m) = (6m + 1) * (12m + 1) * (18m + 1)
U(4, m) = U(3, m) * (2^2 * 9m + 1)
U(5, m) = U(4, m) * (2^3 * 9m + 1)
...
U(n, m) = U(n-1, m) * (2^(n-2) * 9m + 1)
The smallest Chernick's Carmichael number with 3 prime factors, is: U(3, 1) = 1729.
The smallest Chernick's Carmichael number with 4 prime factors, is: U(4, 1) = 63973.
The smallest Chernick's Carmichael number with 5 prime factors, is: U(5, 380) = 26641259752490421121.
For n = 5, the smallest number m that satisfy Chernick's conditions, is m = 380, therefore U(5, 380) is the smallest Chernick's Carmichael number with 5 prime factors.
U(5, 380) is a Chernick's Carmichael number because m = 380 is a multiple of 2^(n-4), where n = 5, and the factors { (6*380 + 1), (12*380 + 1), (18*380 + 1), (36*380 + 1), (72*380 + 1) } are all prime numbers.
Task
For n ≥ 3, let a(n) be the smallest Chernick's Carmichael number with n prime factors.
Compute a(n) for n = 3..9.
Optional: find a(10).
Note: it's perfectly acceptable to show the terms in factorized form:
a(3) = 7 * 13 * 19
a(4) = 7 * 13 * 19 * 37
a(5) = 2281 * 4561 * 6841 * 13681 * 27361
...
See also
Jack Chernick, On Fermat's simple theorem (PDF)
OEIS A318646: The least Chernick's "universal form" Carmichael number with n prime factors
Related tasks
Carmichael 3 strong pseudoprimes
| #Go | Go | package main
import (
"fmt"
"math/big"
)
var (
zero = new(big.Int)
prod = new(big.Int)
fact = new(big.Int)
)
func ccFactors(n, m uint64) (*big.Int, bool) {
prod.SetUint64(6*m + 1)
if !prod.ProbablyPrime(0) {
return zero, false
}
fact.SetUint64(12*m + 1)
if !fact.ProbablyPrime(0) { // 100% accurate up to 2 ^ 64
return zero, false
}
prod.Mul(prod, fact)
for i := uint64(1); i <= n-2; i++ {
fact.SetUint64((1<<i)*9*m + 1)
if !fact.ProbablyPrime(0) {
return zero, false
}
prod.Mul(prod, fact)
}
return prod, true
}
func ccNumbers(start, end uint64) {
for n := start; n <= end; n++ {
m := uint64(1)
if n > 4 {
m = 1 << (n - 4)
}
for {
num, ok := ccFactors(n, m)
if ok {
fmt.Printf("a(%d) = %d\n", n, num)
break
}
if n <= 4 {
m++
} else {
m += 1 << (n - 4)
}
}
}
}
func main() {
ccNumbers(3, 9)
} |
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The sequence is named after Sarvadaman D. S. Chowla, (22 October 1907 ──► 10 December 1995),
a London born Indian American mathematician specializing in number theory.
German mathematician Carl Friedrich Gauss (1777─1855) said:
"Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics".
Definitions
Chowla numbers can also be expressed as:
chowla(n) = sum of divisors of n excluding unity and n
chowla(n) = sum( divisors(n)) - 1 - n
chowla(n) = sum( properDivisors(n)) - 1
chowla(n) = sum(aliquotDivisors(n)) - 1
chowla(n) = aliquot(n) - 1
chowla(n) = sigma(n) - 1 - n
chowla(n) = sigmaProperDivisiors(n) - 1
chowla(a*b) = a + b, if a and b are distinct primes
if chowla(n) = 0, and n > 1, then n is prime
if chowla(n) = n - 1, and n > 1, then n is a perfect number
Task
create a chowla function that returns the chowla number for a positive integer n
Find and display (1 per line) for the 1st 37 integers:
the integer (the index)
the chowla number for that integer
For finding primes, use the chowla function to find values of zero
Find and display the count of the primes up to 100
Find and display the count of the primes up to 1,000
Find and display the count of the primes up to 10,000
Find and display the count of the primes up to 100,000
Find and display the count of the primes up to 1,000,000
Find and display the count of the primes up to 10,000,000
For finding perfect numbers, use the chowla function to find values of n - 1
Find and display all perfect numbers up to 35,000,000
use commas within appropriate numbers
show all output here
Related tasks
totient function
perfect numbers
Proper divisors
Sieve of Eratosthenes
See also
the OEIS entry for A48050 Chowla's function.
| #C.23 | C# | using System;
namespace chowla_cs
{
class Program
{
static int chowla(int n)
{
int sum = 0;
for (int i = 2, j; i * i <= n; i++)
if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
return sum;
}
static bool[] sieve(int limit)
{
// True denotes composite, false denotes prime.
// Only interested in odd numbers >= 3
bool[] c = new bool[limit];
for (int i = 3; i * 3 < limit; i += 2)
if (!c[i] && (chowla(i) == 0))
for (int j = 3 * i; j < limit; j += 2 * i)
c[j] = true;
return c;
}
static void Main(string[] args)
{
for (int i = 1; i <= 37; i++)
Console.WriteLine("chowla({0}) = {1}", i, chowla(i));
int count = 1, limit = (int)(1e7), power = 100;
bool[] c = sieve(limit);
for (int i = 3; i < limit; i += 2)
{
if (!c[i]) count++;
if (i == power - 1)
{
Console.WriteLine("Count of primes up to {0,10:n0} = {1:n0}", power, count);
power *= 10;
}
}
count = 0; limit = 35000000;
int k = 2, kk = 3, p;
for (int i = 2; ; i++)
{
if ((p = k * kk) > limit) break;
if (chowla(p) == p - 1)
{
Console.WriteLine("{0,10:n0} is a number that is perfect", p);
count++;
}
k = kk + 1; kk += k;
}
Console.WriteLine("There are {0} perfect numbers <= 35,000,000", count);
if (System.Diagnostics.Debugger.IsAttached) Console.ReadKey();
}
}
} |
http://rosettacode.org/wiki/Church_numerals | Church numerals | Task
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
Church one applies its first argument f just once to its second argument x, yielding f(x)
Church two applies its first argument f twice to its second argument x, yielding f(f(x))
and each successive Church numeral applies its first argument one additional time to its second argument, f(f(f(x))), f(f(f(f(x)))) ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument.
Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals.
In your language define:
Church Zero,
a Church successor function (a function on a Church numeral which returns the next Church numeral in the series),
functions for Addition, Multiplication and Exponentiation over Church numerals,
a function to convert integers to corresponding Church numerals,
and a function to convert Church numerals to corresponding integers.
You should:
Derive Church numerals three and four in terms of Church zero and a Church successor function.
use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4,
similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function,
convert each result back to an integer, and return it or print it to the console.
| #Haskell | Haskell | import Unsafe.Coerce ( unsafeCoerce )
type Church a = (a -> a) -> a -> a
churchZero :: Church a
churchZero = const id
churchOne :: Church a
churchOne = id
succChurch :: Church a -> Church a
succChurch = (<*>) (.) -- add one recursion, or \ ch f -> f . ch f
addChurch :: Church a -> Church a -> Church a
addChurch = (<*>). fmap (.) -- or \ ach bch f -> ach f . bch f
multChurch :: Church a -> Church a -> Church a
multChurch = (.) -- or \ ach bch -> ach . bch
expChurch :: Church a -> Church a -> Church a
expChurch basech expch = unsafeCoerce expch basech
isChurchZero :: Church a -> Church a
isChurchZero ch = unsafeCoerce ch (const churchZero) churchOne
predChurch :: Church a -> Church a
predChurch ch f x = unsafeCoerce ch (\ g h -> h (g f)) (const x) id
minusChurch :: Church a -> Church a -> Church a
minusChurch ach bch = unsafeCoerce bch predChurch ach
-- counts the times divisor can be subtracted from dividend to zero...
divChurch :: Church a -> Church a -> Church a
divChurch dvdnd dvsr =
let divr n d =
(\ v -> v (const $ succChurch $ divr v d) -- if branch
churchZero -- else branch
) (minusChurch n d)
in divr (unsafeCoerce succChurch dvdnd) $ unsafeCoerce dvsr
churchFromInt :: Int -> Church a
churchFromInt 0 = churchZero
churchFromInt n = succChurch $ churchFromInt (n - 1)
-- Or as a fold:
-- churchFromInt n = foldr (.) id . replicate n
-- Or as an iterated application:
-- churchFromInt n = iterate succChurch churchZero !! n
intFromChurch :: Church Int -> Int
intFromChurch ch = ch succ 0
------------------------------------- TEST -------------------------------------
main :: IO ()
main = do
let [cThree, cFour, cEleven, cTwelve] = churchFromInt <$> [3, 4, 11, 12]
print $ fmap intFromChurch [ addChurch cThree cFour
, multChurch cThree cFour
, expChurch cFour cThree
, expChurch cThree cFour
, isChurchZero churchZero
, predChurch cFour
, minusChurch cEleven cThree
, divChurch cEleven cThree
, divChurch cTwelve cThree
] |
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.
| #D | D | import std.stdio;
class MyClass {
//constructor (not necessary if empty)
this() {}
void someMethod() {
variable = 1;
}
// getter method
@property int variable() const {
return variable_;
}
// setter method
@property int variable(int newVariable) {
return variable_ = newVariable;
}
private int variable_;
}
void main() {
// On default class instances are allocated on the heap
// The GC will manage their lifetime
auto obj = new MyClass();
// prints 'variable = 0', ints are initialized to 0 by default
writeln("variable = ", obj.variable);
// invoke the method
obj.someMethod();
// prints 'variable = 1'
writeln("variable = ", obj.variable);
// set the variable using setter method
obj.variable = 99;
// prints 'variable = 99'
writeln("variable = ", obj.variable);
} |
http://rosettacode.org/wiki/Cistercian_numerals | Cistercian numerals | Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999.
How they work
All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyphs representing the digits 1 through 9 are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:
The upper-right quadrant represents the ones place.
The upper-left quadrant represents the tens place.
The lower-right quadrant represents the hundreds place.
The lower-left quadrant represents the thousands place.
Please consult the following image for examples of Cistercian numerals showing each glyph: [1]
Task
Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).
Use the routine to show the following Cistercian numerals:
0
1
20
300
4000
5555
6789
And a number of your choice!
Notes
Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed — especially for text output.
See also
Numberphile - The Forgotten Number System
dcode.fr - Online Cistercian numeral converter
| #Phix | Phix | --
-- Define each digit as {up-down multiplier, left-right multiplier, char},
-- that is starting each drawing from line 1 or 7, column 3,
-- and with `/` and `\` being flipped below when necessary.
--
with javascript_semantics
constant ds = {{{0,0,'+'},{0,1,'-'},{0,2,'-'}}, -- 1
{{2,0,'+'},{2,1,'-'},{2,2,'-'}}, -- 2
{{0,0,'+'},{1,1,'\\'},{2,2,'\\'}}, -- 3
{{2,0,'+'},{1,1,'/'},{0,2,'/'}}, -- 4
{{2,0,'+'},{1,1,'/'},{0,2,'+'},
{0,0,'+'},{0,1,'-'}}, -- 5
{{0,2,'|'},{1,2,'|'},{2,2,'|'}}, -- 6
{{0,0,'+'},{0,1,'-'},{0,2,'+'},
{1,2,'|'},{2,2,'|'}}, -- 7
{{2,0,'+'},{2,1,'-'},{2,2,'+'},
{1,2,'|'},{0,2,'|'}}, -- 8
{{2,0,'+'},{2,1,'-'},{2,2,'+'},
{1,2,'|'},{0,2,'+'},
{0,1,'-'},{0,0,'+'}}} -- 9
function cdigit(sequence s, integer d, pos)
--
-- s is our canvas, 7 lines of 5 characters
-- d is the digit, 0..9
-- pos is 4..1 for bl,br,tl,tr (easier to say/see 'backwards')
--
if d then
integer ud = {+1,+1,-1,-1}[pos],
lr = {+1,-1,+1,-1}[pos],
l = {1,1,7,7}[pos]
sequence dset = ds[d]
for i=1 to length(dset) do
integer {udm, lrm, ch} = dset[i],
tf = find(ch,`/\`)
if tf and ud!=lr then ch=`\/`[tf] end if
s[l+ud*udm][3+lr*lrm] = ch
end for
end if
return s
end function
procedure cisterian(sequence n)
sequence res = {}
for i=1 to length(n) do
integer cn = n[i]
res = append(res,sprintf("%4d:",cn))
sequence s = repeat(" | ",7)
integer pos = 1
while cn do
s = cdigit(s, remainder(cn,10), pos)
pos += 1
cn = floor(cn/10)
end while
res &= s
end for
puts(1,join_by(res,8,10))
end procedure
cisterian({0,1,2,3,4,5,6,7,8,9,20, 300, 4000, 5555, 6789, 9394, 7922, 9999})
|
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)
| #Fortran | Fortran |
Dim As Integer i, j
Dim As Double minDist = 1^30
Dim As Double x(9), y(9), dist, mini, minj
Data 0.654682, 0.925557
Data 0.409382, 0.619391
Data 0.891663, 0.888594
Data 0.716629, 0.996200
Data 0.477721, 0.946355
Data 0.925092, 0.818220
Data 0.624291, 0.142924
Data 0.211332, 0.221507
Data 0.293786, 0.691701
Data 0.839186, 0.728260
For i = 0 To 9
Read x(i), y(i)
Next i
For i = 0 To 8
For j = i+1 To 9
dist = (x(i) - x(j))^2 + (y(i) - y(j))^2
If dist < minDist Then
minDist = dist
mini = i
minj = j
End If
Next j
Next i
Print "El par más cercano es "; mini; " y "; minj; " a una distancia de "; Sqr(minDist)
End
|
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
Goal
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: Multiple distinct objects
| #Lua | Lua |
funcs={}
for i=1,10 do
table.insert(funcs, function() return i*i end)
end
funcs[2]()
funcs[3]()
|
http://rosettacode.org/wiki/Circular_primes | Circular primes | Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not.
A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1.
For example:
R(2) = 11 and R(5) = 11111 are repunits.
Task
Find the first 19 circular primes.
If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes.
(Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can.
See also
Wikipedia article - Circular primes.
Wikipedia article - Repunit.
OEIS sequence A016114 - Circular primes.
| #Raku | Raku | sub isCircular(\n) {
return False unless n.is-prime;
my @circular = n.comb;
return False if @circular.min < @circular[0];
for 1 ..^ @circular -> $i {
return False unless .is-prime and $_ >= n given @circular.rotate($i).join;
}
True
}
say "The first 19 circular primes are:";
say ((2..*).hyper.grep: { isCircular $_ })[^19];
say "\nThe next 4 circular primes, in repunit format, are:";
loop ( my $i = 7, my $count = 0; $count < 4; $i++ ) {
++$count, say "R($i)" if (1 x $i).is-prime
}
use ntheory:from<Perl5> qw[is_prime];
say "\nRepunit testing:";
(5003, 9887, 15073, 25031, 35317, 49081).map: {
my $now = now;
say "R($_): Prime? ", ?is_prime("{1 x $_}"), " {(now - $now).fmt: '%.2f'}"
} |
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
| #AutoHotkey | AutoHotkey | CircleCenter(x1, y1, x2, y2, r){
d := sqrt((x2-x1)**2 + (y2-y1)**2)
x3 := (x1+x2)/2 , y3 := (y1+y2)/2
cx1 := x3 + sqrt(r**2-(d/2)**2)*(y1-y2)/d , cy1:= y3 + sqrt(r**2-(d/2)**2)*(x2-x1)/d
cx2 := x3 - sqrt(r**2-(d/2)**2)*(y1-y2)/d , cy2:= y3 - sqrt(r**2-(d/2)**2)*(x2-x1)/d
if (d = 0)
return "No circles can be drawn, points are identical"
if (d = r*2)
return "points are opposite ends of a diameter center = " cx1 "," cy1
if (d = r*2)
return "points are too far"
if (r <= 0)
return "radius is not valid"
if !(cx1 && cy1 && cx2 && cy2)
return "no solution"
return cx1 "," cy1 " & " cx2 "," cy2
} |
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).
| #ALGOL_68 | ALGOL 68 | BEGIN # Chinese Zodiac #
# returns s right-padded with blanks to w characters, or s if s is already at least w characters long #
PRIO PAD = 1;
OP PAD = ( STRING s, INT w )STRING:
BEGIN
STRING result := s;
WHILE ( ( UPB result + 1 ) - LWB s ) < w DO result +:= " " OD;
result
END # PAD # ;
[]STRING animal name = ( "Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake"
, "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"
);
[]STRING element name = ( "Wood", "Fire", "Earth", "Metal", "Water" );
[]INT test year = ( 1935, 1938, 1968, 1972, 1976, 1984, 1985, 2017 );
print( ( "year element animal aspect", newline ) );
FOR i FROM LWB test year TO UPB test year DO
INT year = test year[ i ];
STRING element = element name[ ( ( year - 4 ) MOD 10 OVER 2 ) + 1 ];
STRING animal = animal name[ ( year - 4 ) MOD 12 + 1 ];
STRING yy = IF ODD year THEN "Yin" ELSE "Yang" FI;
print( ( whole( year, -4 ), " ", element PAD 7, " ", animal PAD 7, " ", yy, newline ) )
OD
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. | #AutoHotkey | AutoHotkey | Cholesky_Decomposition(A){
L := [], n := A.Count()
L[1,1] := Sqrt(A[1,1])
loop % n {
k := A_Index
loop % n-1 {
i := A_Index+1
Sigma := 0, j := 0
while (++j <= k-1)
Sigma += L[i, j] * L[k, j]
L[i, k] := (A[i, k] - Sigma) / L[k, k]
Sigma := 0, j := 0
while (++j <= k-1)
Sigma += (L[k, j])**2
L[k, k] := Sqrt(A[k, k] - Sigma)
}
}
loop % n{
k := A_Index
loop % n
L[k, A_Index] := L[k, A_Index] ? L[k, A_Index] : 0
}
return L
}
ShowMatrix(L){
for r, obj in L{
row := ""
for c, v in obj
row .= Format("{:.3f}", v) ", "
output .= "[" trim(row, ", ") "]`n,"
}
return "[" Trim(output, "`n,") "]"
} |
http://rosettacode.org/wiki/Cheryl%27s_birthday | Cheryl's birthday | Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.
Cheryl gave them a list of ten possible dates:
May 15, May 16, May 19
June 17, June 18
July 14, July 16
August 14, August 15, August 17
Cheryl then tells Albert the month of birth, and Bernard the day (of the month) of birth.
1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.
2) Bernard: At first I don't know when Cheryl's birthday is, but I know now.
3) Albert: Then I also know when Cheryl's birthday is.
Task
Write a computer program to deduce, by successive elimination, Cheryl's birthday.
Related task
Sum and Product Puzzle
References
Wikipedia article of the same name.
Tuple Relational Calculus
| #11l | 11l | T Date
String month
Int day
F (month, day)
.month = month
.day = day
V dates = [Date(‘May’, 15), Date(‘May’, 16), Date(‘May’, 19), Date(‘June’, 17), Date(‘June’, 18),
Date(‘July’, 14), Date(‘July’, 16), Date(‘August’, 14), Date(‘August’, 15), Date(‘August’, 17)]
DefaultDict[Int, Set[String]] monthTable
L(date) dates
monthTable[date.day].add(date.month)
DefaultDict[String, Set[Int]] dayTable
L(date) dates
dayTable[date.month].add(date.day)
Set[String] possibleMonths
Set[Int] possibleDays
L(month, days) dayTable
I days.len > 1
possibleMonths.add(month)
L(month, days) dayTable
L(day) days
I monthTable[day].len == 1
possibleMonths.remove(month)
print(‘After first Albert's sentence, possible months are ’Array(possibleMonths).join(‘, ’)‘.’)
L(day, months) monthTable
I months.len > 1
possibleDays.add(day)
Set[Int] impossibleDays
L(day) possibleDays
I monthTable[day].intersection(possibleMonths).len > 1
impossibleDays.add(day)
L(day) impossibleDays
possibleDays.remove(day)
print(‘After Bernard's sentence, possible days are ’Array(possibleDays).join(‘, ’)‘.’)
Set[String] impossibleMonths
L(month) possibleMonths
I dayTable[month].intersection(possibleDays).len > 1
impossibleMonths.add(month)
L(month) impossibleMonths
possibleMonths.remove(month)
assert(possibleMonths.len == 1)
V month = possibleMonths.pop()
print(‘After second Albert's sentence, remaining month is ’month‘...’)
possibleDays = possibleDays.intersection(dayTable[month])
assert(possibleDays.len == 1)
V day = possibleDays.pop()
print(‘and thus remaining day is ’day‘.’)
print()
print(‘So birthday date is ’month‘ ’day‘.’) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.