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/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)
| #J | J | vecl =: +/"1&.:*: NB. length of each vector
dist =: <@:vecl@:({: -"1 }:)\ NB. calculate all distances among vectors
minpair=: ({~ > {.@($ #: I.@,)@:= <./@;)dist NB. find one pair of the closest points
closestpairbf =: (; vecl@:-/)@minpair NB. the pair and their distance |
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
| #Phixmonti | Phixmonti | def power2
dup *
enddef
getid power2 10 repeat
len for
dup rot swap get rot swap exec print " " print
endfor
nl
/# Another mode #/
len for
var i
i get i swap exec print " " print
endfor |
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
| #PHP | PHP | <?php
$funcs = array();
for ($i = 0; $i < 10; $i++) {
$funcs[] = function () use ($i) { return $i * $i; };
}
echo $funcs[3](), "\n"; // prints 9
?> |
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
| #Delphi | Delphi |
program Circles_of_given_radius_through_two_points;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Types,
System.Math;
const
Cases: array[0..9] of TPointF = ((
x: 0.1234;
y: 0.9876
), (
x: 0.8765;
y: 0.2345
), (
x: 0.0000;
y: 2.0000
), (
x: 0.0000;
y: 0.0000
), (
x: 0.1234;
y: 0.9876
), (
x: 0.1234;
y: 0.9876
), (
x: 0.1234;
y: 0.9876
), (
x: 0.8765;
y: 0.2345
), (
x: 0.1234;
y: 0.9876
), (
x: 0.1234;
y: 0.9876
));
radii: array of double = [2.0, 1.0, 2.0, 0.5, 0.0];
procedure FindCircles(p1, p2: TPointF; radius: double);
var
separation, mirrorDistance: double;
begin
separation := p1.Distance(p2);
if separation = 0.0 then
begin
if radius = 0 then
write(format(#10'No circles can be drawn through (%.4f,%.4f)', [p1.x, p1.y]))
else
write(format(#10'Infinitely many circles can be drawn through (%.4f,%.4f)',
[p1.x, p1.y]));
exit;
end;
if separation = 2 * radius then
begin
write(format(#10'Given points are opposite ends of a diameter of the circle with center (%.4f,%.4f) and radius %.4f',
[(p1.x + p2.x) / 2, (p1.y + p2.y) / 2, radius]));
exit;
end;
if separation > 2 * radius then
begin
write(format(#10'Given points are farther away from each other than a diameter of a circle with radius %.4f',
[radius]));
exit;
end;
mirrorDistance := sqrt(Power(radius, 2) - Power(separation / 2, 2));
write(#10'Two circles are possible.');
write(format(#10'Circle C1 with center (%.4f,%.4f), radius %.4f and Circle C2 with center (%.4f,%.4f), radius %.4f',
[(p1.x + p2.x) / 2 + mirrorDistance * (p1.y - p2.y) / separation, (p1.y + p2.y)
/ 2 + mirrorDistance * (p2.x - p1.x) / separation, radius, (p1.x + p2.x) / 2
- mirrorDistance * (p1.y - p2.y) / separation, (p1.y + p2.y) / 2 -
mirrorDistance * (p2.x - p1.x) / separation, radius]));
end;
begin
for var i := 0 to 4 do
begin
write(#10'Case ', i + 1,')');
findCircles(cases[2 * i], cases[2 * i + 1], radii[i]);
end;
readln;
end. |
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Tuesday, February 1, 2022 CE (in the common Gregorian calendar) will begin the lunisolar Year of the Tiger.
The celestial stems have no one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems each belong to one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element's governance is associated with yin, the other with yang.
Thus, 2022 is also the yang year of Water. Note that since 12 is an even number, the association between animals and yin/yang doesn't change. Consecutive Years of the Rooster will cycle through the five elements, but will always be yin, despite the apparent conceptual mismatch between the specifically-male English animal name and the female aspect denoted by yin.
Task
Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.
You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).
Requisite information
The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.
The element cycle runs in this order: Wood, Fire, Earth, Metal, Water.
The yang year precedes the yin year within each element.
The current 60-year cycle began in 1984 CE; the first cycle of the Common Era began in 4 CE.
Thus, 1984 was the year of the Wood Rat (yang), 1985 was the year of the Wood Ox (yin), and 1986 the year of the Fire Tiger (yang); 2022 - which, as already noted, is the year of the Water Tiger (yang) - is the 39th year of the current cycle.
Information for optional task
The ten celestial stems are 甲 jiă, 乙 yĭ, 丙 bĭng, 丁 dīng, 戊 wù, 己 jĭ, 庚 gēng, 辛 xīn, 壬 rén, and 癸 gŭi. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3".
The twelve terrestrial branches are 子 zĭ, 丑 chŏu, 寅 yín, 卯 măo, 辰 chén, 巳 sì, 午 wŭ, 未 wèi, 申 shēn, 酉 yŏu, 戌 xū, 亥 hài. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4".
Therefore 1984 was 甲子 (jiă-zĭ, or jia3-zi3). 2022 is 壬寅 (rén-yín or ren2-yin2).
| #C.2B.2B | C++ | #include <iostream>
#include <cmath>
using namespace std;
const string animals[]={"Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig"};
const string elements[]={"Wood","Fire","Earth","Metal","Water"};
string getElement(int year)
{
int element = floor((year-4)%10/2);
return elements[element];
}
string getAnimal(int year)
{
return animals[(year-4)%12];
}
string getYY(int year)
{
if(year%2==0)
{
return "yang";
}
else
{
return "yin";
}
}
int main()
{
int years[]={1935,1938,1968,1972,1976,2017};
//the zodiac cycle didnt start until 4 CE, so years <4 shouldnt be valid
for(int i=0;i<6;i++)
{
cout << years[i] << " is the year of the " << getElement(years[i]) << " " << getAnimal(years[i]) << " (" << getYY(years[i]) << ")." << endl;
}
return 0;
} |
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an unusual filename: `Abdu'l-Bahá.txt
| #Amazing_Hopper | Amazing Hopper |
#include <flow.h>
DEF-MAIN(argv, argc)
WHEN( IS-FILE?("hopper") ){
MEM("File \"hopper\" exist!\n")
}
WHEN( IS-DIR?("fl") ){
MEM("Directory \"fl\" exist!\n")
}
IF( IS-DIR?("noExisDir"), "Directory \"noExistDir\" exist!\n", \
"Directory \"noExistDir\" does NOT exist!\n" )
//"arch mañoso bacán.txt" text-file created
STR-TO-UTF8("File \"arch mañoso bacán.txt\" ")
IF( IS-FILE?( STR-TO-UTF8("arch mañoso bacán.txt") ), "exist!\n", "NOT exist!\n")
PRNL
END
|
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an unusual filename: `Abdu'l-Bahá.txt
| #APL | APL |
h ← ⎕fio['fopen'] 'input.txt'
h
7
⎕fio['fstat'] h
66311 803134 33188 1 1000 1000 0 11634 4096 24 1642047105 1642047105 1642047105
⎕fio['fclose'] h
0
h ← ⎕fio['fopen'] 'docs/'
h
7
⎕fio['fstat'] h
66311 3296858 16877 2 1000 1000 0 4096 4096 8 1642047108 1642047108 1642047108
⎕fio['fclose'] h
0
h ← ⎕fio['fopen'] 'does_not_exist.txt'
h
¯1
|
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Perl | Perl | $ perl -e "warn -t STDOUT ? 'Terminal' : 'Other'"
Terminal
$ perl -e "warn -t STDOUT ? 'Terminal' : 'Other'" > x.tmp
Other
|
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Phix | Phix | without js -- (no input or output redirection in a browser!)
printf(1,"stdin:%t, stdout:%t, stderr:%t\n",{isatty(0),isatty(1),isatty(2)})
|
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #PHP | PHP |
if(posix_isatty(STDOUT)) {
echo "The output device is a terminal".PHP_EOL;
} else {
echo "The output device is NOT a terminal".PHP_EOL;
}
|
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Python | Python | from sys import stdout
if stdout.isatty():
print 'The output device is a teletype. Or something like a teletype.'
else:
print 'The output device isn\'t like a teletype.' |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Quackery | Quackery | [ $ |from sys import stdout
to_stack( 1 if stdout.isatty() else 0)|
python ] is ttyout ( --> b )
ttyout if
[ say "Looks like a teletype." ]
else
[ say "Not a teletype." ] |
http://rosettacode.org/wiki/Check_Machin-like_formulas | Check Machin-like formulas | Machin-like formulas are useful for efficiently computing numerical approximations for
π
{\displaystyle \pi }
Task
Verify the following Machin-like formulas are correct by calculating the value of tan (right hand side) for each equation using exact arithmetic and showing they equal 1:
π
4
=
arctan
1
2
+
arctan
1
3
{\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 3}}
π
4
=
2
arctan
1
3
+
arctan
1
7
{\displaystyle {\pi \over 4}=2\arctan {1 \over 3}+\arctan {1 \over 7}}
π
4
=
4
arctan
1
5
−
arctan
1
239
{\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 239}}
π
4
=
5
arctan
1
7
+
2
arctan
3
79
{\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+2\arctan {3 \over 79}}
π
4
=
5
arctan
29
278
+
7
arctan
3
79
{\displaystyle {\pi \over 4}=5\arctan {29 \over 278}+7\arctan {3 \over 79}}
π
4
=
arctan
1
2
+
arctan
1
5
+
arctan
1
8
{\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 5}+\arctan {1 \over 8}}
π
4
=
4
arctan
1
5
−
arctan
1
70
+
arctan
1
99
{\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 70}+\arctan {1 \over 99}}
π
4
=
5
arctan
1
7
+
4
arctan
1
53
+
2
arctan
1
4443
{\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+4\arctan {1 \over 53}+2\arctan {1 \over 4443}}
π
4
=
6
arctan
1
8
+
2
arctan
1
57
+
arctan
1
239
{\displaystyle {\pi \over 4}=6\arctan {1 \over 8}+2\arctan {1 \over 57}+\arctan {1 \over 239}}
π
4
=
8
arctan
1
10
−
arctan
1
239
−
4
arctan
1
515
{\displaystyle {\pi \over 4}=8\arctan {1 \over 10}-\arctan {1 \over 239}-4\arctan {1 \over 515}}
π
4
=
12
arctan
1
18
+
8
arctan
1
57
−
5
arctan
1
239
{\displaystyle {\pi \over 4}=12\arctan {1 \over 18}+8\arctan {1 \over 57}-5\arctan {1 \over 239}}
π
4
=
16
arctan
1
21
+
3
arctan
1
239
+
4
arctan
3
1042
{\displaystyle {\pi \over 4}=16\arctan {1 \over 21}+3\arctan {1 \over 239}+4\arctan {3 \over 1042}}
π
4
=
22
arctan
1
28
+
2
arctan
1
443
−
5
arctan
1
1393
−
10
arctan
1
11018
{\displaystyle {\pi \over 4}=22\arctan {1 \over 28}+2\arctan {1 \over 443}-5\arctan {1 \over 1393}-10\arctan {1 \over 11018}}
π
4
=
22
arctan
1
38
+
17
arctan
7
601
+
10
arctan
7
8149
{\displaystyle {\pi \over 4}=22\arctan {1 \over 38}+17\arctan {7 \over 601}+10\arctan {7 \over 8149}}
π
4
=
44
arctan
1
57
+
7
arctan
1
239
−
12
arctan
1
682
+
24
arctan
1
12943
{\displaystyle {\pi \over 4}=44\arctan {1 \over 57}+7\arctan {1 \over 239}-12\arctan {1 \over 682}+24\arctan {1 \over 12943}}
π
4
=
88
arctan
1
172
+
51
arctan
1
239
+
32
arctan
1
682
+
44
arctan
1
5357
+
68
arctan
1
12943
{\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12943}}
and confirm that the following formula is incorrect by showing tan (right hand side) is not 1:
π
4
=
88
arctan
1
172
+
51
arctan
1
239
+
32
arctan
1
682
+
44
arctan
1
5357
+
68
arctan
1
12944
{\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12944}}
These identities are useful in calculating the values:
tan
(
a
+
b
)
=
tan
(
a
)
+
tan
(
b
)
1
−
tan
(
a
)
tan
(
b
)
{\displaystyle \tan(a+b)={\tan(a)+\tan(b) \over 1-\tan(a)\tan(b)}}
tan
(
arctan
a
b
)
=
a
b
{\displaystyle \tan \left(\arctan {a \over b}\right)={a \over b}}
tan
(
−
a
)
=
−
tan
(
a
)
{\displaystyle \tan(-a)=-\tan(a)}
You can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input.
Note: to formally prove the formula correct, it would have to be shown that
−
3
p
i
4
{\displaystyle {-3pi \over 4}}
< right hand side <
5
p
i
4
{\displaystyle {5pi \over 4}}
due to
tan
(
)
{\displaystyle \tan()}
periodicity.
| #Clojure | Clojure | (ns tanevaulator
(:gen-class))
;; Notation: [a b c] -> a x arctan(a/b)
(def test-cases [
[[1, 1, 2], [1, 1, 3]],
[[2, 1, 3], [1, 1, 7]],
[[4, 1, 5], [-1, 1, 239]],
[[5, 1, 7], [2, 3, 79]],
[[1, 1, 2], [1, 1, 5], [1, 1, 8]],
[[4, 1, 5], [-1, 1, 70], [1, 1, 99]],
[[5, 1, 7], [4, 1, 53], [2, 1, 4443]],
[[6, 1, 8], [2, 1, 57], [1, 1, 239]],
[[8, 1, 10], [-1, 1, 239], [-4, 1, 515]],
[[12, 1, 18], [8, 1, 57], [-5, 1, 239]],
[[16, 1, 21], [3, 1, 239], [4, 3, 1042]],
[[22, 1, 28], [2, 1, 443], [-5, 1, 1393], [-10, 1, 11018]],
[[22, 1, 38], [17, 7, 601], [10, 7, 8149]],
[[44, 1, 57], [7, 1, 239], [-12, 1, 682], [24, 1, 12943]],
[[88, 1, 172], [51, 1, 239], [32, 1, 682], [44, 1, 5357], [68, 1, 12943]],
[[88, 1, 172], [51, 1, 239], [32, 1, 682], [44, 1, 5357], [68, 1, 12944]]
])
(defn tan-sum [a b]
" tan (a + b) "
(/ (+ a b) (- 1 (* a b))))
(defn tan-eval [m]
" Evaluates tan of a triplet (e.g. [1, 1, 2])"
(let [coef (first m)
rat (/ (nth m 1) (nth m 2))]
(cond
(= 1 coef) rat
(neg? coef) (tan-eval [(- (nth m 0)) (- (nth m 1)) (nth m 2)])
:else (let [
ca (quot coef 2)
cb (- coef ca)
a (tan-eval [ca (nth m 1) (nth m 2)])
b (tan-eval [cb (nth m 1) (nth m 2)])]
(tan-sum a b)))))
(defn tans [m]
" Evaluates tan of set of triplets (e.g. [[1, 1, 2], [1, 1, 3]])"
(if (= 1 (count m))
(tan-eval (nth m 0))
(let [a (tan-eval (first m))
b (tans (rest m))]
(tan-sum a b))))
(doseq [q test-cases]
" Display results "
(println "tan " q " = "(tans q)))
|
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #360_Assembly | 360 Assembly | * Character codes EBCDIC 15/02/2017
CHARCODE CSECT
USING CHARCODE,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) " <-
ST R15,8(R13) " ->
LR R13,R15 " addressability
* Character to Decimal
SR R1,R1 r1=0
IC R1,=C'a' insert character 'a'
XDECO R1,PG
XPRNT PG,L'PG print -> 129
* Hexadecimal to character
SR R1,R1 r1=0
IC R1,=X'81' insert character X'81'
STC R1,CHAR store character r1
XPRNT CHAR,L'CHAR print -> 'a'
* Decimal to character
LH R1,=H'129' r1=129
STC R1,CHAR store character r1
XPRNT CHAR,L'CHAR print -> 'a'
*
XDUMP CHAR,L'CHAR dump -> X'81'
*
RETURN L R13,4(0,R13) epilog
LM R14,R12,12(R13) " restore
XR R15,R15 " rc=0
BR R14 exit
PG DS CL12
CHAR DS CL1
YREGS
END CHARCODE |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #68000_Assembly | 68000 Assembly | JSR ResetCoords ;RESET TYPING CURSOR
MOVE.B #'A',D1
MOVE.W #25,D2
MOVE.B #0,(softCarriageReturn) ;new line takes the cursor to left edge of screen.
jsr PrintAllTheCodes
jsr ResetCoords
MOVE.B #8,(Cursor_X)
MOVE.B #'a',D1
MOVE.W #25,D2
MOVE.B #8,(softCarriageReturn)
;set the writing cursor to column 3 of the screen
;so we don't erase the old output.
jsr PrintAllTheCodes
forever:
bra forever
PrintAllTheCodes:
MOVE.B D1,D0
jsr PrintChar ;print the character as-is
MOVE.B #" ",D0
jsr PrintChar
MOVE.B #"=",D0
jsr PrintChar
MOVE.B #" ",D0
jsr PrintChar
MOVE.B D1,D0 ;get ready to print the code
JSR UnpackNibbles8
SWAP D0
ADD.B #$30,D0
JSR PrintChar
SWAP D0
CMP.B #10,D0
BCS noCorrectHex
ADD.B #$07,D0
noCorrectHex:
ADD.B #$30,D0
JSR PrintChar
MOVE.B (softCarriageReturn),D0
JSR doNewLine2 ;new line, with D0 as the carraige return point.
ADDQ.B #1,D1
DBRA D2,PrintAllTheCodes
rts
UnpackNibbles8:
; INPUT: D0 = THE VALUE YOU WISH TO UNPACK.
; HIGH NIBBLE IN HIGH WORD OF D0, LOW NIBBLE IN LOW WORD. SWAP D0 TO GET THE OTHER HALF.
pushWord D1
CLR.W D1
MOVE.B D0,D1
CLR.L D0
MOVE.B D1,D0 ;now D0 = D1 = $000000II, where I = input
AND.B #$F0,D0 ;chop off bottom nibble
LSR.B #4,D0 ;downshift top nibble into bottom nibble of the word
SWAP D0 ;store in high word
AND.B #$0F,D1 ;chop off bottom nibble
MOVE.B D1,D0 ;store in low word
popWord D1
rts |
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. | #Delphi | Delphi | function Cholesky(a : array of Float) : array of Float;
var
i, j, k, n : Integer;
s : Float;
begin
n:=Round(Sqrt(a.Length));
Result:=new Float[n*n];
for i:=0 to n-1 do begin
for j:=0 to i do begin
s:=0 ;
for k:=0 to j-1 do
s+=Result[i*n+k] * Result[j*n+k];
if i=j then
Result[i*n+j]:=Sqrt(a[i*n+i]-s)
else Result[i*n+j]:=1/Result[j*n+j]*(a[i*n+j]-s);
end;
end;
end;
procedure ShowMatrix(a : array of Float);
var
i, j, n : Integer;
begin
n:=Round(Sqrt(a.Length));
for i:=0 to n-1 do begin
for j:=0 to n-1 do
Print(Format('%2.5f ', [a[i*n+j]]));
PrintLn('');
end;
end;
var m1 := new Float[9];
m1 := [ 25.0, 15.0, -5.0,
15.0, 18.0, 0.0,
-5.0, 0.0, 11.0 ];
var c1 := Cholesky(m1);
ShowMatrix(c1);
PrintLn('');
var m2 : array of Float := [ 18.0, 22.0, 54.0, 42.0,
22.0, 70.0, 86.0, 62.0,
54.0, 86.0, 174.0, 134.0,
42.0, 62.0, 134.0, 106.0 ];
var c2 := Cholesky(m2);
ShowMatrix(c2); |
http://rosettacode.org/wiki/Check_input_device_is_a_terminal | Check input device is a terminal | Task
Demonstrate how to check whether the input device is a terminal or not.
Related task
Check output device is a terminal
| #Ring | Ring |
# Project : Check input device is a terminal
load "stdlib.ring"
if isWindows()
write("mycmd.bat","
@echo off
timeout 1 2>nul >nul
if errorlevel 1 (
echo input redirected
) else (
echo input is console
)
")
see SystemCmd("mycmd.bat")
ok
|
http://rosettacode.org/wiki/Check_input_device_is_a_terminal | Check input device is a terminal | Task
Demonstrate how to check whether the input device is a terminal or not.
Related task
Check output device is a terminal
| #Ruby | Ruby | File.new("testfile").isatty #=> false
File.new("/dev/tty").isatty #=> true |
http://rosettacode.org/wiki/Check_input_device_is_a_terminal | Check input device is a terminal | Task
Demonstrate how to check whether the input device is a terminal or not.
Related task
Check output device is a terminal
| #Rust | Rust | /* Uses C library interface */
extern crate libc;
fn main() {
let istty = unsafe { libc::isatty(libc::STDIN_FILENO as i32) } != 0;
if istty {
println!("stdout is tty");
} else {
println!("stdout is not tty");
}
} |
http://rosettacode.org/wiki/Check_input_device_is_a_terminal | Check input device is a terminal | Task
Demonstrate how to check whether the input device is a terminal or not.
Related task
Check output device is a terminal
| #Scala | Scala | import org.fusesource.jansi.internal.CLibrary._
object IsATty extends App {
var enabled = true
def apply(enabled: Boolean): Boolean = {
// We must be on some unix variant..
try {
enabled && isatty(STDIN_FILENO) == 1
}
catch {
case ignore: Throwable =>
ignore.printStackTrace()
false
}
}
println("tty " + apply(true))
} |
http://rosettacode.org/wiki/Check_input_device_is_a_terminal | Check input device is a terminal | Task
Demonstrate how to check whether the input device is a terminal or not.
Related task
Check output device is a terminal
| #Standard_ML | Standard ML | val stdinRefersToTerminal : bool = Posix.ProcEnv.isatty Posix.FileSys.stdin |
http://rosettacode.org/wiki/Check_input_device_is_a_terminal | Check input device is a terminal | Task
Demonstrate how to check whether the input device is a terminal or not.
Related task
Check output device is a terminal
| #Tcl | Tcl | if {[catch {fconfigure stdin -mode}]} {
puts "Input doesn't come from tty."
} else {
puts "Input comes from tty."
} |
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
| #C.23 | C# | public static class CherylsBirthday
{
public static void Main() {
var dates = new HashSet<(string month, int day)> {
("May", 15),
("May", 16),
("May", 19),
("June", 17),
("June", 18),
("July", 14),
("July", 16),
("August", 14),
("August", 15),
("August", 17)
};
Console.WriteLine(dates.Count + " remaining.");
//The month cannot have a unique day.
var monthsWithUniqueDays = dates.GroupBy(d => d.day).Where(g => g.Count() == 1).Select(g => g.First().month).ToHashSet();
dates.RemoveWhere(d => monthsWithUniqueDays.Contains(d.month));
Console.WriteLine(dates.Count + " remaining.");
//The day must now be unique.
dates.IntersectWith(dates.GroupBy(d => d.day).Where(g => g.Count() == 1).Select(g => g.First()));
Console.WriteLine(dates.Count + " remaining.");
//The month must now be unique.
dates.IntersectWith(dates.GroupBy(d => d.month).Where(g => g.Count() == 1).Select(g => g.First()));
Console.WriteLine(dates.Single());
}
} |
http://rosettacode.org/wiki/Checkpoint_synchronization | Checkpoint synchronization | The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before starting another one. Putting details together is the checkpoint at which tasks synchronize themselves before going their paths apart.
The task
Implement checkpoint synchronization in your language.
Make sure that the solution is race condition-free. Note that a straightforward solution based on events is exposed to race condition. Let two tasks A and B need to be synchronized at a checkpoint. Each signals its event (EA and EB correspondingly), then waits for the AND-combination of the events (EA&EB) and resets its event. Consider the following scenario: A signals EA first and gets blocked waiting for EA&EB. Then B signals EB and loses the processor. Then A is released (both events are signaled) and resets EA. Now if B returns and enters waiting for EA&EB, it gets lost.
When a worker is ready it shall not continue before others finish. A typical implementation bug is when a worker is counted twice within one working cycle causing its premature completion. This happens when the quickest worker serves its cycle two times while the laziest one is lagging behind.
If you can, implement workers joining and leaving.
| #Go | Go | package main
import (
"log"
"math/rand"
"sync"
"time"
)
func worker(part string) {
log.Println(part, "worker begins part")
time.Sleep(time.Duration(rand.Int63n(1e6)))
log.Println(part, "worker completes part")
wg.Done()
}
var (
partList = []string{"A", "B", "C", "D"}
nAssemblies = 3
wg sync.WaitGroup
)
func main() {
rand.Seed(time.Now().UnixNano())
for c := 1; c <= nAssemblies; c++ {
log.Println("begin assembly cycle", c)
wg.Add(len(partList))
for _, part := range partList {
go worker(part)
}
wg.Wait()
log.Println("assemble. cycle", c, "complete")
}
} |
http://rosettacode.org/wiki/Checkpoint_synchronization | Checkpoint synchronization | The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before starting another one. Putting details together is the checkpoint at which tasks synchronize themselves before going their paths apart.
The task
Implement checkpoint synchronization in your language.
Make sure that the solution is race condition-free. Note that a straightforward solution based on events is exposed to race condition. Let two tasks A and B need to be synchronized at a checkpoint. Each signals its event (EA and EB correspondingly), then waits for the AND-combination of the events (EA&EB) and resets its event. Consider the following scenario: A signals EA first and gets blocked waiting for EA&EB. Then B signals EB and loses the processor. Then A is released (both events are signaled) and resets EA. Now if B returns and enters waiting for EA&EB, it gets lost.
When a worker is ready it shall not continue before others finish. A typical implementation bug is when a worker is counted twice within one working cycle causing its premature completion. This happens when the quickest worker serves its cycle two times while the laziest one is lagging behind.
If you can, implement workers joining and leaving.
| #Haskell | Haskell | import Control.Parallel
data Task a = Idle | Make a
type TaskList a = [a]
type Results a = [a]
type TaskGroups a = [TaskList a]
type WorkerList a = [Worker a]
type Worker a = [Task a]
-- run tasks in parallel and collect their results
-- the function doesn't return until all tasks are done, therefore
-- finished threads wait for the others to finish.
runTasks :: TaskList a -> Results a
runTasks [] = []
runTasks (x:[]) = x : []
runTasks (x:y:[]) = y `par` x : y : []
runTasks (x:y:ys) = y `par` x : y : runTasks ys
-- take a list of workers with different numbers of tasks and group
-- them: first the first task of each worker, then the second one etc.
groupTasks :: WorkerList a -> TaskGroups a
groupTasks [] = []
groupTasks xs
| allWorkersIdle xs = []
| otherwise =
concatMap extractTask xs : groupTasks (map removeTask xs)
-- return a task as a plain value
extractTask :: Worker a -> [a]
extractTask [] = []
extractTask (Idle:_) = []
extractTask (Make a:_) = [a]
-- remove the foremost task of each worker
removeTask :: Worker a -> Worker a
removeTask = drop 1
-- checks whether all workers are idle in this task
allWorkersIdle :: WorkerList a -> Bool
allWorkersIdle = all null . map extractTask
-- the workers must calculate big sums. the first sum of each worker
-- belongs to the first task, and so on.
-- because of laziness, nothing is computed yet.
-- worker1 has 5 tasks to do
worker1 :: Worker Integer
worker1 = map Make [ sum [1..n*1000000] | n <- [1..5] ]
-- worker2 has 4 tasks to do
worker2 :: Worker Integer
worker2 = map Make [ sum [1..n*100000] | n <- [1..4] ]
-- worker3 has 3 tasks to do
worker3 :: Worker Integer
worker3 = map Make [ sum [1..n*1000000] | n <- [1..3] ]
-- worker4 has 5 tasks to do
worker4 :: Worker Integer
worker4 = map Make [ sum [1..n*300000] | n <- [1..5] ]
-- worker5 has 4 tasks to do, but starts at the second task.
worker5 :: Worker Integer
worker5 = [Idle] ++ map Make [ sum [1..n*400000] | n <- [1..4] ]
-- group the workers' tasks
tasks :: TaskGroups Integer
tasks = groupTasks [worker1, worker2, worker3, worker4, worker5]
-- a workshop: take a function to operate the results and a group of tasks,
-- execute the tasks showing the process and process the results
workshop :: (Show a, Num a, Show b, Num b) => ([a] -> b) -> [[a]] -> IO ()
workshop func a = mapM_ doWork $ zip [1..length a] a
where
doWork (x, y) = do
putStrLn $ "Doing task " ++ show x ++ "."
putStrLn $ "There are " ++ show (length y) ++ " workers for this task."
putStrLn "Waiting for all workers..."
print $ func $ runTasks y
putStrLn $ "Task " ++ show x ++ " done."
main = workshop sum tasks
|
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
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
'create fixed size array of integers
Dim a(1 To 5) As Integer = {1, 2, 3, 4, 5}
Print a(2), a(4)
'create empty dynamic array of doubles
Dim b() As Double
' add two elements by first redimensioning the array to hold this number of elements
Redim b(0 To 1)
b(0) = 3.5 : b(1) = 7.1
Print b(0), b(1)
'create 2 dimensional fixed size array of bytes
Dim c(1 To 2, 1 To 2) As Byte = {{1, 2}, {3, 4}}
Print c(1, 1), c(2,2)
Sleep |
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
| #Maple | Maple | > combinat:-choose( 5, 3 );
[[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5],
[2, 4, 5], [3, 4, 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.
| #Racket | Racket |
(if (< x 10)
"small"
"big")
|
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}}}
.
| #Coffeescript | Coffeescript | crt = (n,a) ->
sum = 0
prod = n.reduce (a,c) -> a*c
for [ni,ai] in _.zip n,a
p = prod // ni
sum += ai * p * mulInv p,ni
sum % prod
mulInv = (a,b) ->
b0 = b
[x0,x1] = [0,1]
if b==1 then return 1
while a > 1
q = a // b
[a,b] = [b, a % b]
[x0,x1] = [x1-q*x0, x0]
if x1 < 0 then x1 += b0
x1
print crt [3,5,7], [2,3,2] |
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
| #Sidef | Sidef | func chernick_carmichael_factors (n, m) {
[6*m + 1, 12*m + 1, {|i| 2**i * 9*m + 1 }.map(1 .. n-2)...]
}
func is_chernick_carmichael (n, m) {
(n == 2) ? (is_prime(6*m + 1) && is_prime(12*m + 1))
: (is_prime(2**(n-2) * 9*m + 1) && __FUNC__(n-1, m))
}
func chernick_carmichael_number(n, callback) {
var multiplier = (n>4 ? 2**(n-4) : 1)
var m = (1..Inf -> first {|m| is_chernick_carmichael(n, m * multiplier) })
var f = chernick_carmichael_factors(n, m * multiplier)
callback(f...)
}
for n in (3..9) {
chernick_carmichael_number(n, {|*f| say "a(#{n}) = #{f.join(' * ')}" })
} |
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
| #Wren | Wren | import "/big" for BigInt, BigInts
import "/fmt" for Fmt
var min = 3
var max = 9
var prod = BigInt.zero
var fact = BigInt.zero
var factors = List.filled(max, 0)
var bigFactors = List.filled(max, null)
var init = Fn.new {
for (i in 0...max) bigFactors[i] = BigInt.zero
}
var isPrimePretest = Fn.new { |k|
if (k%3 == 0 || k%5 == 0 || k%7 == 0 || k%11 == 0 ||
(k%13 == 0) || k%17 == 0 || k%19 == 0 || k%23 == 0) return k <= 23
return true
}
var ccFactors = Fn.new { |n, m|
if (!isPrimePretest.call(6*m + 1)) return false
if (!isPrimePretest.call(12*m + 1)) return false
factors[0] = 6*m + 1
factors[1] = 12*m + 1
var t = 9 * m
var i = 1
while (i <= n-2) {
var tt = (t << i) + 1
if (!isPrimePretest.call(tt)) return false
factors[i+1] = tt
i = i + 1
}
for (i in 0...n) {
fact = BigInt.new(factors[i])
if (!fact.isProbablePrime(1)) return false
bigFactors[i] = fact
}
return true
}
var ccNumbers = Fn.new { |start, end|
for (n in start..end) {
var mult = 1
if (n > 4) mult = 1 << (n - 4)
if (n > 5) mult = mult * 5
var m = mult
while (true) {
if (ccFactors.call(n, m)) {
var num = BigInts.prod(bigFactors.take(n))
Fmt.print("a($d) = $i", n, num)
Fmt.print("m($d) = $d", n, m)
Fmt.print("Factors: $n\n", factors[0...n])
break
}
m = m + mult
}
}
}
init.call()
ccNumbers.call(min, max) |
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.
| #Groovy | Groovy | class Chowla {
static int chowla(int n) {
if (n < 1) throw new RuntimeException("argument must be a positive integer")
int sum = 0
int i = 2
while (i * i <= n) {
if (n % i == 0) {
int j = (int) (n / i)
sum += (i == j) ? i : i + j
}
i++
}
return sum
}
static boolean[] sieve(int limit) {
// True denotes composite, false denotes prime.
// Only interested in odd numbers >= 3
boolean[] c = new boolean[limit]
for (int i = 3; i < limit / 3; 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++) {
printf("chowla(%2d) = %d\n", i, chowla(i))
}
println()
int count = 1
int limit = 10_000_000
boolean[] c = sieve(limit)
int power = 100
for (int i = 3; i < limit; i += 2) {
if (!c[i]) {
count++
}
if (i == power - 1) {
printf("Count of primes up to %,10d = %,7d\n", power, count)
power *= 10
}
}
println()
count = 0
limit = 35_000_000
int i = 2
while (true) {
int p = (1 << (i - 1)) * ((1 << i) - 1) // perfect numbers must be of this form
if (p > limit) break
if (chowla(p) == p - 1) {
printf("%,d is a perfect number\n", p)
count++
}
i++
}
printf("There are %,d perfect numbers <= %,d\n", count, limit)
}
} |
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.
| #Perl | Perl | use 5.020;
use feature qw<signatures>;
no warnings qw<experimental::signatures>;
use constant zero => sub ($f) {
sub ($x) { $x }};
use constant succ => sub ($n) {
sub ($f) {
sub ($x) { $f->($n->($f)($x)) }}};
use constant add => sub ($n) {
sub ($m) {
sub ($f) {
sub ($x) { $m->($f)($n->($f)($x)) }}}};
use constant mult => sub ($n) {
sub ($m) {
sub ($f) {
sub ($x) { $m->($n->($f))($x) }}}};
use constant power => sub ($b) {
sub ($e) { $e->($b) }};
use constant countup => sub ($i) { $i + 1 };
use constant countdown => sub ($i) { $i == 0 ? zero : succ->( __SUB__->($i - 1) ) };
use constant to_int => sub ($f) { $f->(countup)->(0) };
use constant from_int => sub ($x) { countdown->($x) };
use constant three => succ->(succ->(succ->(zero)));
use constant four => from_int->(4);
say join ' ', map { to_int->($_) } (
add ->( three )->( four ),
mult ->( three )->( four ),
power->( four )->( three ),
power->( three )->( four ),
); |
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.
| #Fancy | Fancy | class MyClass {
read_slot: 'instance_var # creates getter method for @instance_var
@@class_var = []
def initialize {
# 'initialize' is the constructor method invoked during 'MyClass.new' by convention
@instance_var = 0
}
def some_method {
@instance_var = 1
@another_instance_var = "foo"
}
# define class methods: define a singleton method on the class object
def self class_method {
# ...
}
# you can also name the class object itself
def MyClass class_method {
# ...
}
}
myclass = MyClass new |
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.
| #Fantom | Fantom | class MyClass
{
// an instance variable
Int x
// a constructor, providing default value for instance variable
new make (Int x := 1)
{
this.x = x
}
// a method, return double the number x
public Int double ()
{
return 2 * x
}
}
class Main
{
public static Void main ()
{
a := MyClass (2) // instantiates the class, with x = 2
b := MyClass() // instantiates the class, x defaults to 1
c := MyClass { x = 3 } // instantiates the class, sets x to 3
}
} |
http://rosettacode.org/wiki/Closest-pair_problem | Closest-pair problem |
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a function to find the closest two points among a set of given points in two dimensions, i.e. to solve the Closest pair of points problem in the planar case.
The straightforward solution is a O(n2) algorithm (which we can call brute-force algorithm); the pseudo-code (using indexes) could be simply:
bruteForceClosestPair of P(1), P(2), ... P(N)
if N < 2 then
return ∞
else
minDistance ← |P(1) - P(2)|
minPoints ← { P(1), P(2) }
foreach i ∈ [1, N-1]
foreach j ∈ [i+1, N]
if |P(i) - P(j)| < minDistance then
minDistance ← |P(i) - P(j)|
minPoints ← { P(i), P(j) }
endif
endfor
endfor
return minDistance, minPoints
endif
A better algorithm is based on the recursive divide&conquer approach, as explained also at Wikipedia's Closest pair of points problem, which is O(n log n); a pseudo-code could be:
closestPair of (xP, yP)
where xP is P(1) .. P(N) sorted by x coordinate, and
yP is P(1) .. P(N) sorted by y coordinate (ascending order)
if N ≤ 3 then
return closest points of xP using brute-force algorithm
else
xL ← points of xP from 1 to ⌈N/2⌉
xR ← points of xP from ⌈N/2⌉+1 to N
xm ← xP(⌈N/2⌉)x
yL ← { p ∈ yP : px ≤ xm }
yR ← { p ∈ yP : px > xm }
(dL, pairL) ← closestPair of (xL, yL)
(dR, pairR) ← closestPair of (xR, yR)
(dmin, pairMin) ← (dR, pairR)
if dL < dR then
(dmin, pairMin) ← (dL, pairL)
endif
yS ← { p ∈ yP : |xm - px| < dmin }
nS ← number of points in yS
(closest, closestPair) ← (dmin, pairMin)
for i from 1 to nS - 1
k ← i + 1
while k ≤ nS and yS(k)y - yS(i)y < dmin
if |yS(k) - yS(i)| < closest then
(closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)})
endif
k ← k + 1
endwhile
endfor
return closest, closestPair
endif
References and further readings
Closest pair of points problem
Closest Pair (McGill)
Closest Pair (UCSB)
Closest pair (WUStL)
Closest pair (IUPUI)
| #Java | Java | import java.util.*;
public class ClosestPair
{
public static class Point
{
public final double x;
public final double y;
public Point(double x, double y)
{
this.x = x;
this.y = y;
}
public String toString()
{ return "(" + x + ", " + y + ")"; }
}
public static class Pair
{
public Point point1 = null;
public Point point2 = null;
public double distance = 0.0;
public Pair()
{ }
public Pair(Point point1, Point point2)
{
this.point1 = point1;
this.point2 = point2;
calcDistance();
}
public void update(Point point1, Point point2, double distance)
{
this.point1 = point1;
this.point2 = point2;
this.distance = distance;
}
public void calcDistance()
{ this.distance = distance(point1, point2); }
public String toString()
{ return point1 + "-" + point2 + " : " + distance; }
}
public static double distance(Point p1, Point p2)
{
double xdist = p2.x - p1.x;
double ydist = p2.y - p1.y;
return Math.hypot(xdist, ydist);
}
public static Pair bruteForce(List<? extends Point> points)
{
int numPoints = points.size();
if (numPoints < 2)
return null;
Pair pair = new Pair(points.get(0), points.get(1));
if (numPoints > 2)
{
for (int i = 0; i < numPoints - 1; i++)
{
Point point1 = points.get(i);
for (int j = i + 1; j < numPoints; j++)
{
Point point2 = points.get(j);
double distance = distance(point1, point2);
if (distance < pair.distance)
pair.update(point1, point2, distance);
}
}
}
return pair;
}
public static void sortByX(List<? extends Point> points)
{
Collections.sort(points, new Comparator<Point>() {
public int compare(Point point1, Point point2)
{
if (point1.x < point2.x)
return -1;
if (point1.x > point2.x)
return 1;
return 0;
}
}
);
}
public static void sortByY(List<? extends Point> points)
{
Collections.sort(points, new Comparator<Point>() {
public int compare(Point point1, Point point2)
{
if (point1.y < point2.y)
return -1;
if (point1.y > point2.y)
return 1;
return 0;
}
}
);
}
public static Pair divideAndConquer(List<? extends Point> points)
{
List<Point> pointsSortedByX = new ArrayList<Point>(points);
sortByX(pointsSortedByX);
List<Point> pointsSortedByY = new ArrayList<Point>(points);
sortByY(pointsSortedByY);
return divideAndConquer(pointsSortedByX, pointsSortedByY);
}
private static Pair divideAndConquer(List<? extends Point> pointsSortedByX, List<? extends Point> pointsSortedByY)
{
int numPoints = pointsSortedByX.size();
if (numPoints <= 3)
return bruteForce(pointsSortedByX);
int dividingIndex = numPoints >>> 1;
List<? extends Point> leftOfCenter = pointsSortedByX.subList(0, dividingIndex);
List<? extends Point> rightOfCenter = pointsSortedByX.subList(dividingIndex, numPoints);
List<Point> tempList = new ArrayList<Point>(leftOfCenter);
sortByY(tempList);
Pair closestPair = divideAndConquer(leftOfCenter, tempList);
tempList.clear();
tempList.addAll(rightOfCenter);
sortByY(tempList);
Pair closestPairRight = divideAndConquer(rightOfCenter, tempList);
if (closestPairRight.distance < closestPair.distance)
closestPair = closestPairRight;
tempList.clear();
double shortestDistance =closestPair.distance;
double centerX = rightOfCenter.get(0).x;
for (Point point : pointsSortedByY)
if (Math.abs(centerX - point.x) < shortestDistance)
tempList.add(point);
for (int i = 0; i < tempList.size() - 1; i++)
{
Point point1 = tempList.get(i);
for (int j = i + 1; j < tempList.size(); j++)
{
Point point2 = tempList.get(j);
if ((point2.y - point1.y) >= shortestDistance)
break;
double distance = distance(point1, point2);
if (distance < closestPair.distance)
{
closestPair.update(point1, point2, distance);
shortestDistance = distance;
}
}
}
return closestPair;
}
public static void main(String[] args)
{
int numPoints = (args.length == 0) ? 1000 : Integer.parseInt(args[0]);
List<Point> points = new ArrayList<Point>();
Random r = new Random();
for (int i = 0; i < numPoints; i++)
points.add(new Point(r.nextDouble(), r.nextDouble()));
System.out.println("Generated " + numPoints + " random points");
long startTime = System.currentTimeMillis();
Pair bruteForceClosestPair = bruteForce(points);
long elapsedTime = System.currentTimeMillis() - startTime;
System.out.println("Brute force (" + elapsedTime + " ms): " + bruteForceClosestPair);
startTime = System.currentTimeMillis();
Pair dqClosestPair = divideAndConquer(points);
elapsedTime = System.currentTimeMillis() - startTime;
System.out.println("Divide and conquer (" + elapsedTime + " ms): " + dqClosestPair);
if (bruteForceClosestPair.distance != dqClosestPair.distance)
System.out.println("MISMATCH");
}
} |
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
| #PicoLisp | PicoLisp | (setq FunList
(make
(for @N 10
(link (curry (@N) () (* @N @N))) ) ) ) |
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
| #Pike | Pike | array funcs = ({});
foreach(enumerate(10);; int i)
{
funcs+= ({
lambda(int j)
{
return lambda()
{
return j*j;
};
}(i)
});
} |
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points | Circles of given radius through two points |
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
Exceptions
r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.
If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language.
If the points are too far apart then no circles can be drawn.
Task detail
Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned.
Show here the output for the following inputs:
p1 p2 r
0.1234, 0.9876 0.8765, 0.2345 2.0
0.0000, 2.0000 0.0000, 0.0000 1.0
0.1234, 0.9876 0.1234, 0.9876 2.0
0.1234, 0.9876 0.8765, 0.2345 0.5
0.1234, 0.9876 0.1234, 0.9876 0.0
Related task
Total circles area.
See also
Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
| #Elixir | Elixir | defmodule RC do
def circle(p, p, r) when r>0.0 do
raise ArgumentError, message: "Infinite number of circles, points coincide."
end
def circle(p, p, r) when r==0.0 do
{px, py} = p
[{px, py, r}]
end
def circle({p1x,p1y}, {p2x,p2y}, r) do
{dx, dy} = {p2x-p1x, p2y-p1y}
q = :math.sqrt(dx*dx + dy*dy)
if q > 2*r do
raise ArgumentError, message: "Distance of points > diameter."
else
{x3, y3} = {(p1x+p2x) / 2, (p1y+p2y) / 2}
d = :math.sqrt(r*r - q*q/4)
Enum.uniq([{x3 - d*dy/q, y3 + d+dx/q, r}, {x3 + d*dy/q, y3 - d*dx/q, r}])
end
end
end
data = [{{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}]
Enum.each(data, fn {p1, p2, r} ->
IO.write "Given points:\n #{inspect p1},\n #{inspect p2}\n and radius #{r}\n"
try do
circles = RC.circle(p1, p2, r)
IO.puts "You can construct the following circles:"
Enum.each(circles, fn circle -> IO.puts " #{inspect circle}" end)
rescue
e in ArgumentError -> IO.inspect e
end
IO.puts ""
end) |
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Tuesday, February 1, 2022 CE (in the common Gregorian calendar) will begin the lunisolar Year of the Tiger.
The celestial stems have no one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems each belong to one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element's governance is associated with yin, the other with yang.
Thus, 2022 is also the yang year of Water. Note that since 12 is an even number, the association between animals and yin/yang doesn't change. Consecutive Years of the Rooster will cycle through the five elements, but will always be yin, despite the apparent conceptual mismatch between the specifically-male English animal name and the female aspect denoted by yin.
Task
Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.
You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).
Requisite information
The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.
The element cycle runs in this order: Wood, Fire, Earth, Metal, Water.
The yang year precedes the yin year within each element.
The current 60-year cycle began in 1984 CE; the first cycle of the Common Era began in 4 CE.
Thus, 1984 was the year of the Wood Rat (yang), 1985 was the year of the Wood Ox (yin), and 1986 the year of the Fire Tiger (yang); 2022 - which, as already noted, is the year of the Water Tiger (yang) - is the 39th year of the current cycle.
Information for optional task
The ten celestial stems are 甲 jiă, 乙 yĭ, 丙 bĭng, 丁 dīng, 戊 wù, 己 jĭ, 庚 gēng, 辛 xīn, 壬 rén, and 癸 gŭi. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3".
The twelve terrestrial branches are 子 zĭ, 丑 chŏu, 寅 yín, 卯 măo, 辰 chén, 巳 sì, 午 wŭ, 未 wèi, 申 shēn, 酉 yŏu, 戌 xū, 亥 hài. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4".
Therefore 1984 was 甲子 (jiă-zĭ, or jia3-zi3). 2022 is 壬寅 (rén-yín or ren2-yin2).
| #Clojure | Clojure | (def base-year 4)
(def celestial-stems ["甲" "乙" "丙" "丁" "戊" "己" "庚" "辛" "壬" "癸"])
(def terrestrial-branches ["子" "丑" "寅" "卯" "辰" "巳" "午" "未" "申" "酉" "戌" "亥"])
(def zodiac-animals ["Rat" "Ox" "Tiger" "Rabbit" "Dragon" "Snake" "Horse" "Goat" "Monkey" "Rooster" "Dog" "Pig"])
(def elements ["Wood" "Fire" "Earth" "Metal" "Water"])
(def aspects ["yang" "yin"])
(def pinyin (zipmap (concat celestial-stems terrestrial-branches)
'("jiă" "yĭ" "bĭng" "dīng" "wù" "jĭ" "gēng" "xīn" "rén" "gŭi"
"zĭ" "chŏu" "yín" "măo" "chén" "sì" "wŭ" "wèi" "shēn" "yŏu" "xū" "hài")))
(defn chinese-zodiac [year]
(let [cycle-year (- year base-year)
cycle-position (inc (mod cycle-year 60))
stem-number (mod cycle-year 10)
stem-han (nth celestial-stems stem-number)
stem-pinyin (get pinyin stem-han)
element-number (int (Math/floor (/ stem-number 2)))
element (nth elements element-number)
branch-number (mod cycle-year 12)
branch-han (nth terrestrial-branches branch-number)
branch-pinyin (get pinyin branch-han)
zodiac-animal (nth zodiac-animals branch-number)
aspect-number (mod cycle-year 2)
aspect (nth aspects aspect-number)]
(println (format "%s: %s%s (%s-%s, %s %s; %s - cycle %s/60)"
year stem-han branch-han stem-pinyin branch-pinyin element zodiac-animal aspect cycle-position))))
(defn -main [& args]
(doseq [years (map read-string args)]
(chinese-zodiac years))) |
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an unusual filename: `Abdu'l-Bahá.txt
| #AppleScript | AppleScript | use framework "Foundation" -- YOSEMITE OS X onwards
use scripting additions
on run
setCurrentDirectory("~/Desktop")
ap({doesFileExist, doesDirectoryExist}, ¬
{"input.txt", "/input.txt", "docs", "/docs"})
--> {true, true, true, true, false, false, true, true}
-- The first four booleans are returned by `doesFileExist`.
-- The last four are returned by `doesDirectoryExist`,
-- which yields false for simple files, and true for directories.
end run
-- GENERIC SYSTEM DIRECTORY FUNCTIONS -----------------------------------------
-- doesDirectoryExist :: String -> Bool
on doesDirectoryExist(strPath)
set ca to current application
set oPath to (ca's NSString's stringWithString:strPath)'s ¬
stringByStandardizingPath
set {bln, int} to (ca's NSFileManager's defaultManager()'s ¬
fileExistsAtPath:oPath isDirectory:(reference))
bln and (int = 1)
end doesDirectoryExist
-- doesFileExist :: String -> Bool
on doesFileExist(strPath)
set ca to current application
set oPath to (ca's NSString's stringWithString:strPath)'s ¬
stringByStandardizingPath
ca's NSFileManager's defaultManager()'s fileExistsAtPath:oPath
end doesFileExist
-- getCurrentDirectory :: String
on getCurrentDirectory()
set ca to current application
ca's NSFileManager's defaultManager()'s currentDirectoryPath as string
end getCurrentDirectory
-- getFinderDirectory :: String
on getFinderDirectory()
tell application "Finder" to POSIX path of (insertion location as alias)
end getFinderDirectory
-- getHomeDirectory :: String
on getHomeDirectory()
(current application's NSHomeDirectory() as string)
end getHomeDirectory
-- setCurrentDirectory :: String -> IO ()
on setCurrentDirectory(strPath)
if doesDirectoryExist(strPath) then
set ca to current application
set oPath to (ca's NSString's stringWithString:strPath)'s ¬
stringByStandardizingPath
ca's NSFileManager's defaultManager()'s ¬
changeCurrentDirectoryPath:oPath
end if
end setCurrentDirectory
-- GENERIC HIGHER ORDER FUNCTIONS FOR THE TEST --------------------------------
-- A list of functions applied to a list of arguments
-- (<*> | ap) :: [(a -> b)] -> [a] -> [b]
on ap(fs, xs)
set {intFs, intXs} to {length of fs, length of xs}
set lst to {}
repeat with i from 1 to intFs
tell mReturn(item i of fs)
repeat with j from 1 to intXs
set end of lst to |λ|(contents of (item j of xs))
end repeat
end tell
end repeat
return lst
end ap
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Racket | Racket |
(terminal-port? (current-output-port))
|
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Raku | Raku | $ raku -e 'note $*OUT.t'
True
$ raku -e 'note $*OUT.t' >/dev/null
False |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #REXX | REXX | /*REXX program determines if the STDIN is a terminal device or other. */
signal on syntax /*if syntax error, then jump ──► SYNTAX*/
say 'output device:' testSTDIN() /*displays terminal ──or── other */
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
testSTDIN: syntax.=1; signal .; .: z.= sigl; call linein ,2; ..: syntax.= 0; return z..
/* [↑] must/should be all on one line.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
syntax: z..= 'other' /*when a SYNTAX error occurs, come here*/
if syntax. then do /*are we handling STDIN thingy error?*/
if sigl==z. then z..= 'terminal'; signal .. /*is this a stdin ?*/
end /* [↑] can't use a RETURN here. */
/* ··· handle other REXX syntax errors here ··· */ |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Ruby | Ruby | f = File.open("test.txt")
p f.isatty # => false
p STDOUT.isatty # => true
|
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Rust | Rust | /* Uses C library interface */
extern crate libc;
fn main() {
let istty = unsafe { libc::isatty(libc::STDOUT_FILENO as i32) } != 0;
if istty {
println!("stdout is tty");
} else {
println!("stdout is not tty");
}
} |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Scala | Scala | import org.fusesource.jansi.internal.CLibrary._
object IsATty extends App {
var enabled = true
def apply(enabled: Boolean): Boolean = {
// We must be on some unix variant..
try {
enabled && isatty(STDOUT_FILENO) == 1
}
catch {
case ignore: Throwable =>
ignore.printStackTrace()
false
}
}
println("tty " + apply(true))
} |
http://rosettacode.org/wiki/Chat_server | Chat server | Task
Write a server for a minimal text based chat.
People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
| #Ada | Ada | with Ada.Containers.Vectors;
with Ada.Command_Line; use Ada.Command_Line;
with Ada.Exceptions; use Ada.Exceptions;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Sockets; use Sockets;
procedure Chat_Server is
package Client_Vectors is new Ada.Containers.Vectors
(Element_Type => Socket_FD, Index_Type => Positive);
All_Clients : Client_Vectors.Vector;
procedure Write (S : String) is
procedure Output (Position : Client_Vectors.Cursor) is
Sock : Socket_FD := Client_Vectors.Element (Position);
begin
Put_Line (Sock, S);
end Output;
begin
All_Clients.Iterate (Output'Access);
end Write;
task type Client_Task is
entry Start (FD : Socket_FD);
end Client_Task;
task body Client_Task is
Sock : Socket_FD;
Sock_ID : Positive;
Name : Unbounded_String;
begin
select
accept Start (FD : Socket_FD) do
Sock := FD;
end Start;
or
terminate;
end select;
while Name = Null_Unbounded_String loop
Put (Sock, "Enter Name:");
Name := To_Unbounded_String (Get_Line (Sock));
end loop;
Write (To_String (Name) & " joined.");
All_Clients.Append (Sock);
Sock_ID := All_Clients.Find_Index (Sock);
loop
declare
Input : String := Get_Line (Sock);
begin
Write (To_String (Name) & ": " & Input);
end;
end loop;
exception
when Connection_Closed =>
Put_Line ("Connection closed");
Shutdown (Sock, Both);
All_Clients.Delete (Sock_ID);
Write (To_String (Name) & " left.");
end Client_Task;
Accepting_Socket : Socket_FD;
Incoming_Socket : Socket_FD;
type Client_Access is access Client_Task;
Dummy : Client_Access;
begin
if Argument_Count /= 1 then
Raise_Exception (Constraint_Error'Identity,
"Usage: " & Command_Name & " port");
end if;
Socket (Accepting_Socket, PF_INET, SOCK_STREAM);
Setsockopt (Accepting_Socket, SOL_SOCKET, SO_REUSEADDR, 1);
Bind (Accepting_Socket, Positive'Value (Argument (1)));
Listen (Accepting_Socket);
loop
Put_Line ("Waiting for new connection");
Accept_Socket (Accepting_Socket, Incoming_Socket);
Put_Line ("New connection acknowledged");
Dummy := new Client_Task;
Dummy.Start (Incoming_Socket);
end loop;
end Chat_Server; |
http://rosettacode.org/wiki/Check_Machin-like_formulas | Check Machin-like formulas | Machin-like formulas are useful for efficiently computing numerical approximations for
π
{\displaystyle \pi }
Task
Verify the following Machin-like formulas are correct by calculating the value of tan (right hand side) for each equation using exact arithmetic and showing they equal 1:
π
4
=
arctan
1
2
+
arctan
1
3
{\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 3}}
π
4
=
2
arctan
1
3
+
arctan
1
7
{\displaystyle {\pi \over 4}=2\arctan {1 \over 3}+\arctan {1 \over 7}}
π
4
=
4
arctan
1
5
−
arctan
1
239
{\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 239}}
π
4
=
5
arctan
1
7
+
2
arctan
3
79
{\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+2\arctan {3 \over 79}}
π
4
=
5
arctan
29
278
+
7
arctan
3
79
{\displaystyle {\pi \over 4}=5\arctan {29 \over 278}+7\arctan {3 \over 79}}
π
4
=
arctan
1
2
+
arctan
1
5
+
arctan
1
8
{\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 5}+\arctan {1 \over 8}}
π
4
=
4
arctan
1
5
−
arctan
1
70
+
arctan
1
99
{\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 70}+\arctan {1 \over 99}}
π
4
=
5
arctan
1
7
+
4
arctan
1
53
+
2
arctan
1
4443
{\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+4\arctan {1 \over 53}+2\arctan {1 \over 4443}}
π
4
=
6
arctan
1
8
+
2
arctan
1
57
+
arctan
1
239
{\displaystyle {\pi \over 4}=6\arctan {1 \over 8}+2\arctan {1 \over 57}+\arctan {1 \over 239}}
π
4
=
8
arctan
1
10
−
arctan
1
239
−
4
arctan
1
515
{\displaystyle {\pi \over 4}=8\arctan {1 \over 10}-\arctan {1 \over 239}-4\arctan {1 \over 515}}
π
4
=
12
arctan
1
18
+
8
arctan
1
57
−
5
arctan
1
239
{\displaystyle {\pi \over 4}=12\arctan {1 \over 18}+8\arctan {1 \over 57}-5\arctan {1 \over 239}}
π
4
=
16
arctan
1
21
+
3
arctan
1
239
+
4
arctan
3
1042
{\displaystyle {\pi \over 4}=16\arctan {1 \over 21}+3\arctan {1 \over 239}+4\arctan {3 \over 1042}}
π
4
=
22
arctan
1
28
+
2
arctan
1
443
−
5
arctan
1
1393
−
10
arctan
1
11018
{\displaystyle {\pi \over 4}=22\arctan {1 \over 28}+2\arctan {1 \over 443}-5\arctan {1 \over 1393}-10\arctan {1 \over 11018}}
π
4
=
22
arctan
1
38
+
17
arctan
7
601
+
10
arctan
7
8149
{\displaystyle {\pi \over 4}=22\arctan {1 \over 38}+17\arctan {7 \over 601}+10\arctan {7 \over 8149}}
π
4
=
44
arctan
1
57
+
7
arctan
1
239
−
12
arctan
1
682
+
24
arctan
1
12943
{\displaystyle {\pi \over 4}=44\arctan {1 \over 57}+7\arctan {1 \over 239}-12\arctan {1 \over 682}+24\arctan {1 \over 12943}}
π
4
=
88
arctan
1
172
+
51
arctan
1
239
+
32
arctan
1
682
+
44
arctan
1
5357
+
68
arctan
1
12943
{\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12943}}
and confirm that the following formula is incorrect by showing tan (right hand side) is not 1:
π
4
=
88
arctan
1
172
+
51
arctan
1
239
+
32
arctan
1
682
+
44
arctan
1
5357
+
68
arctan
1
12944
{\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12944}}
These identities are useful in calculating the values:
tan
(
a
+
b
)
=
tan
(
a
)
+
tan
(
b
)
1
−
tan
(
a
)
tan
(
b
)
{\displaystyle \tan(a+b)={\tan(a)+\tan(b) \over 1-\tan(a)\tan(b)}}
tan
(
arctan
a
b
)
=
a
b
{\displaystyle \tan \left(\arctan {a \over b}\right)={a \over b}}
tan
(
−
a
)
=
−
tan
(
a
)
{\displaystyle \tan(-a)=-\tan(a)}
You can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input.
Note: to formally prove the formula correct, it would have to be shown that
−
3
p
i
4
{\displaystyle {-3pi \over 4}}
< right hand side <
5
p
i
4
{\displaystyle {5pi \over 4}}
due to
tan
(
)
{\displaystyle \tan()}
periodicity.
| #D | D | import std.stdio, std.regex, std.conv, std.string, std.range,
arithmetic_rational;
struct Pair { int x; Rational r; }
Pair[][] parseEquations(in string text) /*pure nothrow*/ {
auto r = regex(r"\s*(?P<sign>[+-])?\s*(?:(?P<mul>\d+)\s*\*)?\s*" ~
r"arctan\((?P<num>\d+)/(?P<denom>\d+)\)");
Pair[][] machins;
foreach (const line; text.splitLines) {
Pair[] formula;
foreach (part; line.split("=")[1].matchAll(r)) {
immutable mul = part["mul"],
num = part["num"],
denom = part["denom"];
formula ~= Pair((part["sign"] == "-" ? -1 : 1) *
(mul.empty ? 1 : mul.to!int),
Rational(num.to!int,
denom.empty ? 1 : denom.to!int));
}
machins ~= formula;
}
return machins;
}
Rational tans(in Pair[] xs) pure nothrow {
static Rational tanEval(in int coef, in Rational f)
pure nothrow {
if (coef == 1)
return f;
if (coef < 0)
return -tanEval(-coef, f);
immutable a = tanEval(coef / 2, f),
b = tanEval(coef - coef / 2, f);
return (a + b) / (1 - a * b);
}
if (xs.length == 1)
return tanEval(xs[0].tupleof);
immutable a = xs[0 .. $ / 2].tans,
b = xs[$ / 2 .. $].tans;
return (a + b) / (1 - a * b);
}
void main() {
immutable equationText =
"pi/4 = arctan(1/2) + arctan(1/3)
pi/4 = 2*arctan(1/3) + arctan(1/7)
pi/4 = 4*arctan(1/5) - arctan(1/239)
pi/4 = 5*arctan(1/7) + 2*arctan(3/79)
pi/4 = 5*arctan(29/278) + 7*arctan(3/79)
pi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8)
pi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/99)
pi/4 = 5*arctan(1/7) + 4*arctan(1/53) + 2*arctan(1/4443)
pi/4 = 6*arctan(1/8) + 2*arctan(1/57) + arctan(1/239)
pi/4 = 8*arctan(1/10) - arctan(1/239) - 4*arctan(1/515)
pi/4 = 12*arctan(1/18) + 8*arctan(1/57) - 5*arctan(1/239)
pi/4 = 16*arctan(1/21) + 3*arctan(1/239) + 4*arctan(3/1042)
pi/4 = 22*arctan(1/28) + 2*arctan(1/443) - 5*arctan(1/1393) - 10*arctan(1/11018)
pi/4 = 22*arctan(1/38) + 17*arctan(7/601) + 10*arctan(7/8149)
pi/4 = 44*arctan(1/57) + 7*arctan(1/239) - 12*arctan(1/682) + 24*arctan(1/12943)
pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12943)
pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12944)";
const machins = equationText.parseEquations;
foreach (const machin, const eqn; machins.zip(equationText.splitLines)) {
immutable ans = machin.tans;
writefln("%5s: %s", ans == 1 ? "OK" : "ERROR", eqn);
}
} |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program character64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessCodeChar: .asciz "The code of character is : @ \n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
sZoneconv: .skip 32
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main: // entry of program
mov x0,'A'
ldr x1,qAdrsZoneconv
bl conversion10S
ldr x0,qAdrszMessCodeChar
ldr x1,qAdrsZoneconv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess
mov x0,'a'
ldr x1,qAdrsZoneconv
bl conversion10S
ldr x0,qAdrszMessCodeChar
ldr x1,qAdrsZoneconv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess
mov x0,'1'
ldr x1,qAdrsZoneconv
bl conversion10S
ldr x0,qAdrszMessCodeChar
ldr x1,qAdrsZoneconv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess
100: // standard end of the program */
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrsZoneconv: .quad sZoneconv
qAdrszMessCodeChar: .quad szMessCodeChar
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #ABAP | ABAP | report zcharcode
data: c value 'A', n type i.
field-symbols <n> type x.
assign c to <n> casting.
move <n> to n.
write: c, '=', n left-justified. |
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. | #DWScript | DWScript | function Cholesky(a : array of Float) : array of Float;
var
i, j, k, n : Integer;
s : Float;
begin
n:=Round(Sqrt(a.Length));
Result:=new Float[n*n];
for i:=0 to n-1 do begin
for j:=0 to i do begin
s:=0 ;
for k:=0 to j-1 do
s+=Result[i*n+k] * Result[j*n+k];
if i=j then
Result[i*n+j]:=Sqrt(a[i*n+i]-s)
else Result[i*n+j]:=1/Result[j*n+j]*(a[i*n+j]-s);
end;
end;
end;
procedure ShowMatrix(a : array of Float);
var
i, j, n : Integer;
begin
n:=Round(Sqrt(a.Length));
for i:=0 to n-1 do begin
for j:=0 to n-1 do
Print(Format('%2.5f ', [a[i*n+j]]));
PrintLn('');
end;
end;
var m1 := new Float[9];
m1 := [ 25.0, 15.0, -5.0,
15.0, 18.0, 0.0,
-5.0, 0.0, 11.0 ];
var c1 := Cholesky(m1);
ShowMatrix(c1);
PrintLn('');
var m2 : array of Float := [ 18.0, 22.0, 54.0, 42.0,
22.0, 70.0, 86.0, 62.0,
54.0, 86.0, 174.0, 134.0,
42.0, 62.0, 134.0, 106.0 ];
var c2 := Cholesky(m2);
ShowMatrix(c2); |
http://rosettacode.org/wiki/Check_input_device_is_a_terminal | Check input device is a terminal | Task
Demonstrate how to check whether the input device is a terminal or not.
Related task
Check output device is a terminal
| #UNIX_Shell | UNIX Shell | #!/bin/sh
if [ -t 0 ]
then
echo "Input is a terminal"
else
echo "Input is NOT a terminal"
fi |
http://rosettacode.org/wiki/Check_input_device_is_a_terminal | Check input device is a terminal | Task
Demonstrate how to check whether the input device is a terminal or not.
Related task
Check output device is a terminal
| #Wren | Wren | import "io" for Stdin
System.print("Input device is a terminal? %(Stdin.isTerminal ? "Yes" : "No")") |
http://rosettacode.org/wiki/Check_input_device_is_a_terminal | Check input device is a terminal | Task
Demonstrate how to check whether the input device is a terminal or not.
Related task
Check output device is a terminal
| #zkl | zkl | const S_IFCHR=0x2000;
fcn S_ISCHR(f){ f.info()[4].bitAnd(S_IFCHR).toBool() }
S_ISCHR(File.stdin).println(); |
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
| #C.2B.2B | C++ | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
const vector<string> MONTHS = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
struct Birthday {
int month, day;
friend ostream &operator<<(ostream &, const Birthday &);
};
ostream &operator<<(ostream &out, const Birthday &birthday) {
return out << MONTHS[birthday.month - 1] << ' ' << birthday.day;
}
template <typename C>
bool monthUniqueIn(const Birthday &b, const C &container) {
auto it = cbegin(container);
auto end = cend(container);
int count = 0;
while (it != end) {
if (it->month == b.month) {
count++;
}
it = next(it);
}
return count == 1;
}
template <typename C>
bool dayUniqueIn(const Birthday &b, const C &container) {
auto it = cbegin(container);
auto end = cend(container);
int count = 0;
while (it != end) {
if (it->day == b.day) {
count++;
}
it = next(it);
}
return count == 1;
}
template <typename C>
bool monthWithUniqueDayIn(const Birthday &b, const C &container) {
auto it = cbegin(container);
auto end = cend(container);
while (it != end) {
if (it->month == b.month && dayUniqueIn(*it, container)) {
return true;
}
it = next(it);
}
return false;
}
int main() {
vector<Birthday> choices = {
{5, 15}, {5, 16}, {5, 19}, {6, 17}, {6, 18},
{7, 14}, {7, 16}, {8, 14}, {8, 15}, {8, 17},
};
// Albert knows the month but doesn't know the day.
// So the month can't be unique within the choices.
vector<Birthday> filtered;
for (auto bd : choices) {
if (!monthUniqueIn(bd, choices)) {
filtered.push_back(bd);
}
}
// Albert also knows that Bernard doesn't know the answer.
// So the month can't have a unique day.
vector<Birthday> filtered2;
for (auto bd : filtered) {
if (!monthWithUniqueDayIn(bd, filtered)) {
filtered2.push_back(bd);
}
}
// Bernard now knows the answer.
// So the day must be unique within the remaining choices.
vector<Birthday> filtered3;
for (auto bd : filtered2) {
if (dayUniqueIn(bd, filtered2)) {
filtered3.push_back(bd);
}
}
// Albert now knows the answer too.
// So the month must be unique within the remaining choices.
vector<Birthday> filtered4;
for (auto bd : filtered3) {
if (monthUniqueIn(bd, filtered3)) {
filtered4.push_back(bd);
}
}
if (filtered4.size() == 1) {
cout << "Cheryl's birthday is " << filtered4[0] << '\n';
} else {
cout << "Something went wrong!\n";
}
return 0;
} |
http://rosettacode.org/wiki/Checkpoint_synchronization | Checkpoint synchronization | The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before starting another one. Putting details together is the checkpoint at which tasks synchronize themselves before going their paths apart.
The task
Implement checkpoint synchronization in your language.
Make sure that the solution is race condition-free. Note that a straightforward solution based on events is exposed to race condition. Let two tasks A and B need to be synchronized at a checkpoint. Each signals its event (EA and EB correspondingly), then waits for the AND-combination of the events (EA&EB) and resets its event. Consider the following scenario: A signals EA first and gets blocked waiting for EA&EB. Then B signals EB and loses the processor. Then A is released (both events are signaled) and resets EA. Now if B returns and enters waiting for EA&EB, it gets lost.
When a worker is ready it shall not continue before others finish. A typical implementation bug is when a worker is counted twice within one working cycle causing its premature completion. This happens when the quickest worker serves its cycle two times while the laziest one is lagging behind.
If you can, implement workers joining and leaving.
| #Icon_and_Unicon | Icon and Unicon | global nWorkers, workers, cv
procedure main(A)
nWorkers := integer(A[1]) | 3
cv := condvar()
every put(workers := [], worker(!nWorkers))
every wait(!workers)
end
procedure worker(n)
return thread every !3 do { # Union limits each worker to 3 pieces
write(n," is working")
delay(?3 * 1000)
write(n," is done")
countdown()
}
end
procedure countdown()
critical cv: {
if (nWorkers -:= 1) <= 0 then {
write("\t\tAll done")
nWorkers := *workers
return (unlock(cv),signal(cv, 0))
}
wait(cv)
}
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
| #Gambas | Gambas | Public Sub Main()
Dim siCount As Short
Dim cCollection As Collection = ["0": "zero", "1": "one", "2": "two", "3": "three", "4": "four",
"5": "five", "6": "six", "7": "seven", "8": "eight", "9": "nine"]
For siCount = 0 To 9
Print cCollection[Str(siCount)]
Next
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | combinations[n_Integer, m_Integer]/;m>= 0:=Union[Sort /@ Permutations[Range[0, n - 1], {m}]] |
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.
| #Raku | Raku | given lc prompt("Done? ") {
when 'yes' { return }
when 'no' { next }
default { say "Please answer either yes or no." }
} |
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}}}
.
| #Common_Lisp | Common Lisp |
(defun chinese-remainder (am)
"Calculates the Chinese Remainder for the given set of integer modulo pairs.
Note: All the ni and the N must be coprimes."
(loop :for (a . m) :in am
:with mtot = (reduce #'* (mapcar #'(lambda(X) (cdr X)) am))
:with sum = 0
:finally (return (mod sum mtot))
:do
(incf sum (* a (invmod (/ mtot m) m) (/ mtot m)))))
|
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
| #zkl | zkl | var [const] BI=Import("zklBigNum"); // libGMP
fcn ccFactors(n,m){ // not re-entrant
prod:=BI(6*m + 1);
if(not prod.probablyPrime()) return(False);
fact:=BI(12*m + 1);
if(not fact.probablyPrime()) return(False);
prod.mul(fact);
foreach i in ([1..n-2]){
fact.set((2).pow(i) *9*m + 1);
if(not fact.probablyPrime()) return(False);
prod.mul(fact);
}
prod
}
fcn ccNumbers(start,end){
foreach n in ([start..end]){
a,m := ( if(n<=4) 1 else (2).pow(n - 4) ), a;
while(1){
if(num := ccFactors(n,m)){
println("a(%d) = %,d".fmt(n,num));
break;
}
m+=a;
}
}
} |
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.
| #Haskell | Haskell | import Control.Concurrent (setNumCapabilities)
import Control.Monad.Par (runPar, get, spawnP)
import Control.Monad (join, (>=>))
import Data.List.Split (chunksOf)
import Data.List (intercalate, mapAccumL, genericTake, genericDrop)
import Data.Bifunctor (bimap)
import GHC.Conc (getNumProcessors)
import Math.NumberTheory.Primes (factorise, unPrime)
import Text.Printf (printf)
chowla :: Word -> Word
chowla 1 = 0
chowla n = f n
where
f = (-) =<< pred . product . fmap sumFactor . factorise
sumFactor (n, e) = foldr (\p s -> s + unPrime n^p) 1 [1..e]
chowlas :: [Word] -> [(Word, Word)]
chowlas [] = []
chowlas xs = runPar $ join <$>
(mapM (spawnP . fmap ((,) <*> chowla)) >=> mapM get) (chunksOf (10^6) xs)
chowlaPrimes :: [(Word, Word)] -> (Word, Word) -> (Word, Word)
chowlaPrimes chowlas range = (count chowlas, snd range)
where
isPrime (1, n) = False
isPrime (_, n) = n == 0
count = fromIntegral . length . filter isPrime . between range
between (min, max) = genericTake (max - pred min) . genericDrop (pred min)
chowlaPerfects :: [(Word, Word)] -> [Word]
chowlaPerfects = fmap fst . filter isPerfect
where
isPerfect (1, _) = False
isPerfect (n, c) = c == pred n
commas :: (Show a, Integral a) => a -> String
commas = reverse . intercalate "," . chunksOf 3 . reverse . show
main :: IO ()
main = do
cores <- getNumProcessors
setNumCapabilities cores
printf "Using %d cores\n" cores
mapM_ (uncurry (printf "chowla(%2d) = %d\n")) $ take 37 allChowlas
mapM_ (uncurry (printf "There are %8s primes < %10s\n"))
(chowlaP
[ (1, 10^2)
, (succ $ 10^2, 10^3)
, (succ $ 10^3, 10^4)
, (succ $ 10^4, 10^5)
, (succ $ 10^5, 10^6)
, (succ $ 10^6, 10^7) ])
mapM_ (printf "%10s is a perfect number.\n" . commas) perfects
printf "There are %2d perfect numbers < 35,000,000\n" $ length perfects
where
chowlaP = fmap (bimap commas commas) . snd
. mapAccumL (\total (count, max) -> (total + count, (total + count, max))) 0
. fmap (chowlaPrimes $ take (10^7) allChowlas)
perfects = chowlaPerfects allChowlas
allChowlas = chowlas [1..35*10^6] |
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.
| #Phix | Phix | with javascript_semantics
type church(object c)
-- eg {r_add,1,{a,b}}
return sequence(c) and length(c)=3
and integer(c[1]) and integer(c[2])
and sequence(c[3]) and length(c[3])=2
end type
function succ(church c)
-- eg {r_add,1,{a,b}} => {r_add,2,{a,b}} aka a+b -> a+b+b
c = deep_copy(c)
c[2] += 1
return c
end function
-- three normal integer-handling routines...
function add(integer n, a, b)
for i=1 to n do
a += b
end for
return a
end function
constant r_add = routine_id("add")
function mul(integer n, a, b)
for i=1 to n do
a *= b
end for
return a
end function
constant r_mul = routine_id("mul")
function pow(integer n, a, b)
for i=1 to n do
a = power(a,b)
end for
return a
end function
constant r_pow = routine_id("pow")
-- ...and three church constructors to match
-- (no maths here, just pure static data)
function addch(church c, d)
church res = {r_add,1,{c,d}}
return res
end function
function mulch(church c, d)
church res = {r_mul,1,{c,d}}
return res
end function
function powch(church c, d)
church res = {r_pow,1,{c,d}}
return res
end function
function tointch(church c)
-- note this is where the bulk of any processing happens
{integer rid, integer n, object x} = c
x = deep_copy(x)
for i=1 to length(x) do
if church(x[i]) then x[i] = tointch(x[i]) end if
end for
-- return call_func(rid,n&x)
x = deep_copy({n})&deep_copy(x)
return call_func(rid,x)
end function
constant church zero = {r_add,0,{0,1}}
function inttoch(integer i)
if i=0 then
return zero
else
return succ(inttoch(i-1))
end if
end function
church three = succ(succ(succ(zero))),
four = succ(three)
printf(1,"three -> %d\n",tointch(three))
printf(1,"four -> %d\n",tointch(four))
printf(1,"three + four -> %d\n",tointch(addch(three,four)))
printf(1,"three * four -> %d\n",tointch(mulch(three,four)))
printf(1,"three ^ four -> %d\n",tointch(powch(three,four)))
printf(1,"four ^ three -> %d\n",tointch(powch(four,three)))
printf(1,"5 -> five -> %d\n",tointch(inttoch(5)))
|
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.
| #Forth | Forth | :class MyClass <super Object
int memvar
:m ClassInit: ( -- )
ClassInit: super
1 to memvar ;m
:m ~: ( -- ) ." Final " show: [ Self ] ;m
:m set: ( n -- ) to memvar ;m
:m show: ( -- ) ." Memvar = " memvar . ;m
;class |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, as a type, has the values and operations of its own.
The operations of are usually called methods of the root type.
Both operations and values are called polymorphic.
A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument.
The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual.
Operations with multiple arguments and/or the results of the class are called multi-methods.
A further generalization of is the operation with arguments and/or results from different classes.
single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x).
multiple-dispatch languages allow many arguments and/or results to control the dispatch.
A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type.
This type is sometimes called the most specific type of a [polymorphic] value.
The type tag of the value is used in order to resolve the dispatch.
The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class.
In many OO languages
the type of the class of T and T itself are considered equivalent.
In some languages they are distinct (like in Ada).
When class T and T are equivalent, there is no way to distinguish
polymorphic and specific values.
Task
Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
| #Fortran | Fortran |
!-----------------------------------------------------------------------
!Module accuracy defines precision and some constants
!-----------------------------------------------------------------------
module accuracy_module
implicit none
integer, parameter, public :: rdp = kind(1.d0)
! constants
real(rdp), parameter :: pi=3.141592653589793238462643383279502884197_rdp
end module accuracy_module
!-----------------------------------------------------------------------
!Module typedefs_module contains abstract derived type and extended type definitions.
! Note that a reserved word "class" in Fortran is used to describe
! some polymorphic variable whose data type may vary at run time.
!-----------------------------------------------------------------------
module typedefs_module
use accuracy_module
implicit none
private ! all
public :: TPoint, TShape, TCircle, TRectangle, TSquare ! public only these defined derived types
! abstract derived type
type, abstract :: TShape
real(rdp) :: area
character(len=:),allocatable :: name
contains
! deferred method i.e. abstract method = must be overridden in extended type
procedure(calculate_area), deferred,pass :: calculate_area
end type TShape
! just declaration of the abstract method/procedure for TShape type
abstract interface
function calculate_area(this)
use accuracy_module
import TShape !imports TShape type from host scoping unit and makes it accessible here
implicit none
class(TShape) :: this
real(rdp) :: calculate_area
end function calculate_area
end interface
! auxiliary derived type
type TPoint
real(rdp) :: x,y
end type TPoint
! extended derived type
type, extends(TShape) :: TCircle
real(rdp) :: radius
real(rdp), private :: diameter
type(TPoint) :: centre
contains
procedure, pass :: calculate_area => calculate_circle_area
procedure, pass :: get_circle_diameter
final :: finalize_circle
end type TCircle
! extended derived type
type, extends(TShape) :: TRectangle
type(TPoint) :: A,B,C,D
contains
procedure, pass :: calculate_area => calculate_rectangle_area
final :: finalize_rectangle
end type TRectangle
! extended derived type
type, extends(TRectangle) :: TSquare
contains
procedure, pass :: calculate_area => calculate_square_area
final :: finalize_square
end type TSquare
contains
! finalization subroutines for each type
! They called recursively, i.e. finalize_rectangle
! will be called after finalize_square subroutine
subroutine finalize_circle(x)
type(TCircle), intent(inout) :: x
write(*,*) "Deleting TCircle object"
end subroutine finalize_circle
subroutine finalize_rectangle(x)
type(TRectangle), intent(inout) :: x
write(*,*) "Deleting also TRectangle object"
end subroutine finalize_rectangle
subroutine finalize_square(x)
type(TSquare), intent(inout) :: x
write(*,*) "Deleting TSquare object"
end subroutine finalize_square
function calculate_circle_area(this)
implicit none
class(TCircle) :: this
real(rdp) :: calculate_circle_area
this%area = pi * this%radius**2
calculate_circle_area = this%area
end function calculate_circle_area
function calculate_rectangle_area(this)
implicit none
class(TRectangle) :: this
real(rdp) :: calculate_rectangle_area
! here could be more code
this%area = 1
calculate_rectangle_area = this%area
end function calculate_rectangle_area
function calculate_square_area(this)
implicit none
class(TSquare) :: this
real(rdp) :: calculate_square_area
! here could be more code
this%area = 1
calculate_square_area = this%area
end function calculate_square_area
function get_circle_diameter(this)
implicit none
class(TCircle) :: this
real(rdp) :: get_circle_diameter
this % diameter = 2.0_rdp * this % radius
get_circle_diameter = this % diameter
end function get_circle_diameter
end module typedefs_module
!-----------------------------------------------------------------------
!Main program
!-----------------------------------------------------------------------
program rosetta_class
use accuracy_module
use typedefs_module
implicit none
! we need this subroutine in order to show the finalization
call test_types()
contains
subroutine test_types()
implicit none
! declare object of type TPoint
type(TPoint), target :: point
! declare object of type TCircle
type(TCircle),target :: circle
! declare object of type TSquare
type(TSquare),target :: square
! declare pointers
class(TPoint), pointer :: ppo
class(TCircle), pointer :: pci
class(TSquare), pointer :: psq
!constructor
point = TPoint(5.d0,5.d0)
ppo => point
write(*,*) "x=",point%x,"y=",point%y
pci => circle
pci % radius = 1
write(*,*) pci % radius
! write(*,*) pci % diameter !No,it is a PRIVATE component
write(*,*) pci % get_circle_diameter()
write(*,*) pci % calculate_area()
write(*,*) pci % area
psq => square
write(*,*) psq % area
write(*,*) psq % calculate_area()
write(*,*) psq % area
end subroutine test_types
end program rosetta_class
|
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)
| #JavaScript | JavaScript | function distance(p1, p2) {
var dx = Math.abs(p1.x - p2.x);
var dy = Math.abs(p1.y - p2.y);
return Math.sqrt(dx*dx + dy*dy);
}
function bruteforceClosestPair(arr) {
if (arr.length < 2) {
return Infinity;
} else {
var minDist = distance(arr[0], arr[1]);
var minPoints = arr.slice(0, 2);
for (var i=0; i<arr.length-1; i++) {
for (var j=i+1; j<arr.length; j++) {
if (distance(arr[i], arr[j]) < minDist) {
minDist = distance(arr[i], arr[j]);
minPoints = [ arr[i], arr[j] ];
}
}
}
return {
distance: minDist,
points: minPoints
};
}
} |
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
| #PowerShell | PowerShell |
function Get-Closure ([double]$Number)
{
{param([double]$Sum) return $script:Number *= $Sum}.GetNewClosure()
}
|
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
| #Prolog | Prolog | :-use_module(library(lambda)).
closure :-
numlist(1,10, Lnum),
maplist(make_func, Lnum, Lfunc),
maplist(call_func, Lnum, Lfunc).
make_func(I, \X^(X is I*I)).
call_func(N, F) :-
call(F, R),
format('Func ~w : ~w~n', [N, R]).
|
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
| #ERRE | ERRE |
PROGRAM CIRCLES
!
! for rosettacode.org
!
PROCEDURE CIRCLE_CENTER(X1,Y1,X2,Y2,R->MSG$)
LOCAL D,W,X3,Y3
D=SQR((X2-X1)^2+(Y2-Y1)^2)
IF D=0 THEN
MSG$="NO CIRCLES CAN BE DRAWN, POINTS ARE IDENTICAL"
EXIT PROCEDURE
END IF
X3=(X1+X2)/2 Y3=(Y1+Y2)/2
W=R^2-(D/2)^2
IF W<0 THEN
MSG$="NO SOLUTION"
EXIT PROCEDURE
END IF
CX1=X3+SQR(W)*(Y1-Y2)/D CY1=Y3+SQR(W)*(X2-X1)/D
CX2=X3-SQR(W)*(Y1-Y2)/D CY2=Y3-SQR(W)*(X2-X1)/D
IF D=R*2 THEN
MSG$="POINTS ARE OPPOSITE ENDS OF A DIAMETER CENTER = "+STR$(CX1)+","+STR$(CY1)
EXIT PROCEDURE
END IF
IF D>R*2 THEN
MSG$="POINTS ARE TOO FAR"
EXIT PROCEDURE
END IF
IF R<=0 THEN
MSG$="RADIUS IS NOT VALID"
EXIT PROCEDURE
END IF
MSG$=STR$(CX1)+","+STR$(CY1)+" & "+STR$(CX2)+","+STR$(CY2)
END PROCEDURE
BEGIN
DATA(0.1234,0.9876,0.8765,0.2345,2.0)
DATA(0.0000,2.0000,0.0000,0.0000,1.0)
DATA(0.1234,0.9876,0.1234,0.9876,2.0)
DATA(0.1234,0.9876,0.8765,0.2345,0.5)
DATA(0.1234,0.9876,0.1234,0.9876,0.0)
FOR I%=1 TO 5 DO
READ(PX,PY,QX,QY,RADIUS)
CIRCLE_CENTER(PX,PY,QX,QY,RADIUS->MSG$)
PRINT(MSG$)
END FOR
END PROGRAM
|
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).
| #Commodore_BASIC | Commodore BASIC | 1000 rem display the chinese zodiac for a given year
1010 poke 53281,7: rem yellow background
1020 poke 53280,2: rem red border
1030 poke 646,2: rem red text
1040 h1$="chinese zodiac":gosub 2000 set-heading
1050 gosub 3000 initialize-data
1060 print
1070 print "enter year (return to quit):";
1080 get k$:if k$="" then 1080
1090 if k$=chr$(13) then end
1100 poke 631,asc(k$):poke 198,1:rem ungetc(k$)
1110 open 1,0: input#1, y$: close 1:print
1120 if val(y$)=0 and y$<>"0" then print chr$(145):goto 1060
1130 y=val(y$)-4
1140 sy=fnym(60): rem year of the sexagesimal cycle
1150 cs=fnym(10): rem celestial stem
1160 tb=fnym(12): rem terrestrial branch
1170 el=int(cs/2): rem element
1180 za=tb: rem zodiac animal
1190 as=fnym(2): rem aspect
1200 print
1210 print "the chinese year beginning in ce "y$
1220 print "is "cs$(cs)"-"tb$(tb)", year"(sy+1)"of 60,"
1230 print "the year of the "el$(el)" "za$(za)" ("as$(as)")."
1260 goto 1060
1270 end
2000 print chr$(147);chr$(18);"****";
2010 sp=32-len(h1$)
2020 for i=1 to int(sp/2)
2030 : print " ";
2040 next i
2050 print h1$;
2060 for i=i to sp
2070 : print " ";
2080 next i
2090 print "****";
2100 return
3000 dim cs$(9): rem ten celestial stems
3010 dim tb$(11): rem twelve terrestrial branches
3020 dim za$(11): rem twelve "zodiac" animals
3030 dim el$(4): rem five elements
3040 dim as$(1): rem two aspects
3050 for i=0 to 9
3060 : read cs$(i)
3070 next i
3080 data jia3, yi3, bing3, ding1, wu4
3090 data ji3, geng1, xin1, ren2, gui3
3100 for i=0 to 11
3110 : read tb$(i)
3120 next i
3130 data zi3, chou3, yin2, mao3
3140 data chen2, si4, wu3, wei4
3150 data shen2, you3, xu1, hai4
3160 for i=0 to 11
3170 : read za$(i)
3180 next i
3190 data rat, ox, tiger, rabbit
3200 data dragon, snake, horse, goat
3210 data monkey, rooster, dog, pig
3220 for i=0 to 4
3230 : read el$(i)
3240 next i
3250 data wood, fire, earth
3260 data metal, water
3270 for i=0 to 1
3280 : read as$(i)
3290 next i
3300 data yang, yin
3310 rem year-mod function
3320 def fnym(d) = y - int(y/d)*d
3330 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).
| #Common_Lisp | Common Lisp | ; Any CE Year that was the first of a 60-year cycle
(defconstant base-year 1984)
(defconstant celestial-stems
'("甲" "乙" "丙" "丁" "戊" "己" "庚" "辛" "壬" "癸"))
(defconstant terrestrial-branches
'("子" "丑" "寅" "卯" "辰" "巳" "午" "未" "申" "酉" "戌" "亥"))
(defconstant zodiac-animals
'("Rat" "Ox" "Tiger" "Rabbit" "Dragon" "Snake"
"Horse" "Goat" "Monkey" "Rooster" "Dog" "Pig"))
(defconstant elements '("Wood" "Fire" "Earth" "Metal" "Water"))
(defconstant aspects '("yang" "yin"))
(defconstant pinyin
(pairlis (append celestial-stems terrestrial-branches)
'("jiă" "yĭ" "bĭng" "dīng" "wù" "jĭ" "gēng" "xīn" "rén" "gŭi"
"zĭ" "chŏu" "yín" "măo" "chén" "sì" "wŭ" "wèi" "shēn" "yŏu" "xū" "hài")))
(defun this-year () (nth 5 (multiple-value-list (get-decoded-time))))
(defun pinyin-for (han) (cdr (assoc han pinyin :test #'string=)))
(defun chinese-zodiac (&rest years)
(loop for ce-year in (if (null years) (list (this-year)) years) collecting
(let* ((cycle-year (- ce-year base-year))
(stem-number (mod cycle-year 10))
(stem-han (nth stem-number celestial-stems))
(stem-pinyin (pinyin-for stem-han))
(element-number (floor stem-number 2))
(element (nth element-number elements))
(branch-number (mod cycle-year 12))
(branch-han (nth branch-number terrestrial-branches))
(branch-pinyin (pinyin-for branch-han))
(zodiac-animal (nth branch-number zodiac-animals))
(aspect-number (mod cycle-year 2))
(aspect (nth aspect-number aspects)))
(cons ce-year (list stem-han branch-han stem-pinyin branch-pinyin element zodiac-animal aspect)))))
(defun get-args ()
(or
#+CLISP *args*
#+SBCL (cdr *posix-argv*)
#+LISPWORKS system:*line-arguments-list*
#+CMU extensions:*command-line-words*
nil))
(loop for cz in (apply #'chinese-zodiac (mapcar #'read-from-string (get-args)))
doing
(format t "~{~a: ~a~a (~a-~a, ~a ~a; ~a)~%~}" cz)) |
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an unusual filename: `Abdu'l-Bahá.txt
| #Applesoft_BASIC | Applesoft BASIC | 100 F$ = "THAT FILE"
110 T$(0) = "DOES NOT EXIST."
120 T$(1) = "EXISTS."
130 GOSUB 200"FILE EXISTS?
140 PRINT F$; " "; T$(E)
150 END
200 REM FILE EXISTS?
210 REM TRY
220 ON ERR GOTO 300"CATCH
230 PRINT CHR$(4); "VERIFY "; F$
240 POKE 216, 0 : REM ONERR OFF
250 E = 1
260 GOTO 350"END TRY
300 REM CATCH
310 E = PEEK(222) <> 6
320 POKE 216, 0 : REM ONERR OFF
330 IF E THEN RESUME : REM THROW
340 CALL - 3288 : REM RECOVER
350 REM END TRY
360 RETURN
|
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Standard_ML | Standard ML | val stdoutRefersToTerminal : bool = Posix.ProcEnv.isatty Posix.FileSys.stdout |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Tcl | Tcl | set toTTY [dict exists [fconfigure stdout] -mode]
puts [expr {$toTTY ? "Output goes to tty" : "Output doesn't go to tty"}] |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #UNIX_Shell | UNIX Shell | #!/bin/sh
if [ -t 1 ]
then
echo "Output is a terminal"
else
echo "Output is NOT a terminal" >/dev/tty
fi |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Sub Main()
Console.WriteLine("Stdout is tty: {0}", Console.IsOutputRedirected)
End Sub
End Module |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Wren | Wren | /* check_output_device_is_terminal.wren */
class C {
foreign static isOutputDeviceTerminal
}
System.print("Output device is a terminal = %(C.isOutputDeviceTerminal)") |
http://rosettacode.org/wiki/Chat_server | Chat server | Task
Write a server for a minimal text based chat.
People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
| #BaCon | BaCon | DECLARE user$ ASSOC STRING
DECLARE connect ASSOC long
OPEN "localhost:51000" FOR SERVER AS mynet
WHILE TRUE
IF WAIT(mynet, 30) THEN
fd = ACCEPT(mynet)
connect(GETPEER$(fd)) = fd
SEND "Enter your name: " TO fd
ELSE
FOR con$ IN OBTAIN$(connect)
IF WAIT(connect(con$), 10) THEN
RECEIVE in$ FROM connect(con$)
IF user$(GETPEER$(connect(con$))) = "" THEN
user$(GETPEER$(connect(con$))) = CHOP$(in$)
chat$ = chat$ & user$(GETPEER$(connect(con$))) & " joined the chat." & NL$
SEND "Welcome, " & CHOP$(in$) & "!" & NL$ TO connect(con$)
ELIF LEFT$(in$, 4) = "quit" THEN
SEND "You're disconnected!" & NL$ TO connect(con$)
chat$ = chat$ & user$(GETPEER$(connect(con$))) & " left the chat." & NL$
FREE user$(GETPEER$(connect(con$)))
FREE connect(con$)
CLOSE SERVER connect(con$)
ELIF LEFT$(in$, 4) = "say " THEN
chat$ = chat$ & user$(GETPEER$(connect(con$))) & " said: " & MID$(in$, 5)
ENDIF
ENDIF
NEXT
IF LEN(chat$) > 0 THEN
FOR con$ IN OBTAIN$(connect)
IF user$(GETPEER$(connect(con$))) <> "" THEN SEND chat$ TO connect(con$)
NEXT
chat$ = ""
ENDIF
ENDIF
WEND |
http://rosettacode.org/wiki/Check_Machin-like_formulas | Check Machin-like formulas | Machin-like formulas are useful for efficiently computing numerical approximations for
π
{\displaystyle \pi }
Task
Verify the following Machin-like formulas are correct by calculating the value of tan (right hand side) for each equation using exact arithmetic and showing they equal 1:
π
4
=
arctan
1
2
+
arctan
1
3
{\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 3}}
π
4
=
2
arctan
1
3
+
arctan
1
7
{\displaystyle {\pi \over 4}=2\arctan {1 \over 3}+\arctan {1 \over 7}}
π
4
=
4
arctan
1
5
−
arctan
1
239
{\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 239}}
π
4
=
5
arctan
1
7
+
2
arctan
3
79
{\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+2\arctan {3 \over 79}}
π
4
=
5
arctan
29
278
+
7
arctan
3
79
{\displaystyle {\pi \over 4}=5\arctan {29 \over 278}+7\arctan {3 \over 79}}
π
4
=
arctan
1
2
+
arctan
1
5
+
arctan
1
8
{\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 5}+\arctan {1 \over 8}}
π
4
=
4
arctan
1
5
−
arctan
1
70
+
arctan
1
99
{\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 70}+\arctan {1 \over 99}}
π
4
=
5
arctan
1
7
+
4
arctan
1
53
+
2
arctan
1
4443
{\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+4\arctan {1 \over 53}+2\arctan {1 \over 4443}}
π
4
=
6
arctan
1
8
+
2
arctan
1
57
+
arctan
1
239
{\displaystyle {\pi \over 4}=6\arctan {1 \over 8}+2\arctan {1 \over 57}+\arctan {1 \over 239}}
π
4
=
8
arctan
1
10
−
arctan
1
239
−
4
arctan
1
515
{\displaystyle {\pi \over 4}=8\arctan {1 \over 10}-\arctan {1 \over 239}-4\arctan {1 \over 515}}
π
4
=
12
arctan
1
18
+
8
arctan
1
57
−
5
arctan
1
239
{\displaystyle {\pi \over 4}=12\arctan {1 \over 18}+8\arctan {1 \over 57}-5\arctan {1 \over 239}}
π
4
=
16
arctan
1
21
+
3
arctan
1
239
+
4
arctan
3
1042
{\displaystyle {\pi \over 4}=16\arctan {1 \over 21}+3\arctan {1 \over 239}+4\arctan {3 \over 1042}}
π
4
=
22
arctan
1
28
+
2
arctan
1
443
−
5
arctan
1
1393
−
10
arctan
1
11018
{\displaystyle {\pi \over 4}=22\arctan {1 \over 28}+2\arctan {1 \over 443}-5\arctan {1 \over 1393}-10\arctan {1 \over 11018}}
π
4
=
22
arctan
1
38
+
17
arctan
7
601
+
10
arctan
7
8149
{\displaystyle {\pi \over 4}=22\arctan {1 \over 38}+17\arctan {7 \over 601}+10\arctan {7 \over 8149}}
π
4
=
44
arctan
1
57
+
7
arctan
1
239
−
12
arctan
1
682
+
24
arctan
1
12943
{\displaystyle {\pi \over 4}=44\arctan {1 \over 57}+7\arctan {1 \over 239}-12\arctan {1 \over 682}+24\arctan {1 \over 12943}}
π
4
=
88
arctan
1
172
+
51
arctan
1
239
+
32
arctan
1
682
+
44
arctan
1
5357
+
68
arctan
1
12943
{\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12943}}
and confirm that the following formula is incorrect by showing tan (right hand side) is not 1:
π
4
=
88
arctan
1
172
+
51
arctan
1
239
+
32
arctan
1
682
+
44
arctan
1
5357
+
68
arctan
1
12944
{\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12944}}
These identities are useful in calculating the values:
tan
(
a
+
b
)
=
tan
(
a
)
+
tan
(
b
)
1
−
tan
(
a
)
tan
(
b
)
{\displaystyle \tan(a+b)={\tan(a)+\tan(b) \over 1-\tan(a)\tan(b)}}
tan
(
arctan
a
b
)
=
a
b
{\displaystyle \tan \left(\arctan {a \over b}\right)={a \over b}}
tan
(
−
a
)
=
−
tan
(
a
)
{\displaystyle \tan(-a)=-\tan(a)}
You can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input.
Note: to formally prove the formula correct, it would have to be shown that
−
3
p
i
4
{\displaystyle {-3pi \over 4}}
< right hand side <
5
p
i
4
{\displaystyle {5pi \over 4}}
due to
tan
(
)
{\displaystyle \tan()}
periodicity.
| #EchoLisp | EchoLisp |
(lib 'math)
(lib 'match)
(math-precision 1.e-10)
;; formally derive (tan ..) expressions
;; copied from Racket
;; adapted and improved for performance
(define (reduce e)
;; (set! rcount (1+ rcount)) ;; # of calls
(match e
[(? number? a) a]
[('+ (? number? a) (? number? b)) (+ a b)]
[('- (? number? a) (? number? b)) (- a b)]
[('- (? number? a)) (- a)]
[('* (? number? a) (? number? b)) (* a b)]
[('/ (? number? a) (? number? b)) (/ a b)] ; patch
[( '+ a b) (reduce `(+ ,(reduce a) ,(reduce b)))]
[( '- a b) (reduce `(- ,(reduce a) ,(reduce b)))]
[( '- a) (reduce `(- ,(reduce a)))]
[( '* a b) (reduce `(* ,(reduce a) ,(reduce b)))]
[( '/ a b) (reduce `(/ ,(reduce a) ,(reduce b)))]
[( 'tan ('arctan a)) (reduce a)]
[( 'tan ( '- a)) (reduce `(- (tan ,a)))]
;; x 100 # calls reduction : derive (tan ,a) only once
[( 'tan ( '+ a b))
(let ((alpha (reduce `(tan ,a))) (beta (reduce `(tan ,b))))
(reduce `(/ (+ ,alpha ,beta) (- 1 (* ,alpha ,beta)))))]
[( 'tan ( '+ a b c ...)) (reduce `(tan (+ ,a (+ ,b ,@c))))]
[( 'tan ( '- a b))
(let ((alpha (reduce `(tan ,a))) (beta (reduce `(tan ,b))))
(reduce `(/ (- ,alpha ,beta) (+ 1 (* ,alpha ,beta)))))]
;; add formula for (tan 2 (arctan a)) = 2 a / (1 - a^2))
[( 'tan ( '* 2 ('arctan a))) (reduce `(/ (* 2 ,a) (- 1 (* ,a ,a))))]
[( 'tan ( '* 1 ('arctan a))) (reduce a)] ; added
[( 'tan ( '* (? number? n) a))
(cond [(< n 0) (reduce `(- (tan (* ,(- n) ,a))))]
[(= n 0) 0]
[(= n 1) (reduce `(tan ,a))]
[(even? n)
(let ((alpha (reduce `(tan (* ,(/ n 2) ,a))))) ;; # calls reduction
(reduce `(/ (* 2 ,alpha) (- 1 (* ,alpha ,alpha)))))]
[else (reduce `(tan (+ ,a (* ,(- n 1) ,a))))])]
))
(define (task)
(for ((f machins))
(if (~= 1 (reduce f))
(writeln '👍 f '⟾ 1 )
(writeln '❌ f '➽ (reduce f) ))))
|
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #ACL2 | ACL2 | (cw "~x0" (char-code #\a))
(cw "~x0" (code-char 97)) |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #Action.21 | Action! | PROC Main()
CHAR c=['a]
BYTE b=[97]
Put(c) Put('=) PrintBE(c)
PrintB(b) Put('=) Put(b)
RETURN |
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. | #F.23 | F# | open Microsoft.FSharp.Collections
let cholesky a =
let calc (a: float[,]) (l: float[,]) i j =
let c1 j =
let sum = List.sumBy (fun k -> l.[j, k] ** 2.0) [0..j - 1]
sqrt (a.[j, j] - sum)
let c2 i j =
let sum = List.sumBy (fun k -> l.[i, k] * l.[j, k]) [0..j - 1]
(1.0 / l.[j, j]) * (a.[i, j] - sum)
if j > i then 0.0 else
if i = j
then c1 j
else c2 i j
let l = Array2D.zeroCreate (Array2D.length1 a) (Array2D.length2 a)
Array2D.iteri (fun i j _ -> l.[i, j] <- calc a l i j) l
l
let printMat a =
let arrow = (Array2D.length2 a |> float) / 2.0 |> int
let c = cholesky a
for row in 0..(Array2D.length1 a) - 1 do
for col in 0..(Array2D.length2 a) - 1 do
printf "%.5f,\t" a.[row, col]
printf (if arrow = row then "--> \t" else "\t\t")
for col in 0..(Array2D.length2 c) - 1 do
printf "%.5f,\t" c.[row, col]
printfn ""
let ex1 = array2D [
[25.0; 15.0; -5.0];
[15.0; 18.0; 0.0];
[-5.0; 0.0; 11.0]]
let ex2 = array2D [
[18.0; 22.0; 54.0; 42.0];
[22.0; 70.0; 86.0; 62.0];
[54.0; 86.0; 174.0; 134.0];
[42.0; 62.0; 134.0; 106.0]]
printfn "ex1:"
printMat ex1
printfn "ex2:"
printMat ex2
|
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
| #Common_Lisp | Common Lisp |
;; Author: Amir Teymuri, Saturday 20.10.2018
(defparameter *possible-dates*
'((15 . may) (16 . may) (19 . may)
(17 . june) (18 . june)
(14 . july) (16 . july)
(14 . august) (15 . august) (17 . august)))
(defun unique-date-parts (possible-dates &key (alist-look-at #'car) (alist-r-assoc #'assoc))
(let* ((date-parts (mapcar alist-look-at possible-dates))
(unique-date-parts (remove-if #'(lambda (part) (> (count part date-parts) 1)) date-parts)))
(mapcar #'(lambda (part) (funcall alist-r-assoc part possible-dates))
unique-date-parts)))
(defun person (person possible-dates)
"Who's turn is it to think?"
(case person
('albert (unique-date-parts possible-dates :alist-look-at #'cdr :alist-r-assoc #'rassoc))
('bernard (unique-date-parts possible-dates :alist-look-at #'car :alist-r-assoc #'assoc))))
(defun cheryls-birthday (possible-dates)
(person 'albert
(person 'bernard
(set-difference
possible-dates
(person 'bernard possible-dates)
:key #'cdr))))
(cheryls-birthday *possible-dates*) ;; => ((16 . JULY))
|
http://rosettacode.org/wiki/Checkpoint_synchronization | Checkpoint synchronization | The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before starting another one. Putting details together is the checkpoint at which tasks synchronize themselves before going their paths apart.
The task
Implement checkpoint synchronization in your language.
Make sure that the solution is race condition-free. Note that a straightforward solution based on events is exposed to race condition. Let two tasks A and B need to be synchronized at a checkpoint. Each signals its event (EA and EB correspondingly), then waits for the AND-combination of the events (EA&EB) and resets its event. Consider the following scenario: A signals EA first and gets blocked waiting for EA&EB. Then B signals EB and loses the processor. Then A is released (both events are signaled) and resets EA. Now if B returns and enters waiting for EA&EB, it gets lost.
When a worker is ready it shall not continue before others finish. A typical implementation bug is when a worker is counted twice within one working cycle causing its premature completion. This happens when the quickest worker serves its cycle two times while the laziest one is lagging behind.
If you can, implement workers joining and leaving.
| #J | J | import java.util.Scanner;
import java.util.Random;
public class CheckpointSync{
public static void main(String[] args){
System.out.print("Enter number of workers to use: ");
Scanner in = new Scanner(System.in);
Worker.nWorkers = in.nextInt();
System.out.print("Enter number of tasks to complete:");
runTasks(in.nextInt());
}
/*
* Informs that workers started working on the task and
* starts running threads. Prior to proceeding with next
* task syncs using static Worker.checkpoint() method.
*/
private static void runTasks(int nTasks){
for(int i = 0; i < nTasks; i++){
System.out.println("Starting task number " + (i+1) + ".");
runThreads();
Worker.checkpoint();
}
}
/*
* Creates a thread for each worker and runs it.
*/
private static void runThreads(){
for(int i = 0; i < Worker.nWorkers; i ++){
new Thread(new Worker(i+1)).start();
}
}
/*
* Worker inner static class.
*/
public static class Worker implements Runnable{
public Worker(int threadID){
this.threadID = threadID;
}
public void run(){
work();
}
/*
* Notifies that thread started running for 100 to 1000 msec.
* Once finished increments static counter 'nFinished'
* that counts number of workers finished their work.
*/
private synchronized void work(){
try {
int workTime = rgen.nextInt(900) + 100;
System.out.println("Worker " + threadID + " will work for " + workTime + " msec.");
Thread.sleep(workTime); //work for 'workTime'
nFinished++; //increases work finished counter
System.out.println("Worker " + threadID + " is ready");
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
/*
* Used to synchronize Worker threads using 'nFinished' static integer.
* Waits (with step of 10 msec) until 'nFinished' equals to 'nWorkers'.
* Once they are equal resets 'nFinished' counter.
*/
public static synchronized void checkpoint(){
while(nFinished != nWorkers){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
nFinished = 0;
}
/* inner class instance variables */
private int threadID;
/* static variables */
private static Random rgen = new Random();
private static int nFinished = 0;
public static int nWorkers = 0;
}
} |
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
| #Go | Go | package main
import "fmt"
func main() {
var a []interface{}
a = append(a, 3)
a = append(a, "apples", "oranges")
fmt.Println(a)
} |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #MATLAB | MATLAB | >> nchoosek((0:4),3)
ans =
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4 |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #Red | Red | >> if 10 > 2 [print "ten is bigger"]
ten is bigger |
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}}}
.
| #Crystal | Crystal | def extended_gcd(a, b)
last_remainder, remainder = a.abs, b.abs
x, last_x = 0, 1
until remainder == 0
tmp = remainder
quotient, remainder = last_remainder.divmod(remainder)
last_remainder = tmp
x, last_x = last_x - quotient * x, x
end
return last_remainder, last_x * (a < 0 ? -1 : 1)
end
def invmod(e, et)
g, x = extended_gcd(e, et)
unless g == 1
raise "Multiplicative inverse modulo does not exist"
end
return x % et
end
def chinese_remainder(mods, remainders)
max = mods.product
series = remainders.zip(mods).map { |r, m| r * max * invmod(max // m, m) // m }
return series.sum % max
end
puts chinese_remainder([3, 5, 7], [2, 3, 2])
puts chinese_remainder([5, 7, 9, 11], [1, 2, 3, 4])
|
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}}}
.
| #D | D | import std.stdio, std.algorithm;
T chineseRemainder(T)(in T[] n, in T[] a) pure nothrow @safe @nogc
in {
assert(n.length == a.length);
} body {
static T mulInv(T)(T a, T b) pure nothrow @safe @nogc {
auto b0 = b;
T x0 = 0, x1 = 1;
if (b == 1)
return T(1);
while (a > 1) {
immutable q = a / b;
immutable amb = a % b;
a = b;
b = amb;
immutable xqx = x1 - q * x0;
x1 = x0;
x0 = xqx;
}
if (x1 < 0)
x1 += b0;
return x1;
}
immutable prod = reduce!q{a * b}(T(1), n);
T p = 1, sm = 0;
foreach (immutable i, immutable ni; n) {
p = prod / ni;
sm += a[i] * mulInv(p, ni) * p;
}
return sm % prod;
}
void main() {
immutable n = [3, 5, 7],
a = [2, 3, 2];
chineseRemainder(n, a).writeln;
} |
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.
| #J | J | chowla=: >: -~ >:@#.~/.~&.q: NB. sum of factors - (n + 1)
intsbelow=: (2 }. i.)"0
countPrimesbelow=: +/@(0 = chowla)@intsbelow
findPerfectsbelow=: (#~ <: = chowla)@intsbelow |
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.
| #Java | Java |
public class Chowla {
public static void main(String[] args) {
int[] chowlaNumbers = findChowlaNumbers(37);
for (int i = 0; i < chowlaNumbers.length; i++) {
System.out.printf("chowla(%d) = %d%n", (i+1), chowlaNumbers[i]);
}
System.out.println();
int[][] primes = countPrimes(100, 10_000_000);
for (int i = 0; i < primes.length; i++) {
System.out.printf(Locale.US, "There is %,d primes up to %,d%n", primes[i][1], primes[i][0]);
}
System.out.println();
int[] perfectNumbers = findPerfectNumbers(35_000_000);
for (int i = 0; i < perfectNumbers.length; i++) {
System.out.printf("%d is a perfect number%n", perfectNumbers[i]);
}
System.out.printf(Locale.US, "There are %d perfect numbers < %,d%n", perfectNumbers.length, 35_000_000);
}
public static int chowla(int n) {
if (n < 0) throw new IllegalArgumentException("n is not positive");
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;
}
protected static int[][] countPrimes(int power, int limit) {
int count = 0;
int[][] num = new int[countMultiplicity(limit, power)][2];
for (int n = 2, i=0; n <= limit; n++) {
if (chowla(n) == 0) count++;
if (n % power == 0) {
num[i][0] = power;
num[i][1] = count;
i++;
power *= 10;
}
}
return num;
}
protected static int countMultiplicity(int limit, int start) {
int count = 0;
int cur = limit;
while(cur >= start) {
count++;
cur = cur/10;
}
return count;
}
protected static int[] findChowlaNumbers(int limit) {
int[] num = new int[limit];
for (int i = 0; i < limit; i++) {
num[i] = chowla(i+1);
}
return num;
}
protected static int[] findPerfectNumbers(int limit) {
int count = 0;
int[] num = new int[count];
int k = 2, kk = 3, p;
while ((p = k * kk) < limit) {
if (chowla(p) == p - 1) {
num = increaseArr(num);
num[count++] = p;
}
k = kk + 1;
kk += k;
}
return num;
}
private static int[] increaseArr(int[] arr) {
int[] tmp = new int[arr.length + 1];
System.arraycopy(arr, 0, tmp, 0, arr.length);
return tmp;
}
}
|
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.
| #PHP | PHP | <?php
$zero = function($f) { return function ($x) { return $x; }; };
$succ = function($n) {
return function($f) use (&$n) {
return function($x) use (&$n, &$f) {
return $f( ($n($f))($x) );
};
};
};
$add = function($n, $m) {
return function($f) use (&$n, &$m) {
return function($x) use (&$f, &$n, &$m) {
return ($m($f))(($n($f))($x));
};
};
};
$mult = function($n, $m) {
return function($f) use (&$n, &$m) {
return function($x) use (&$f, &$n, &$m) {
return ($m($n($f)))($x);
};
};
};
$power = function($b,$e) {
return $e($b);
};
$to_int = function($f) {
$count_up = function($i) { return $i+1; };
return ($f($count_up))(0);
};
$from_int = function($x) {
$countdown = function($i) use (&$countdown) {
global $zero, $succ;
if ( $i == 0 ) {
return $zero;
} else {
return $succ($countdown($i-1));
};
};
return $countdown($x);
};
$three = $succ($succ($succ($zero)));
$four = $from_int(4);
foreach (array($add($three,$four), $mult($three,$four),
$power($three,$four), $power($four,$three)) as $ch) {
print($to_int($ch));
print("\n");
}
?> |
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.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Type MyClass
Private:
myInt_ As Integer
Public:
Declare Constructor(myInt_ As Integer)
Declare Property MyInt() As Integer
Declare Function Treble() As Integer
End Type
Constructor MyClass(myInt_ As Integer)
This.myInt_ = myInt_
End Constructor
Property MyClass.MyInt() As Integer
Return myInt_
End Property
Function MyClass.Treble() As Integer
Return 3 * myInt_
End Function
Dim mc As MyClass = MyClass(24)
Print mc.MyInt, mc.Treble()
Print "Press any key to quit the program"
Sleep |
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)
| #jq | jq | # This definition of "until" is included in recent versions (> 1.4) of jq
# Emit the first input that satisfied the condition
def until(cond; next):
def _until:
if cond then . else (next|_until) end;
_until;
# Euclidean 2d distance
def dist(x;y):
[x[0] - y[0], x[1] - y[1]] | map(.*.) | add | sqrt; |
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
| #Python | Python | funcs = []
for i in range(10):
funcs.append(lambda: i * i)
print funcs[3]() # prints 81 |
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
| #Quackery | Quackery | [ table ] is functions ( n --> [ )
10 times
[ i^ ' [ dup * ] join
' functions put ]
5 functions do echo |
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
| #F.23 | F# | open System
let add (a:double, b:double) (x:double, y:double) = (a + x, b + y)
let sub (a:double, b:double) (x:double, y:double) = (a - x, b - y)
let magSqr (a:double, b:double) = a * a + b * b
let mag a:double = Math.Sqrt(magSqr a)
let mul (a:double, b:double) c = (a * c, b * c)
let div2 (a:double, b:double) c = (a / c, b / c)
let perp (a:double, b:double) = (-b, a)
let norm a = div2 a (mag a)
let circlePoints p q (radius:double) =
let diameter = radius * 2.0
let pq = sub p q
let magPQ = mag pq
let midpoint = div2 (add p q) 2.0
let halfPQ = magPQ / 2.0
let magMidC = Math.Sqrt(Math.Abs(radius * radius - halfPQ * halfPQ))
let midC = mul (norm (perp pq)) magMidC
let center1 = add midpoint midC
let center2 = sub midpoint midC
if radius = 0.0 then None
else if p = q then None
else if diameter < magPQ then None
else Some (center1, center2)
[<EntryPoint>]
let main _ =
printfn "%A" (circlePoints (0.1234, 0.9876) (0.8765, 0.2345) 2.0)
printfn "%A" (circlePoints (0.0, 2.0) (0.0, 0.0) 1.0)
printfn "%A" (circlePoints (0.1234, 0.9876) (0.1234, 0.9876) 2.0)
printfn "%A" (circlePoints (0.1234, 0.9876) (0.8765, 0.2345) 0.5)
printfn "%A" (circlePoints (0.1234, 0.9876) (0.1234, 0.1234) 0.0)
0 // return an integer exit code |
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).
| #D | D | import std.stdio;
// 10 heavenly stems
immutable tiangan=[
["甲","乙","丙","丁","戊","己","庚","辛","壬","癸"],
["jiă","yĭ","bĭng","dīng","wù","jĭ","gēng","xīn","rén","gŭi"]
];
// 12 terrestrial branches
immutable dizhi=[
["子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"],
["zĭ","chŏu","yín","măo","chén","sì","wŭ","wèi","shēn","yŏu","xū","hài"]
];
// 5 elements
immutable wuxing=[
["木","火","土","金","水"],
["mù","huǒ","tǔ","jīn","shuǐ"],
["wood","fire","earth","metal","water"]
];
// 12 symbolic animals
immutable shengxiao=[
["鼠","牛","虎","兔","龍","蛇","馬","羊","猴","鸡","狗","豬"],
["shǔ","niú","hǔ","tù","lóng","shé","mǎ","yáng","hóu","jī","gǒu","zhū"],
["rat","ox","tiger","rabbit","dragon","snake","horse","goat","monkey","rooster","dog","pig"]
];
// yin yang
immutable yinyang=[
["阳","阴"],
["yáng","yīn"]
];
void main(string[] args) {
process(args[1..$]);
}
void process(string[] years) {
import std.conv;
foreach(yearStr; years) {
try {
auto year = to!int(yearStr);
auto cy = year - 4;
auto stem = cy % 10;
auto branch = cy % 12;
writefln("%4s %-11s %-7s %-10s%s", year,tiangan[0][stem]~dizhi[0][branch], wuxing[0][stem/2], shengxiao[0][branch], yinyang[0][year%2]);
writefln(" %-12s%-8s%-10s%s", tiangan[1][stem]~dizhi[1][branch], wuxing[1][stem/2], shengxiao[1][branch], yinyang[1][year%2]);
writefln(" %2s/60 %-7s%s", cy%60+1, wuxing[2][stem/2], shengxiao[2][branch]);
writeln;
} catch (ConvException e) {
stderr.writeln("Not a valid year: ", yearStr);
}
}
}
|
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an unusual filename: `Abdu'l-Bahá.txt
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program verifFic.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ OPEN, 5 @ Linux syscall
.equ CLOSE, 6 @ Linux syscall
.equ O_RDWR, 0x0002 /* open for reading and writing */
/*******************************************/
/* Fichier des macros */
/********************************************/
.include "../../ficmacros.s"
/* Initialized data */
.data
szMessFound1: .asciz "File 1 found.\n"
szMessFound2: .asciz "File 2 found.\n"
szMessNotFound1: .asciz "File 1 not found.\n"
szMessNotFound2: .asciz "File 2 not found.\n"
szMessNotAuth2: .asciz "File 2 permission denied.\n"
szCarriageReturn: .asciz "\n"
/* areas strings */
szFicName1: .asciz "test1.txt"
szFicName2: .asciz "/debian-binary"
/* UnInitialized data */
.bss
/* code section */
.text
.global main
main: /* entry of program */
push {fp,lr} /* saves 2 registers */
/*************************************
open file 1
************************************/
ldr r0,iAdrszFicName1 @ file name
mov r1,#O_RDWR @ flags
mov r2,#0 @ mode
mov r7, #OPEN @ call system OPEN
swi 0
cmp r0,#0 @ error ?
ble 1f
mov r1,r0 @ FD
ldr r0,iAdrszMessFound1
bl affichageMess
@ close file
mov r0,r1 @ Fd
mov r7, #CLOSE
swi 0
b 2f
1:
ldr r0,iAdrszMessNotFound1
bl affichageMess
2:
/*************************************
open file 2
************************************/
ldr r0,iAdrszFicName2 @ file name
mov r1,#O_RDWR @ flags
mov r2,#0 @ mode
mov r7, #OPEN @ call system OPEN
swi 0
vidregtit verif
cmp r0,#-13 @ permission denied
beq 4f
cmp r0,#0 @ error ?
ble 3f
mov r1,r0 @ FD
ldr r0,iAdrszMessFound2
bl affichageMess
@ close file
mov r0,r1 @ Fd
mov r7, #CLOSE
swi 0
b 100f
3:
ldr r0,iAdrszMessNotFound2
bl affichageMess
b 100f
4:
ldr r0,iAdrszMessNotAuth2
bl affichageMess
100: /* standard end of the program */
mov r0, #0 @ return code
pop {fp,lr} @restaur 2 registers
mov r7, #EXIT @ request to exit program
swi 0 @ perform the system call
iAdrszFicName1: .int szFicName1
iAdrszFicName2: .int szFicName2
iAdrszMessFound1: .int szMessFound1
iAdrszMessFound2: .int szMessFound2
iAdrszMessNotFound1: .int szMessNotFound1
iAdrszMessNotFound2: .int szMessNotFound2
iAdrszMessNotAuth2: .int szMessNotAuth2
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {fp,lr} /* save registres */
push {r0,r1,r2,r7} /* save others registers */
mov r2,#0 /* counter length */
1: /* loop length calculation */
ldrb r1,[r0,r2] /* read octet start position + index */
cmp r1,#0 /* if 0 its over */
addne r2,r2,#1 /* else add 1 in the length */
bne 1b /* and loop */
/* so here r2 contains the length of the message */
mov r1,r0 /* address message in r1 */
mov r0,#STDOUT /* code to write to the standard output Linux */
mov r7, #WRITE /* code call system "write" */
swi #0 /* call systeme */
pop {r0,r1,r2,r7} /* restaur others registers */
pop {fp,lr} /* restaur des 2 registres */
bx lr /* return */
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.