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/Attractive_numbers | Attractive numbers | A number is an attractive number if the number of its prime factors (whether distinct or not) is also prime.
Example
The number 20, whose prime decomposition is 2 × 2 × 5, is an attractive number because the number of its prime factors (3) is also prime.
Task
Show sequence items up to 120.
Reference
The OEIS entry: A063989: Numbers with a prime number of prime divisors.
| #PL.2FM | PL/M | 100H:
BDOS: PROCEDURE (F, ARG); DECLARE F BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PUT$CHAR: PROCEDURE (CH); DECLARE CH BYTE; CALL BDOS(2,CH); END PUT$CHAR;
DECLARE MAXIMUM LITERALLY '120';
PRINT4: PROCEDURE (N);
DECLARE (N, MAGN, Z) BYTE;
CALL PUT$CHAR(' ');
MAGN = 100;
Z = 0;
DO WHILE MAGN > 0;
IF NOT Z AND N < MAGN THEN
CALL PUT$CHAR(' ');
ELSE DO;
CALL PUT$CHAR('0' + N/MAGN);
N = N MOD MAGN;
Z = 1;
END;
MAGN = MAGN/10;
END;
END PRINT4;
NEW$LINE: PROCEDURE;
CALL PUT$CHAR(13);
CALL PUT$CHAR(10);
END NEW$LINE;
SIEVE: PROCEDURE (MAX, PRIME);
DECLARE PRIME ADDRESS;
DECLARE (I, J, MAX, P BASED PRIME) BYTE;
P(0)=0;
P(1)=0;
DO I=2 TO MAX; P(I)=1; END;
DO I=2 TO SHR(MAX,1);
IF P(I) THEN DO J=SHL(I,1) TO MAX BY I;
P(J) = 0;
END;
END;
END SIEVE;
FACTORS: PROCEDURE (N, MAX, PRIME) BYTE;
DECLARE PRIME ADDRESS;
DECLARE (I, J, N, MAX, F, P BASED PRIME) BYTE;
F = 0;
DO I=2 TO MAX;
IF P(I) THEN DO WHILE N MOD I = 0;
F = F + 1;
N = N / I;
END;
END;
RETURN F;
END FACTORS;
ATTRACTIVE: PROCEDURE(N, MAX, PRIME) BYTE;
DECLARE PRIME ADDRESS;
DECLARE (N, MAX, P BASED PRIME) BYTE;
RETURN P(FACTORS(N, MAX, PRIME));
END ATTRACTIVE;
DECLARE (I, COL) BYTE INITIAL (0, 0);
CALL SIEVE(MAXIMUM, .MEMORY);
DO I=2 TO MAXIMUM;
IF ATTRACTIVE(I, MAXIMUM, .MEMORY) THEN DO;
CALL PRINT4(I);
COL = COL + 1;
IF COL MOD 18 = 0 THEN CALL NEW$LINE;
END;
END;
CALL EXIT;
EOF |
http://rosettacode.org/wiki/Averages/Mean_time_of_day | Averages/Mean time of day | Task[edit]
A particular activity of bats occurs at these times of the day:
23:00:17, 23:40:20, 00:12:45, 00:17:19
Using the idea that there are twenty-four hours in a day,
which is analogous to there being 360 degrees in a circle,
map times of day to and from angles;
and using the ideas of Averages/Mean angle
compute and show the average time of the nocturnal activity
to an accuracy of one second of time.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Scheme | Scheme |
(import (scheme base)
(scheme inexact)
(scheme read)
(scheme write)
(srfi 1)) ; for fold
;; functions copied from "Averages/Mean angle" task
(define (average l)
(/ (fold + 0 l) (length l)))
(define pi 3.14159265358979323846264338327950288419716939937510582097)
(define (radians a)
(* pi 1/180 a))
(define (degrees a)
(* 180 (/ 1 pi) a))
(define (mean-angle angles)
(let* ((angles (map radians angles))
(cosines (map cos angles))
(sines (map sin angles)))
(degrees (atan (average sines) (average cosines)))))
;; -- new functions for this task
(define (time->angle time)
(let* ((time2 ; replaces : with space in string
(string-map (lambda (c) (if (char=? c #\:) #\space c)) time))
(string-port (open-input-string time2))
(hour (read string-port))
(minutes (read string-port))
(seconds (read string-port)))
(/ (* 360 (+ (* hour 3600) (* minutes 60) seconds))
(* 24 60 60))))
(define (angle->time angle)
(let* ((nom-angle (if (negative? angle) (+ 360 angle) angle))
(time (/ (* nom-angle 24 60 60) 360))
(hour (exact (floor (/ time 3600))))
(minutes (exact (floor (/ (- time (* 3600 hour)) 60))))
(seconds (exact (floor (- time (* 3600 hour) (* 60 minutes))))))
(string-append (number->string hour)
":"
(number->string minutes)
":"
(number->string seconds))))
(define (mean-time-of-day times)
(angle->time (mean-angle (map time->angle times))))
(write (mean-time-of-day '("23:00:17" "23:40:20" "00:12:45" "00:17:19")))
(newline)
|
http://rosettacode.org/wiki/Averages/Mean_angle | Averages/Mean angle | When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle.
If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the second was of 10 degrees then the average of the numbers is 180 degrees, whereas if you can note that 350 degrees is equivalent to -10 degrees and so you have two readings at 10 degrees either side of zero degrees leading to a more fitting mean angle of zero degrees.
To calculate the mean angle of several angles:
Assume all angles are on the unit circle and convert them to complex numbers expressed in real and imaginary form.
Compute the mean of the complex numbers.
Convert the complex mean to polar coordinates whereupon the phase of the complex mean is the required angular mean.
(Note that, since the mean is the sum divided by the number of numbers, and division by a positive real number does not affect the angle, you can also simply compute the sum for step 2.)
You can alternatively use this formula:
Given the angles
α
1
,
…
,
α
n
{\displaystyle \alpha _{1},\dots ,\alpha _{n}}
the mean is computed by
α
¯
=
atan2
(
1
n
⋅
∑
j
=
1
n
sin
α
j
,
1
n
⋅
∑
j
=
1
n
cos
α
j
)
{\displaystyle {\bar {\alpha }}=\operatorname {atan2} \left({\frac {1}{n}}\cdot \sum _{j=1}^{n}\sin \alpha _{j},{\frac {1}{n}}\cdot \sum _{j=1}^{n}\cos \alpha _{j}\right)}
Task[edit]
write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle.
(You should use a built-in function if you have one that does this for degrees or radians).
Use the function to compute the means of these lists of angles (in degrees):
[350, 10]
[90, 180, 270, 360]
[10, 20, 30]
Show your output here.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
include "math.s7i";
include "complex.s7i";
const func float: deg2rad (in float: degree) is
return degree * PI / 180.0;
const func float: rad2deg (in float: rad) is
return rad * 180.0 / PI;
const func float: meanAngle (in array float: degrees) is func
result
var float: mean is 0.0;
local
var float: degree is 0.0;
var complex: sum is complex.value;
begin
for degree range degrees do
sum +:= polar(1.0, deg2rad(degree));
end for;
mean := rad2deg(arg(sum / complex conv length(degrees)));
end func;
const proc: main is func
begin
writeln(meanAngle([] (350.0, 10.0)) digits 4);
writeln(meanAngle([] (90.0, 180.0, 270.0, 360.0)) digits 4);
writeln(meanAngle([] (10.0, 20.0, 30.0)) digits 4);
end func; |
http://rosettacode.org/wiki/Averages/Mean_angle | Averages/Mean angle | When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle.
If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the second was of 10 degrees then the average of the numbers is 180 degrees, whereas if you can note that 350 degrees is equivalent to -10 degrees and so you have two readings at 10 degrees either side of zero degrees leading to a more fitting mean angle of zero degrees.
To calculate the mean angle of several angles:
Assume all angles are on the unit circle and convert them to complex numbers expressed in real and imaginary form.
Compute the mean of the complex numbers.
Convert the complex mean to polar coordinates whereupon the phase of the complex mean is the required angular mean.
(Note that, since the mean is the sum divided by the number of numbers, and division by a positive real number does not affect the angle, you can also simply compute the sum for step 2.)
You can alternatively use this formula:
Given the angles
α
1
,
…
,
α
n
{\displaystyle \alpha _{1},\dots ,\alpha _{n}}
the mean is computed by
α
¯
=
atan2
(
1
n
⋅
∑
j
=
1
n
sin
α
j
,
1
n
⋅
∑
j
=
1
n
cos
α
j
)
{\displaystyle {\bar {\alpha }}=\operatorname {atan2} \left({\frac {1}{n}}\cdot \sum _{j=1}^{n}\sin \alpha _{j},{\frac {1}{n}}\cdot \sum _{j=1}^{n}\cos \alpha _{j}\right)}
Task[edit]
write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle.
(You should use a built-in function if you have one that does this for degrees or radians).
Use the function to compute the means of these lists of angles (in degrees):
[350, 10]
[90, 180, 270, 360]
[10, 20, 30]
Show your output here.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Sidef | Sidef | func mean_angle(angles) {
atan2(
Math.avg(angles.map{ .deg2rad.sin }...),
Math.avg(angles.map{ .deg2rad.cos }...),
) -> rad2deg
}
[[350,10], [90,180,270,360], [10,20,30]].each { |angles|
say "The mean angle of #{angles.dump} is: #{ '%.2f' % mean_angle(angles)} degrees"
} |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches to this. One is to sort the elements, and then pick the element(s) in the middle.
Sorting would take at least O(n logn). Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s). This would also take O(n logn). The best solution is to use the selection algorithm to find the median in O(n) time.
See also
Quickselect_algorithm
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Lasso | Lasso | define median_ext(a::array) => {
#a->sort
if(#a->size % 2) => {
// odd numbered element array, pick middle
return #a->get(#a->size / 2 + 1)
else
// even number elements in array
return (#a->get(#a->size / 2) + #a->get(#a->size / 2 + 1)) / 2.0
}
}
median_ext(array(3,2,7,6)) // 4.5
median_ext(array(3,2,9,7,6)) // 6 |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches to this. One is to sort the elements, and then pick the element(s) in the middle.
Sorting would take at least O(n logn). Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s). This would also take O(n logn). The best solution is to use the selection algorithm to find the median in O(n) time.
See also
Quickselect_algorithm
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Liberty_BASIC | Liberty BASIC |
dim a( 100), b( 100) ' assumes we will not have vectors of more terms...
a$ ="4.1,5.6,7.2,1.7,9.3,4.4,3.2"
print "Median is "; median( a$) ' 4.4 7 terms
print
a$ ="4.1,7.2,1.7,9.3,4.4,3.2"
print "Median is "; median( a$) ' 4.25 6 terms
print
a$ ="4.1,4,1.2,6.235,7868.33" ' 4.1
print "Median of "; a$; " is "; median( a$)
print
a$ ="1,5,3,2,4" ' 3
print "Median of "; a$; " is "; median( a$)
print
a$ ="1,5,3,6,4,2" ' 3.5
print "Median of "; a$; " is "; median( a$)
print
a$ ="4.4,2.3,-1.7,7.5,6.6,0.0,1.9,8.2,9.3,4.5" ' 4.45
print "Median of "; a$; " is "; median( a$)
end
function median( a$)
i =1
do
v$ =word$( a$, i, ",")
if v$ ="" then exit do
print v$,
a( i) =val( v$)
i =i +1
loop until 0
print
sort a(), 1, i -1
for j =1 to i -1
print a( j),
next j
print
middle =( i -1) /2
intmiddle =int( middle)
if middle <>intmiddle then median= a( 1 +intmiddle) else median =( a( intmiddle) +a( intmiddle +1)) /2
end function
|
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of positive integers.
The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
A
(
x
1
,
…
,
x
n
)
=
x
1
+
⋯
+
x
n
n
{\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}}
The geometric mean is the
n
{\displaystyle n}
th root of the product of the list:
G
(
x
1
,
…
,
x
n
)
=
x
1
⋯
x
n
n
{\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}}
The harmonic mean is
n
{\displaystyle n}
divided by the sum of the reciprocal of each item in the list:
H
(
x
1
,
…
,
x
n
)
=
n
1
x
1
+
⋯
+
1
x
n
{\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Maxima | Maxima | /* built-in */
L: makelist(i, i, 1, 10)$
mean(L), numer; /* 5.5 */
geometric_mean(L), numer; /* 4.528728688116765 */
harmonic_mean(L), numer; /* 3.414171521474055 */ |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #Transd | Transd | #lang transd
MainModule : {
rem: 269696,
_start: (lambda
(with n (to-Int (sqrt rem))
(while (neq (mod (pow n 2) 1000000) rem) (+= n 1))
(lout n)
) )
} |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #UNIX_Shell | UNIX Shell | # Program to determine the smallest positive integer whose square
# has a decimal representation ending in the digits 269,696.
# Start with the smallest positive integer of them all
let trial_value=1
# Compute the remainder when the square of the current trial value is divided
# by 1,000,000.␣
while (( trial_value * trial_value % 1000000 != 269696 )); do
# As long as this value is not yet 269,696, increment
# our trial integer and try again.
let trial_value=trial_value+1
done
# To get here we must have found an integer whose square meets the
# condition; display that final result
echo $trial_value |
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #Forth | Forth | include lib/choose.4th ( n1 -- n2)
include lib/ctos.4th ( n -- a 1)
10 constant /[] \ maximum number of brackets
/[] string [] \ string with brackets
\ create string with brackets
: make[] ( --)
0 dup [] place /[] choose 0 ?do 2 choose 2* [char] [ + c>s [] +place loop
; \ empty string, fill with brackets
\ evaluate string
: eval[] ( --)
[] count 2dup over chars + >r swap type 0
begin \ setup string and count
over r@ < \ reached end of string?
while \ if not ..
dup 0< 0= \ unbalanced ]?
while \ if not ..
over c@ [char] \ - negate + swap char+ swap
repeat \ evaluate, goto next character
r> drop if ." NOT" then ." OK" cr drop
; \ evaluate string and print result
make[] eval[] |
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file | Append a record to the end of a text file | Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment.
This feature is most useful in the case of log files, where many jobs may be appending to the log file at the same time, or where care must be taken to avoid concurrently overwriting the same record from another job.
Task
Given a two record sample for a mythical "passwd" file:
Write these records out in the typical system format.
Ideally these records will have named fields of various types.
Close the file, then reopen the file for append.
Append a new record to the file and close the file again.
Take appropriate care to avoid concurrently overwrites from another job.
Open the file and demonstrate the new record has indeed written to the end.
Source record field types and contents.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
jsmith
x
1001
1000
Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]
/home/jsmith
/bin/bash
jdoe
x
1002
1000
Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]
/home/jdoe
/bin/bash
Record to be appended.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
xyz
x
1003
1000
X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]
/home/xyz
/bin/bash
Resulting file format: should mimic Linux's /etc/passwd file format with particular attention to the "," separator used in the GECOS field. But if the specific language has a particular or unique format of storing records in text file, then this format should be named and demonstrated with an additional example.
Expected output:
Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash
Finally: Provide a summary of the language's "append record" capabilities in a table. eg.
Append Capabilities.
Data Representation
IO
Library
Append
Possible
Automatic
Append
Multi-tasking
Safe
In core
On disk
C struct
CSV text file
glibc/stdio
☑
☑
☑ (Not all, eg NFS)
Alternatively: If the language's appends can not guarantee its writes will always append, then note this restriction in the table. If possible, provide an actual code example (possibly using file/record locking) to guarantee correct concurrent appends.
| #MATLAB_.2F_Octave | MATLAB / Octave | DS{1}.account='jsmith';
DS{1}.password='x';
DS{1}.UID=1001;
DS{1}.GID=1000;
DS{1}.fullname='Joe Smith';
DS{1}.office='Room 1007';
DS{1}.extension='(234)555-8917';
DS{1}.homephone='(234)555-0077';
DS{1}.email='[email protected]';
DS{1}.directory='/home/jsmith';
DS{1}.shell='/bin/bash';
DS{2}.account='jdoe';
DS{2}.password='x';
DS{2}.UID=1002;
DS{2}.GID=1000;
DS{2}.fullname='Jane Doe';
DS{2}.office='Room 1004';
DS{2}.extension='(234)555-8914';
DS{2}.homephone='(234)555-0044';
DS{2}.email='[email protected]';
DS{2}.directory='/home/jdoe';
DS{2}.shell='/bin/bash';
function WriteRecord(fid, rec)
fprintf(fid,"%s:%s:%i:%i:%s,%s,%s,%s,%s:%s%s\n", rec.account, rec.password, rec.UID, rec.GID, rec.fullname, rec.office, rec.extension, rec.homephone, rec.email, rec.directory, rec.shell);
return;
end
%% write
fid = fopen('passwd.txt','w');
WriteRecord(fid,DS{1});
WriteRecord(fid,DS{2});
fclose(fid);
new.account='xyz';
new.password='x';
new.UID=1003;
new.GID=1000;
new.fullname='X Yz';
new.office='Room 1003';
new.extension='(234)555-8913';
new.homephone='(234)555-0033';
new.email='[email protected]';
new.directory='/home/xyz';
new.shell='/bin/bash';
%% append
fid = fopen('passwd.txt','a+');
WriteRecord(fid,new);
fclose(fid);
% read password file
fid = fopen('passwd.txt','r');
while ~feof(fid)
printf('%s\n',fgetl(fid));
end;
fclose(fid); |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
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
| #Brat | Brat | h = [:] #Empty hash
h[:a] = 1 #Assign value
h[:b] = [1 2 3] #Assign another value
h2 = [a: 1, b: [1 2 3], 10 : "ten"] #Initialized hash
h2[:b][2] #Returns 3 |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #J | J |
NB. factor count is the product of the incremented powers of prime factors
factor_count =: [: */ [: >: _&q:
NB. N are the integers 1 to 10000
NB. FC are the corresponding factor counts
FC =: factor_count&> N=: >: i. 10000
NB. take from the integers N{~
NB. the indexes of truth I.
NB. the vector which doesn't equal itself when rotated by one position (~: _1&|.)
NB. where that vector is the maximum over all prefixes of the factor counts >./\FC
N{~I.(~: _1&|.)>./\FC
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
|
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #Java | Java | public class Antiprime {
static int countDivisors(int n) {
if (n < 2) return 1;
int count = 2; // 1 and n
for (int i = 2; i <= n/2; ++i) {
if (n%i == 0) ++count;
}
return count;
}
public static void main(String[] args) {
int maxDiv = 0, count = 0;
System.out.println("The first 20 anti-primes are:");
for (int n = 1; count < 20; ++n) {
int d = countDivisors(n);
if (d > maxDiv) {
System.out.printf("%d ", n);
maxDiv = d;
count++;
}
}
System.out.println();
}
} |
http://rosettacode.org/wiki/Atomic_updates | Atomic updates |
Task
Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to:
get the current value of any bucket
remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the transferred amount to ensure the values remain non-negative
In order to exercise this data type, create one set of buckets, and start three concurrent tasks:
As often as possible, pick two buckets and make their values closer to equal.
As often as possible, pick two buckets and arbitrarily redistribute their values.
At whatever rate is convenient, display (by any means) the total value and, optionally, the individual values of each bucket.
The display task need not be explicit; use of e.g. a debugger or trace tool is acceptable provided it is simple to set up to provide the display.
This task is intended as an exercise in atomic operations. The sum of the bucket values must be preserved even if the two tasks attempt to perform transfers simultaneously, and a straightforward solution is to ensure that at any time, only one transfer is actually occurring — that the transfer operation is atomic.
| #Scala | Scala |
object AtomicUpdates {
class Buckets(ns: Int*) {
import scala.actors.Actor._
val buckets = ns.toArray
case class Get(index: Int)
case class Transfer(fromIndex: Int, toIndex: Int, amount: Int)
case object GetAll
val handler = actor {
loop {
react {
case Get(index) => reply(buckets(index))
case Transfer(fromIndex, toIndex, amount) =>
assert(amount >= 0)
val actualAmount = Math.min(amount, buckets(fromIndex))
buckets(fromIndex) -= actualAmount
buckets(toIndex) += actualAmount
case GetAll => reply(buckets.toList)
}
}
}
def get(index: Int): Int = (handler !? Get(index)).asInstanceOf[Int]
def transfer(fromIndex: Int, toIndex: Int, amount: Int) = handler ! Transfer(fromIndex, toIndex, amount)
def getAll: List[Int] = (handler !? GetAll).asInstanceOf[List[Int]]
}
def randomPair(n: Int): (Int, Int) = {
import scala.util.Random._
val pair = (nextInt(n), nextInt(n))
if (pair._1 == pair._2) randomPair(n) else pair
}
def main(args: Array[String]) {
import scala.actors.Scheduler._
val buckets = new Buckets(List.range(1, 11): _*)
val stop = new java.util.concurrent.atomic.AtomicBoolean(false)
val latch = new java.util.concurrent.CountDownLatch(3)
execute {
while (!stop.get) {
val (i1, i2) = randomPair(10)
val (n1, n2) = (buckets.get(i1), buckets.get(i2))
val m = (n1 + n2) / 2
if (n1 < n2)
buckets.transfer(i2, i1, n2 - m)
else
buckets.transfer(i1, i2, n1 - m)
}
latch.countDown
}
execute {
while (!stop.get) {
val (i1, i2) = randomPair(10)
val n = buckets.get(i1)
buckets.transfer(i1, i2, if (n == 0) 0 else scala.util.Random.nextInt(n))
}
latch.countDown
}
execute {
for (i <- 1 to 20) {
val all = buckets.getAll
println(all.sum + ":" + all)
Thread.sleep(500)
}
stop.set(true)
latch.countDown
}
latch.await
shutdown
}
}
|
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #PicoLisp | PicoLisp | ...
~(assert (= N 42)) # Exists only in debug mode
... |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #PL.2FI | PL/I |
/* PL/I does not have an assert function as such, */
/* but it is something that can be implemented in */
/* any of several ways. A straight-forward way */
/* raises a user-defined interrupt. */
on condition (assert_failure) snap
put skip list ('Assert failure');
....
if a ^= b then signal condition(assert_failure);
/* Another way is to use the preprocessor, thus: */
%assert: procedure (a, b) returns (character);
return ('if ' || a || '^=' || b ||
' then signal condition(assert_failure);');
%end assert;
%activate assert;
assert(a, 42);
|
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Prolog | Prolog |
test(A):-
assertion(A==42).
|
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #PureBasic | PureBasic | Macro Assert(TEST,MSG="Assert: ")
CompilerIf #PB_Compiler_Debugger
If Not (TEST)
Debug MSG+" Line="+Str(#PB_Compiler_Line)+" in "+#PB_Compiler_File
CallDebugger
EndIf
CompilerEndIf
EndMacro |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #EGL | EGL | delegate callback( i int ) returns( int ) end
program ApplyCallbackToArray
function main()
values int[] = [ 1, 2, 3, 4, 5 ];
func callback = square;
for ( i int to values.getSize() )
values[ i ] = func( values[ i ] );
end
for ( i int to values.getSize() )
SysLib.writeStdout( values[ i ] );
end
end
function square( i int ) returns( int )
return( i * i );
end
end |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Elena | Elena | import system'routines;
PrintSecondPower(n){ console.writeLine(n * n) }
public program()
{
new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}.forEach:PrintSecondPower
} |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Python | Python | >>> from collections import defaultdict
>>> def modes(values):
count = defaultdict(int)
for v in values:
count[v] +=1
best = max(count.values())
return [k for k,v in count.items() if v == best]
>>> modes([1,3,6,6,6,6,7,7,12,12,17])
[6]
>>> modes((1,1,2,4,4))
[1, 4] |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
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
| #Free_Pascal | Free Pascal | program AssociativeArrayIteration;
{$mode delphi}{$ifdef windows}{$apptype console}{$endif}
uses Generics.Collections;
type
TlDictionary = TDictionary<string, Integer>;
TlPair = TPair<string,integer>;
var
i: Integer;
s: string;
lDictionary: TlDictionary;
lPair: TlPair;
begin
lDictionary := TlDictionary.Create;
try
lDictionary.Add('foo', 5);
lDictionary.Add('bar', 10);
lDictionary.Add('baz', 15);
lDictionary.AddOrSetValue('foo',6);
for lPair in lDictionary do
Writeln('Pair: ',Lpair.Key,' = ',lPair.Value);
for s in lDictionary.Keys do
Writeln('Key: ' + s);
for i in lDictionary.Values do
Writeln('Value: ', i);
finally
lDictionary.Free;
end;
end. |
http://rosettacode.org/wiki/Apply_a_digital_filter_(direct_form_II_transposed) | Apply a digital filter (direct form II transposed) | Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [1]
Task
Filter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667]
The signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]
| #Yabasic | Yabasic | sub filter(a(), b(), signal(), result())
local i, j, tmp
for i = 0 to arraysize(signal(), 1)
tmp = 0
for j = 0 to arraysize(b(), 1)
if (i-j<0) continue
tmp = tmp + b(j) * signal(i-j)
next
for j = 0 to arraysize(a(), 1)
if (i-j<0) continue
tmp = tmp - a(j) * result(i-j)
next
tmp = tmp / a(0)
result(i) = tmp
next
end sub
dim a(4), b(4), signal(20), result(20)
// a()
data 1, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17
// b()
data 0.16666667, 0.5, 0.5, 0.16666667
// signal()
data -0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412
data -0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044
data 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195
data 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293
data 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589
for i = 0 to 3 : read a(i) : next
for i = 0 to 3 : read b(i) : next
for i = 0 to 19 : read signal(i) : next
filter(a(),b(),signal(),result())
for i = 0 to 19
print result(i) using "%11.8f";
if mod(i+1, 5) <> 0 then
print ", ";
else
print
end if
next |
http://rosettacode.org/wiki/Apply_a_digital_filter_(direct_form_II_transposed) | Apply a digital filter (direct form II transposed) | Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [1]
Task
Filter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667]
The signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]
| #zkl | zkl | fcn direct_form_II_transposed_filter(b,a,signal){
out:=List.createLong(signal.len(),0.0); // vector of zeros
foreach i in (signal.len()){
tmp:=0.0;
foreach j in (b.len()){ if(i-j >=0) tmp += b[j]*signal[i-j] }
foreach j in (a.len()){ if(i-j >=0) tmp -= a[j]*out[i-j] }
out[i] = tmp/a[0];
}
out
} |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Frink | Frink |
mean[x] := length[x] > 0 ? sum[x] / length[x] : undef
|
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #GAP | GAP | Mean := function(v)
local n;
n := Length(v);
if n = 0 then
return 0;
else
return Sum(v)/n;
fi;
end;
Mean([3, 1, 4, 1, 5, 9]);
# 23/6 |
http://rosettacode.org/wiki/Attractive_numbers | Attractive numbers | A number is an attractive number if the number of its prime factors (whether distinct or not) is also prime.
Example
The number 20, whose prime decomposition is 2 × 2 × 5, is an attractive number because the number of its prime factors (3) is also prime.
Task
Show sequence items up to 120.
Reference
The OEIS entry: A063989: Numbers with a prime number of prime divisors.
| #Prolog | Prolog | prime_factors(N, Factors):-
S is sqrt(N),
prime_factors(N, Factors, S, 2).
prime_factors(1, [], _, _):-!.
prime_factors(N, [P|Factors], S, P):-
P =< S,
0 is N mod P,
!,
M is N // P,
prime_factors(M, Factors, S, P).
prime_factors(N, Factors, S, P):-
Q is P + 1,
Q =< S,
!,
prime_factors(N, Factors, S, Q).
prime_factors(N, [N], _, _).
is_prime(2):-!.
is_prime(N):-
0 is N mod 2,
!,
fail.
is_prime(N):-
N > 2,
S is sqrt(N),
\+is_composite(N, S, 3).
is_composite(N, S, P):-
P =< S,
0 is N mod P,
!.
is_composite(N, S, P):-
Q is P + 2,
Q =< S,
is_composite(N, S, Q).
attractive_number(N):-
prime_factors(N, Factors),
length(Factors, Len),
is_prime(Len).
print_attractive_numbers(From, To, _):-
From > To,
!.
print_attractive_numbers(From, To, C):-
(attractive_number(From) ->
writef('%4r', [From]),
(0 is C mod 20 -> nl ; true),
C1 is C + 1
;
C1 = C
),
Next is From + 1,
print_attractive_numbers(Next, To, C1).
main:-
print_attractive_numbers(1, 120, 1). |
http://rosettacode.org/wiki/Averages/Mean_time_of_day | Averages/Mean time of day | Task[edit]
A particular activity of bats occurs at these times of the day:
23:00:17, 23:40:20, 00:12:45, 00:17:19
Using the idea that there are twenty-four hours in a day,
which is analogous to there being 360 degrees in a circle,
map times of day to and from angles;
and using the ideas of Averages/Mean angle
compute and show the average time of the nocturnal activity
to an accuracy of one second of time.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Sidef | Sidef | func time2deg(t) {
(var m = t.match(/^(\d\d):(\d\d):(\d\d)$/)) || die "invalid time"
var (hh,mm,ss) = m.cap.map{.to_i}...
((hh ~~ 24.range) && (mm ~~ 60.range) && (ss ~~ 60.range)) || die "invalid time"
(hh*3600 + mm*60 + ss) * 360 / 86400
}
func deg2time(d) {
var sec = ((d % 360) * 86400 / 360)
"%02d:%02d:%02d" % (sec/3600, (sec%3600)/60, sec%60)
}
func mean_time(times) {
deg2time(mean_angle(times.map {|t| time2deg(t)}))
}
say mean_time(["23:00:17", "23:40:20", "00:12:45", "00:17:19"]) |
http://rosettacode.org/wiki/Averages/Mean_angle | Averages/Mean angle | When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle.
If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the second was of 10 degrees then the average of the numbers is 180 degrees, whereas if you can note that 350 degrees is equivalent to -10 degrees and so you have two readings at 10 degrees either side of zero degrees leading to a more fitting mean angle of zero degrees.
To calculate the mean angle of several angles:
Assume all angles are on the unit circle and convert them to complex numbers expressed in real and imaginary form.
Compute the mean of the complex numbers.
Convert the complex mean to polar coordinates whereupon the phase of the complex mean is the required angular mean.
(Note that, since the mean is the sum divided by the number of numbers, and division by a positive real number does not affect the angle, you can also simply compute the sum for step 2.)
You can alternatively use this formula:
Given the angles
α
1
,
…
,
α
n
{\displaystyle \alpha _{1},\dots ,\alpha _{n}}
the mean is computed by
α
¯
=
atan2
(
1
n
⋅
∑
j
=
1
n
sin
α
j
,
1
n
⋅
∑
j
=
1
n
cos
α
j
)
{\displaystyle {\bar {\alpha }}=\operatorname {atan2} \left({\frac {1}{n}}\cdot \sum _{j=1}^{n}\sin \alpha _{j},{\frac {1}{n}}\cdot \sum _{j=1}^{n}\cos \alpha _{j}\right)}
Task[edit]
write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle.
(You should use a built-in function if you have one that does this for degrees or radians).
Use the function to compute the means of these lists of angles (in degrees):
[350, 10]
[90, 180, 270, 360]
[10, 20, 30]
Show your output here.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Stata | Stata | mata
function meanangle(a) {
return(arg(sum(exp(C(0,a)))))
}
deg=pi()/180
meanangle((350,10)*deg)/deg
-1.61481e-15
meanangle((90,180,270,360)*deg)/deg
0
meanangle((10,20,30)*deg)/deg
20
end |
http://rosettacode.org/wiki/Averages/Mean_angle | Averages/Mean angle | When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle.
If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the second was of 10 degrees then the average of the numbers is 180 degrees, whereas if you can note that 350 degrees is equivalent to -10 degrees and so you have two readings at 10 degrees either side of zero degrees leading to a more fitting mean angle of zero degrees.
To calculate the mean angle of several angles:
Assume all angles are on the unit circle and convert them to complex numbers expressed in real and imaginary form.
Compute the mean of the complex numbers.
Convert the complex mean to polar coordinates whereupon the phase of the complex mean is the required angular mean.
(Note that, since the mean is the sum divided by the number of numbers, and division by a positive real number does not affect the angle, you can also simply compute the sum for step 2.)
You can alternatively use this formula:
Given the angles
α
1
,
…
,
α
n
{\displaystyle \alpha _{1},\dots ,\alpha _{n}}
the mean is computed by
α
¯
=
atan2
(
1
n
⋅
∑
j
=
1
n
sin
α
j
,
1
n
⋅
∑
j
=
1
n
cos
α
j
)
{\displaystyle {\bar {\alpha }}=\operatorname {atan2} \left({\frac {1}{n}}\cdot \sum _{j=1}^{n}\sin \alpha _{j},{\frac {1}{n}}\cdot \sum _{j=1}^{n}\cos \alpha _{j}\right)}
Task[edit]
write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle.
(You should use a built-in function if you have one that does this for degrees or radians).
Use the function to compute the means of these lists of angles (in degrees):
[350, 10]
[90, 180, 270, 360]
[10, 20, 30]
Show your output here.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Swift | Swift | import Foundation
@inlinable public func d2r<T: FloatingPoint>(_ f: T) -> T { f * .pi / 180 }
@inlinable public func r2d<T: FloatingPoint>(_ f: T) -> T { f * 180 / .pi }
public func meanOfAngles(_ angles: [Double]) -> Double {
let cInv = 1 / Double(angles.count)
let (s, c) =
angles.lazy
.map(d2r)
.map({ (sin($0), cos($0)) })
.reduce(into: (0.0, 0.0), { $0.0 += $1.0; $0.1 += $1.1 })
return r2d(atan2(cInv * s, cInv * c))
}
let fmt = { String(format: "%lf", $0) }
print("Mean of angles (350, 10) => \(fmt(meanOfAngles([350, 10])))")
print("Mean of angles (90, 180, 270, 360) => \(fmt(meanOfAngles([90, 180, 270, 360])))")
print("Mean of angles (10, 20, 30) => \(fmt(meanOfAngles([10, 20, 30])))") |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches to this. One is to sort the elements, and then pick the element(s) in the middle.
Sorting would take at least O(n logn). Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s). This would also take O(n logn). The best solution is to use the selection algorithm to find the median in O(n) time.
See also
Quickselect_algorithm
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Lingo | Lingo | on median (numlist)
-- numlist = numlist.duplicate() -- if input list should not be altered
numlist.sort()
if numlist.count mod 2 then
return numlist[numlist.count/2+1]
else
return (numlist[numlist.count/2]+numlist[numlist.count/2+1])/2.0
end if
end |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches to this. One is to sort the elements, and then pick the element(s) in the middle.
Sorting would take at least O(n logn). Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s). This would also take O(n logn). The best solution is to use the selection algorithm to find the median in O(n) time.
See also
Quickselect_algorithm
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #LiveCode | LiveCode | put median("4.1,5.6,7.2,1.7,9.3,4.4,3.2") & "," & median("4.1,7.2,1.7,9.3,4.4,3.2")
returns 4.4, 4.25 |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of positive integers.
The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
A
(
x
1
,
…
,
x
n
)
=
x
1
+
⋯
+
x
n
n
{\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}}
The geometric mean is the
n
{\displaystyle n}
th root of the product of the list:
G
(
x
1
,
…
,
x
n
)
=
x
1
⋯
x
n
n
{\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}}
The harmonic mean is
n
{\displaystyle n}
divided by the sum of the reciprocal of each item in the list:
H
(
x
1
,
…
,
x
n
)
=
n
1
x
1
+
⋯
+
1
x
n
{\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Modula-2 | Modula-2 | MODULE PythagoreanMeans;
FROM FormatString IMPORT FormatString;
FROM LongMath IMPORT power;
FROM LongStr IMPORT RealToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE ArithmeticMean(numbers : ARRAY OF LONGREAL) : LONGREAL;
VAR
i,cnt : CARDINAL;
mean : LONGREAL;
BEGIN
mean := 0.0;
cnt := 0;
FOR i:=0 TO HIGH(numbers) DO
mean := mean + numbers[i];
INC(cnt);
END;
RETURN mean / LFLOAT(cnt)
END ArithmeticMean;
PROCEDURE GeometricMean(numbers : ARRAY OF LONGREAL) : LONGREAL;
VAR
i,cnt : CARDINAL;
mean : LONGREAL;
BEGIN
mean := 1.0;
cnt := 0;
FOR i:=0 TO HIGH(numbers) DO
mean := mean * numbers[i];
INC(cnt);
END;
RETURN power(mean, 1.0 / LFLOAT(cnt))
END GeometricMean;
PROCEDURE HarmonicMean(numbers : ARRAY OF LONGREAL) : LONGREAL;
VAR
i,cnt : CARDINAL;
mean : LONGREAL;
BEGIN
mean := 0.0;
cnt := 0;
FOR i:=0 TO HIGH(numbers) DO
mean := mean + ( 1.0 / numbers[i]);
INC(cnt);
END;
RETURN LFLOAT(cnt) / mean
END HarmonicMean;
CONST Size = 10;
TYPE DA = ARRAY[1..Size] OF LONGREAL;
VAR
buf : ARRAY[0..63] OF CHAR;
array : DA;
arithmetic,geometric,harmonic : LONGREAL;
BEGIN
array := DA{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0};
arithmetic := ArithmeticMean(array);
geometric := GeometricMean(array);
harmonic := HarmonicMean(array);
WriteString("A = ");
RealToStr(arithmetic, buf);
WriteString(buf);
WriteString(" G = ");
RealToStr(geometric, buf);
WriteString(buf);
WriteString(" H = ");
RealToStr(harmonic, buf);
WriteString(buf);
WriteLn;
FormatString("A >= G is %b, G >= H is %b\n", buf, arithmetic >= geometric, geometric >= harmonic);
WriteString(buf);
ReadChar
END PythagoreanMeans. |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #UTFool | UTFool |
···
http://rosettacode.org/wiki/Babbage_problem
···
■ BabbageProblem
§ static
▶ main
• args⦂ String[]
for each number from √269696 up to √Integer.MAX_VALUE
if ("⸨number × number⸩").endsWith "269696"
System.exit number
|
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #VAX_Assembly | VAX Assembly |
36 35 34 33 32 31 00000008'010E0000' 0000 1 result: .ascid "123456" ;output buffer
0000 000E 2 retlen: .word 0 ;$fao_s bytes written
4C 55 21 00000018'010E0000' 0010 3 format: .ascid "!UL" ;unsigned decimal
001B 4
0000 001B 5 .entry bab,0
55 D4 001D 6 clrl r5 ;result
001F 7 10$:
55 D6 001F 8 incl r5
56 00 55 55 7A 0021 9 emul r5,r5,#0,r6 ;mulr.rl, muld.rl, add.rl, prod.wq
51 50 56 000F4240 8F 7B 0026 10 ediv #1000000,r6,r0,r1 ;divr.rl, divd.rq, quo.wl, rem.wl
51 00041D80 8F D1 002F 11 cmpl #269696,r1
E7 12 0036 12 bneq 10$ ;not equal - try next
0038 13
0038 14 $fao_s - ;convert integer to text
0038 15 ctrstr = format, -
0038 16 outlen = retlen, -
0038 17 outbuf = result, -
0038 18 p1 = r5
B1 AF C1 AF B0 004A 19 movw retlen, result ;adjust length
AE AF 7F 004F 20 pushaq result
00000000'GF 01 FB 0052 21 calls #1, g^lib$put_output
04 0059 22 ret
005A 23 .end bab
$ run bab
25264
|
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #Fortran | Fortran |
! $ gfortran -g -O0 -std=f2008 -Wall f.f08 -o f.exe
! $ ./f
! compiles syntax error
! :
! : ][
! : ]][[
! :[[[]]]
! : ][[][]][
! : ][[]]][[[]
! : ]]]][]][[[[[
! : ]]]][][]][[[[[
! : ][[[]]]]][]][[[[
! : [[][]]][]]][[[][[]
! : ]]][[][[[[[[[[]]]]]]
! :[[][[[][]]][]]
! :[[[][]][][[[]][]][]]
program balanced_brackets
implicit none
integer :: N
character(len=20) :: brackets, fmt
write(6,*)'compiles syntax error'
call random_seed
do N=0, 10
call generate(N, brackets)
if (balanced(brackets)) then
fmt = '(a,a20)'
else
fmt = '(a,21x,a20)'
end if
write(6,fmt)':',brackets
end do
brackets = '[[][[[][]]][]]'
if (balanced(brackets)) then
fmt = '(a,a20)'
else
fmt = '(a,21x,a20)'
end if
write(6,fmt)':',brackets
N = 10
call generate(N, brackets)
do while (.not. balanced(brackets)) ! show a balanced set
call generate(N, brackets)
end do
fmt = '(a,a20)'
write(6,fmt)':',brackets
contains
logical function balanced(s)
implicit none
character(len=*), intent(in) :: s
integer :: i, a, n
n = len_trim(s)
a = 0
balanced = .true.
do i=1, n
if (s(i:i) == '[') then
a = a+1
else
a = a-1
end if
balanced = balanced .and. (0 <= a)
end do
end function balanced
subroutine generate(N, s)
implicit none
integer, intent(in) :: N
character(len=*), intent(out) :: s
integer :: L, R, i
real, dimension(2*N) :: harvest
character :: c
i = 1
L = 0
R = 0
s = ' '
call random_number(harvest)
do while ((L < N) .and. (R < N))
if (harvest(i) < 0.5) then
L = L+1
s(i:i) = '['
else
R = R+1
s(i:i) = ']'
end if
i = i+1
end do
c = merge('[', ']', L < N)
do while (i <= 2*N)
s(i:i) = c
i = i+1
end do
end subroutine generate
end program balanced_brackets
|
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file | Append a record to the end of a text file | Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment.
This feature is most useful in the case of log files, where many jobs may be appending to the log file at the same time, or where care must be taken to avoid concurrently overwriting the same record from another job.
Task
Given a two record sample for a mythical "passwd" file:
Write these records out in the typical system format.
Ideally these records will have named fields of various types.
Close the file, then reopen the file for append.
Append a new record to the file and close the file again.
Take appropriate care to avoid concurrently overwrites from another job.
Open the file and demonstrate the new record has indeed written to the end.
Source record field types and contents.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
jsmith
x
1001
1000
Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]
/home/jsmith
/bin/bash
jdoe
x
1002
1000
Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]
/home/jdoe
/bin/bash
Record to be appended.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
xyz
x
1003
1000
X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]
/home/xyz
/bin/bash
Resulting file format: should mimic Linux's /etc/passwd file format with particular attention to the "," separator used in the GECOS field. But if the specific language has a particular or unique format of storing records in text file, then this format should be named and demonstrated with an additional example.
Expected output:
Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash
Finally: Provide a summary of the language's "append record" capabilities in a table. eg.
Append Capabilities.
Data Representation
IO
Library
Append
Possible
Automatic
Append
Multi-tasking
Safe
In core
On disk
C struct
CSV text file
glibc/stdio
☑
☑
☑ (Not all, eg NFS)
Alternatively: If the language's appends can not guarantee its writes will always append, then note this restriction in the table. If possible, provide an actual code example (possibly using file/record locking) to guarantee correct concurrent appends.
| #Nim | Nim | import posix
import strutils
type
# GECOS representation.
Gecos = tuple[fullname, office, extension, homephone, email: string]
# Record representation.
Record = object
account: string
password: string
uid: int
gid: int
gecos: Gecos
directory: string
shell: string
#---------------------------------------------------------------------------------------------------
proc str(gecos: Gecos): string =
## Explicit representation of a GECOS.
result = "("
for name, field in gecos.fieldPairs:
result.addSep(", ", 1)
result.add(name & ": " & field)
result.add(')')
#---------------------------------------------------------------------------------------------------
proc `$`(gecos: Gecos): string =
## Compact representation of a GECOS.
for field in gecos.fields:
result.addSep(",", 0)
result.add(field)
#---------------------------------------------------------------------------------------------------
proc parseGecos(s: string): Gecos =
## Parse a string and return a Gecos tuple.
let fields = s.split(",")
result = (fields[0], fields[1], fields[2], fields[3], fields[4])
#---------------------------------------------------------------------------------------------------
proc str(rec: Record): string =
## Explicit representation of a record.
for name, field in rec.fieldPairs:
result.add(name & ": ")
when typeof(field) is Gecos:
result.add(str(field))
else:
result.add($field)
result.add('\n')
#---------------------------------------------------------------------------------------------------
proc `$`(rec: Record): string =
# Compact representation fo a record.
for field in rec.fields:
result.addSep(":", 0)
result.add($field)
#---------------------------------------------------------------------------------------------------
proc parseRecord(line: string): Record =
## Parse a string and return a Record object.
let fields = line.split(":")
result.account = fields[0]
result.password = fields[1]
result.uid = fields[2].parseInt()
result.gid = fields[3].parseInt()
result.gecos = parseGecos(fields[4])
result.directory = fields[5]
result.shell = fields[6]
#---------------------------------------------------------------------------------------------------
proc getLock(f: File): bool =
## Try to get an exclusive write lock on file "f". Return false is unsuccessful.
when defined(posix):
var flock = TFlock(l_type: cshort(F_WRLCK), l_whence: cshort(SEEK_SET), l_start: 0, l_len: 0)
result = f.getFileHandle().fcntl(F_SETLK, flock.addr) >= 0
else:
result = true
#———————————————————————————————————————————————————————————————————————————————————————————————————
var pwfile: File
const Filename = "passwd"
const Data = ["jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash",
"jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash"]
# Prepare initial file.
# We don'’t use a lock here as it is only the preparation.
pwfile = open(FileName, fmWrite)
for line in Data:
pwfile.writeLine(line)
pwfile.close()
# Display initial contents.
echo "Raw content of initial password file:"
echo "-------------------------------------"
var records: seq[Record]
for line in lines(FileName):
echo line
records.add(line.parseRecord())
echo ""
echo "Structured content of initial password file:"
echo "--------------------------------------------"
for rec in records:
echo str(rec)
# Add a new record at the end of password file.
pwfile = open(Filename, fmAppend)
let newRecord = Record(account: "xyz",
password: "x",
uid: 1003,
gid: 1000,
gecos: ("X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "[email protected]"),
directory: "/home/xyz",
shell: "/bin/bash")
echo "Appending new record:"
echo "---------------------"
echo str(newRecord)
if pwfile.getLock():
pwFile.writeLine(newRecord)
pwfile.close()
else:
echo "File is locked. Quitting."
pwFile.close()
quit(QuitFailure)
# Reopen the file and display its contents.
echo "Raw content of updated password file:"
echo "-------------------------------------"
for line in lines(FileName):
echo line |
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file | Append a record to the end of a text file | Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment.
This feature is most useful in the case of log files, where many jobs may be appending to the log file at the same time, or where care must be taken to avoid concurrently overwriting the same record from another job.
Task
Given a two record sample for a mythical "passwd" file:
Write these records out in the typical system format.
Ideally these records will have named fields of various types.
Close the file, then reopen the file for append.
Append a new record to the file and close the file again.
Take appropriate care to avoid concurrently overwrites from another job.
Open the file and demonstrate the new record has indeed written to the end.
Source record field types and contents.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
jsmith
x
1001
1000
Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]
/home/jsmith
/bin/bash
jdoe
x
1002
1000
Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]
/home/jdoe
/bin/bash
Record to be appended.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
xyz
x
1003
1000
X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]
/home/xyz
/bin/bash
Resulting file format: should mimic Linux's /etc/passwd file format with particular attention to the "," separator used in the GECOS field. But if the specific language has a particular or unique format of storing records in text file, then this format should be named and demonstrated with an additional example.
Expected output:
Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash
Finally: Provide a summary of the language's "append record" capabilities in a table. eg.
Append Capabilities.
Data Representation
IO
Library
Append
Possible
Automatic
Append
Multi-tasking
Safe
In core
On disk
C struct
CSV text file
glibc/stdio
☑
☑
☑ (Not all, eg NFS)
Alternatively: If the language's appends can not guarantee its writes will always append, then note this restriction in the table. If possible, provide an actual code example (possibly using file/record locking) to guarantee correct concurrent appends.
| #Pascal | Pascal | program appendARecordToTheEndOfATextFile;
var
passwd: bindable text;
FD: bindingType;
begin
{ initialize FD }
FD := binding(passwd);
FD.name := '/tmp/passwd';
{ attempt opening file [e.g. effective user has proper privileges?] }
bind(passwd, FD);
{ query binding state of `passwd` }
FD := binding(passwd);
if not FD.bound then
begin
writeLn('Error: could not open ', FD.name);
halt;
end;
{ open for overwriting }
rewrite(passwd);
writeLn(passwd, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash');
writeLn(passwd, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash');
{ close }
unbind(passwd);
{ rebind }
bind(passwd, FD);
FD := binding(passwd);
if not FD.bound then
begin
writeLn('Error: could not reopen ', FD.name);
halt;
end;
{ open in append/writable mode }
extend(passwd);
{ write another record to file }
writeLn(passwd, 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash');
end. |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
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
| #C | C | System.Collections.HashTable map = new System.Collections.HashTable();
map["key1"] = "foo"; |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #JavaScript | JavaScript |
function factors(n) {
var factors = [];
for (var i = 1; i <= n; i++) {
if (n % i == 0) {
factors.push(i);
}
}
return factors;
}
function generateAntiprimes(n) {
var antiprimes = [];
var maxFactors = 0;
for (var i = 1; antiprimes.length < n; i++) {
var ifactors = factors(i);
if (ifactors.length > maxFactors) {
antiprimes.push(i);
maxFactors = ifactors.length;
}
}
return antiprimes;
}
function go() {
var number = document.getElementById("n").value;
document.body.removeChild(document.getElementById("result-list"));
document.body.appendChild(showList(generateAntiprimes(number)));
}
function showList(array) {
var list = document.createElement("ul");
list.id = "result-list";
for (var i = 0; i < array.length; i++) {
var item = document.createElement("li");
item.appendChild(document.createTextNode(array[i]));
list.appendChild(item);
}
return list;
}
|
http://rosettacode.org/wiki/Atomic_updates | Atomic updates |
Task
Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to:
get the current value of any bucket
remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the transferred amount to ensure the values remain non-negative
In order to exercise this data type, create one set of buckets, and start three concurrent tasks:
As often as possible, pick two buckets and make their values closer to equal.
As often as possible, pick two buckets and arbitrarily redistribute their values.
At whatever rate is convenient, display (by any means) the total value and, optionally, the individual values of each bucket.
The display task need not be explicit; use of e.g. a debugger or trace tool is acceptable provided it is simple to set up to provide the display.
This task is intended as an exercise in atomic operations. The sum of the bucket values must be preserved even if the two tasks attempt to perform transfers simultaneously, and a straightforward solution is to ensure that at any time, only one transfer is actually occurring — that the transfer operation is atomic.
| #Smalltalk | Smalltalk | NUM_BUCKETS := 10.
"create and preset with random data"
buckets := (1 to:NUM_BUCKETS)
collect:[:i | Random nextIntegerBetween:0 and:10000]
as:Array.
count_randomizations := 0.
count_equalizations := 0.
printSum :=
[
"the sum must be computed and printed while noone fiddles around"
|snapshot|
snapshot := buckets synchronized:[ buckets copy ].
Transcript showCR: e' {snapshot} sum={snapshot sum}'.
].
pickTwo :=
[:action |
"pick two pockets and eval action on it"
|p1 p2|
p1 := Random nextIntegerBetween:1 and:NUM_BUCKETS.
p2 := Random nextIntegerBetween:1 and:NUM_BUCKETS.
buckets synchronized:[ action value:p1 value:p2 ].
].
randomize :=
[
pickTwo value:[:p1 :p2 |
"take a random value from p1 and add to p2"
|howMuch|
howMuch := Random nextIntegerBetween:0 and:(buckets at:p1).
buckets at:p1 put:(buckets at:p1)-howMuch.
buckets at:p2 put:(buckets at:p2)+howMuch.
].
count_randomizations := count_randomizations + 1.
].
equalize :=
[
pickTwo value:[:p1 :p2 |
"average them"
|diff|
diff := ((buckets at:p1) - (buckets at:p2)) // 2.
buckets at:p1 put:(buckets at:p1)-diff.
buckets at:p2 put:(buckets at:p2)+diff.
].
count_equalizations := count_equalizations + 1.
].
"start the show"
randomizer := [ randomize loop ] fork.
equalizer := [ equalize loop ] fork.
"every 2 seconds, print the sum"
monitor := [
[
printSum value.
Delay waitFor:2 seconds.
] loop.
] fork.
"let it run for 10 seconds, then kill them all"
Delay waitFor:20 seconds.
randomizer terminate.
equalizer terminate.
monitor terminate.
Stdout printCR: e'performed {count_equalizations} equalizations and {count_randomizations} randomizations'. |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Python | Python | a = 5
#...input or change a here
assert a == 42 # throws an AssertionError when a is not 42
assert a == 42, "Error message" # throws an AssertionError
# when a is not 42 with "Error message" for the message
# the error message can be any expression |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #QB64 | QB64 | $ASSERTS:CONSOLE
DO
a = INT(RND * 10)
b$ = myFunc$(a)
PRINT a, , b$
_LIMIT 3
LOOP UNTIL _KEYHIT
FUNCTION myFunc$ (value AS SINGLE)
_ASSERT value > 0, "Value cannot be zero"
_ASSERT value <= 10, "Value cannot exceed 10"
IF value > 1 THEN plural$ = "s"
myFunc$ = STRING$(value, "*") + STR$(value) + " star" + plural$ + " :-)"
END FUNCTION |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #R | R | stopifnot(a==42) |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Elixir | Elixir |
Enum.map([1, 2, 3], fn(n) -> n * 2 end)
Enum.map [1, 2, 3], &(&1 * 2)
|
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Erlang | Erlang |
1> L = [1,2,3].
[1,2,3]
|
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Q | Q | mode:{(key x) where value x=max x} count each group @ |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Quackery | Quackery | [ sort
[] [] rot
dup 0 peek temp put
witheach
[ dup temp share = iff
join
else
[ dup temp replace
dip [ nested join ]
[] join ] ]
nested join
temp release ] is bunch ( [ --> [ )
[ sortwith [ size dip size < ]
[] swap
dup 0 peek size temp put
witheach
[ dup size temp share = iff
[ nested join ]
else
[ drop conclude ] ]
temp release
[] swap
witheach
[ 0 peek join ] ] is largest ( [ --> [ )
[ bunch largest ] is mode ( [ --> [ )
' [ 1 3 5 7 3 1 3 7 7 3 3 ] mode echo cr
' [ 7 13 5 13 7 2 7 10 13 ] mode echo cr
' [ 5 ] mode echo cr |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
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
| #Frink | Frink | d = new dict[[[1, "one"], [2, "two"]]]
for [key, value] = d
println["$key\t$value"]
println[]
for key = keys[d]
println["$key"]
|
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
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 cList As Collection = ["2": "quick", "4": "fox", "1": "The", "9": "dog", "7": "the", "5": "jumped", "3": "brown", "6": "over", "8": "lazy"]
Dim siCount As Short
Dim sTemp As String
For Each sTemp In cList
Print cList.key & "=" & sTemp;;
Next
Print
For siCount = 1 To cList.Count
Print cList[Str(siCount)];;
Next
End |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #GEORGE | GEORGE | R (n) P ;
0
1, n rep (i)
R P +
]
n div
P |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #GFA_Basic | GFA Basic |
DIM a%(10)
FOR i%=0 TO 10
a%(i%)=i%*2
PRINT "element ";i%;" is ";a%(i%)
NEXT i%
PRINT "mean is ";@mean(a%)
'
FUNCTION mean(a%)
LOCAL i%,size%,sum
' find size of array,
size%=DIM?(a%())
' return 0 for empty arrays
IF size%<=0
RETURN 0
ENDIF
' find sum of all elements
sum=0
FOR i%=0 TO size%-1
sum=sum+a%(i%)
NEXT i%
' mean is sum over size
RETURN sum/size%
ENDFUNC
|
http://rosettacode.org/wiki/Attractive_numbers | Attractive numbers | A number is an attractive number if the number of its prime factors (whether distinct or not) is also prime.
Example
The number 20, whose prime decomposition is 2 × 2 × 5, is an attractive number because the number of its prime factors (3) is also prime.
Task
Show sequence items up to 120.
Reference
The OEIS entry: A063989: Numbers with a prime number of prime divisors.
| #PureBasic | PureBasic | #MAX=120
Dim prime.b(#MAX)
FillMemory(@prime(),#MAX,#True,#PB_Byte) : FillMemory(@prime(),2,#False,#PB_Byte)
For i=2 To Int(Sqr(#MAX)) : n=i*i : While n<#MAX : prime(n)=#False : n+i : Wend : Next
Procedure.i pfCount(n.i)
Shared prime()
If n=1 : ProcedureReturn 0 : EndIf
If prime(n) : ProcedureReturn 1 : EndIf
count=0 : f=2
Repeat
If n%f=0 : count+1 : n/f
If n=1 : ProcedureReturn count : EndIf
If prime(n) : f=n : EndIf
ElseIf f>=3 : f+2
Else : f=3
EndIf
ForEver
EndProcedure
OpenConsole()
PrintN("The attractive numbers up to and including "+Str(#MAX)+" are:")
For i=1 To #MAX
If prime(pfCount(i))
Print(RSet(Str(i),4)) : count+1 : If count%20=0 : PrintN("") : EndIf
EndIf
Next
PrintN("") : Input() |
http://rosettacode.org/wiki/Averages/Mean_time_of_day | Averages/Mean time of day | Task[edit]
A particular activity of bats occurs at these times of the day:
23:00:17, 23:40:20, 00:12:45, 00:17:19
Using the idea that there are twenty-four hours in a day,
which is analogous to there being 360 degrees in a circle,
map times of day to and from angles;
and using the ideas of Averages/Mean angle
compute and show the average time of the nocturnal activity
to an accuracy of one second of time.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #SQL.2FPostgreSQL | SQL/PostgreSQL |
--Setup table for testing
CREATE TABLE time_table(times TIME);
INSERT INTO time_table VALUES ('23:00:17'::TIME),('23:40:20'::TIME),('00:12:45'::TIME),('00:17:19'::TIME)
--Compute mean time
SELECT to_timestamp((degrees(atan2(AVG(sin),AVG(cos))))* (24*60*60)/360)::TIME
FROM
(SELECT
cos(radians(t*360/(24*60*60))),sin(radians(t*360/(24*60*60)))
FROM
(SELECT EXTRACT(epoch FROM times) t
FROM time_table) T1
)T2 |
http://rosettacode.org/wiki/Averages/Mean_angle | Averages/Mean angle | When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle.
If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the second was of 10 degrees then the average of the numbers is 180 degrees, whereas if you can note that 350 degrees is equivalent to -10 degrees and so you have two readings at 10 degrees either side of zero degrees leading to a more fitting mean angle of zero degrees.
To calculate the mean angle of several angles:
Assume all angles are on the unit circle and convert them to complex numbers expressed in real and imaginary form.
Compute the mean of the complex numbers.
Convert the complex mean to polar coordinates whereupon the phase of the complex mean is the required angular mean.
(Note that, since the mean is the sum divided by the number of numbers, and division by a positive real number does not affect the angle, you can also simply compute the sum for step 2.)
You can alternatively use this formula:
Given the angles
α
1
,
…
,
α
n
{\displaystyle \alpha _{1},\dots ,\alpha _{n}}
the mean is computed by
α
¯
=
atan2
(
1
n
⋅
∑
j
=
1
n
sin
α
j
,
1
n
⋅
∑
j
=
1
n
cos
α
j
)
{\displaystyle {\bar {\alpha }}=\operatorname {atan2} \left({\frac {1}{n}}\cdot \sum _{j=1}^{n}\sin \alpha _{j},{\frac {1}{n}}\cdot \sum _{j=1}^{n}\cos \alpha _{j}\right)}
Task[edit]
write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle.
(You should use a built-in function if you have one that does this for degrees or radians).
Use the function to compute the means of these lists of angles (in degrees):
[350, 10]
[90, 180, 270, 360]
[10, 20, 30]
Show your output here.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Tcl | Tcl | proc meanAngle {angles} {
set toRadians [expr {atan2(0,-1) / 180}]
set sumSin [set sumCos 0.0]
foreach a $angles {
set sumSin [expr {$sumSin + sin($a * $toRadians)}]
set sumCos [expr {$sumCos + cos($a * $toRadians)}]
}
# Don't need to divide by counts; atan2() cancels that out
return [expr {atan2($sumSin, $sumCos) / $toRadians}]
} |
http://rosettacode.org/wiki/Averages/Mean_angle | Averages/Mean angle | When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle.
If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the second was of 10 degrees then the average of the numbers is 180 degrees, whereas if you can note that 350 degrees is equivalent to -10 degrees and so you have two readings at 10 degrees either side of zero degrees leading to a more fitting mean angle of zero degrees.
To calculate the mean angle of several angles:
Assume all angles are on the unit circle and convert them to complex numbers expressed in real and imaginary form.
Compute the mean of the complex numbers.
Convert the complex mean to polar coordinates whereupon the phase of the complex mean is the required angular mean.
(Note that, since the mean is the sum divided by the number of numbers, and division by a positive real number does not affect the angle, you can also simply compute the sum for step 2.)
You can alternatively use this formula:
Given the angles
α
1
,
…
,
α
n
{\displaystyle \alpha _{1},\dots ,\alpha _{n}}
the mean is computed by
α
¯
=
atan2
(
1
n
⋅
∑
j
=
1
n
sin
α
j
,
1
n
⋅
∑
j
=
1
n
cos
α
j
)
{\displaystyle {\bar {\alpha }}=\operatorname {atan2} \left({\frac {1}{n}}\cdot \sum _{j=1}^{n}\sin \alpha _{j},{\frac {1}{n}}\cdot \sum _{j=1}^{n}\cos \alpha _{j}\right)}
Task[edit]
write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle.
(You should use a built-in function if you have one that does this for degrees or radians).
Use the function to compute the means of these lists of angles (in degrees):
[350, 10]
[90, 180, 270, 360]
[10, 20, 30]
Show your output here.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Vala | Vala | double meanAngle(double[] angles) {
double y_part = 0.0;
double x_part = 0.0;
for (int i = 0; i < angles.length; i++) {
x_part += Math.cos(angles[i] * Math.PI / 180.0);
y_part += Math.sin(angles[i] * Math.PI / 180.0);
}
return Math.atan2(y_part / angles.length, x_part / angles.length) * 180 / Math.PI;
}
void main() {
double[] angleSet1 = {350.0, 10.0};
double[] angleSet2 = {90.0, 180.0, 270.0, 360.0};
double[] angleSet3 = {10.0, 20.0, 30.0};
print("\nMean Angle for 1st set : %lf degrees", meanAngle(angleSet1));
print("\nMean Angle for 2nd set : %lf degrees", meanAngle(angleSet2));
print("\nMean Angle for 3rd set : %lf degrees\n", meanAngle(angleSet3));
} |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches to this. One is to sort the elements, and then pick the element(s) in the middle.
Sorting would take at least O(n logn). Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s). This would also take O(n logn). The best solution is to use the selection algorithm to find the median in O(n) time.
See also
Quickselect_algorithm
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #LSL | LSL | integer MAX_ELEMENTS = 10;
integer MAX_VALUE = 100;
default {
state_entry() {
list lst = [];
integer x = 0;
for(x=0 ; x<MAX_ELEMENTS ; x++) {
lst += llFrand(MAX_VALUE);
}
llOwnerSay("lst=["+llList2CSV(lst)+"]");
llOwnerSay("Geometric Mean: "+(string)llListStatistics(LIST_STAT_GEOMETRIC_MEAN, lst));
llOwnerSay(" Max: "+(string)llListStatistics(LIST_STAT_MAX, lst));
llOwnerSay(" Mean: "+(string)llListStatistics(LIST_STAT_MEAN, lst));
llOwnerSay(" Median: "+(string)llListStatistics(LIST_STAT_MEDIAN, lst));
llOwnerSay(" Min: "+(string)llListStatistics(LIST_STAT_MIN, lst));
llOwnerSay(" Num Count: "+(string)llListStatistics(LIST_STAT_NUM_COUNT, lst));
llOwnerSay(" Range: "+(string)llListStatistics(LIST_STAT_RANGE, lst));
llOwnerSay(" Std Dev: "+(string)llListStatistics(LIST_STAT_STD_DEV, lst));
llOwnerSay(" Sum: "+(string)llListStatistics(LIST_STAT_SUM, lst));
llOwnerSay(" Sum Squares: "+(string)llListStatistics(LIST_STAT_SUM_SQUARES, lst));
}
} |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches to this. One is to sort the elements, and then pick the element(s) in the middle.
Sorting would take at least O(n logn). Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s). This would also take O(n logn). The best solution is to use the selection algorithm to find the median in O(n) time.
See also
Quickselect_algorithm
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Lua | Lua | function median (numlist)
if type(numlist) ~= 'table' then return numlist end
table.sort(numlist)
if #numlist %2 == 0 then return (numlist[#numlist/2] + numlist[#numlist/2+1]) / 2 end
return numlist[math.ceil(#numlist/2)]
end
print(median({4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2}))
print(median({4.1, 7.2, 1.7, 9.3, 4.4, 3.2})) |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of positive integers.
The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
A
(
x
1
,
…
,
x
n
)
=
x
1
+
⋯
+
x
n
n
{\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}}
The geometric mean is the
n
{\displaystyle n}
th root of the product of the list:
G
(
x
1
,
…
,
x
n
)
=
x
1
⋯
x
n
n
{\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}}
The harmonic mean is
n
{\displaystyle n}
divided by the sum of the reciprocal of each item in the list:
H
(
x
1
,
…
,
x
n
)
=
n
1
x
1
+
⋯
+
1
x
n
{\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #MUMPS | MUMPS | Pyth(n) New a,ii,g,h,x
For ii=1:1:n set x(ii)=ii
;
; Average
Set a=0 For ii=1:1:n Set a=a+x(ii)
Set a=a/n
;
; Geometric
Set g=1 For ii=1:1:n Set g=g*x(ii)
Set g=g**(1/n)
;
; Harmonic
Set h=0 For ii=1:1:n Set h=1/x(ii)+h
Set h=n/h
;
Write !,"Pythagorean means for 1..",n,":",!
Write "Average = ",a," >= Geometric ",g," >= harmonic ",h,!
Quit
Do Pyth(10)
Pythagorean means for 1..10:
Average = 5.5 >= Geometric 4.528728688116178495 >= harmonic 3.414171521474055006 |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #VBA | VBA |
Sub Baggage_Problem()
Dim i As Long
'We can start at the square root of 269696
i = 520
'269696 is a multiple of 4, 520 too
'so we can increment i by 4
Do While ((i * i) Mod 1000000) <> 269696
i = i + 4 'Increment by 4
Loop
Debug.Print "The smallest positive integer whose square ends in the digits 269 696 is : " & i & vbCrLf & _
"Its square is : " & i * i
End Sub
|
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #VBScript | VBScript | 'Sir, this is a script that could solve your problem.
'Lines that begin with the apostrophe are comments. The machine ignores them.
'The next line declares a variable n and sets it to 0. Note that the
'equals sign "assigns", not just "relates". So in here, this is more
'of a command, rather than just a mere proposition.
n = 0
'Starting from the initial value, which is 0, n is being incremented
'by 1 while its square, n * n (* means multiplication) does not have
'a modulo of 269696 when divided by one million. This means that the
'loop will stop when the smallest positive integer whose square ends
'in 269696 is found and stored in n. Before I forget, "<>" basically
'means "not equal to".
Do While ((n * n) Mod 1000000) <> 269696
n = n + 1 'Increment by 1.
Loop
'The function "WScript.Echo" displays the string to the monitor. The
'ampersand concatenates strings or variables to be displayed.
WScript.Echo("The smallest positive integer whose square ends in 269696 is " & n & ".")
WScript.Echo("Its square is " & n*n & ".")
'End of Program.
|
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function isBalanced(s As String) As Boolean
If s = "" Then Return True
Dim countLeft As Integer = 0 '' counts number of left brackets so far unmatched
Dim c As String
For i As Integer = 1 To Len(s)
c = Mid(s, i, 1)
If c = "[" Then
countLeft += 1
ElseIf countLeft > 0 Then
countLeft -= 1
Else
Return False
End If
Next
Return countLeft = 0
End Function
' checking examples in task description
Dim brackets(1 To 7) As String = {"", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]"}
For i As Integer = 1 To 7
Print IIf(brackets(i) <> "", brackets(i), "(empty)"); Tab(10); IIf(isBalanced(brackets(i)), "OK", "NOT OK")
Next
' checking 7 random strings of brackets of length 8 say
Randomize
Dim r As Integer '' 0 will signify "[" and 1 will signify "]"
Dim s As String
For i As Integer = 1 To 7
s = Space(8)
For j As Integer = 1 To 8
r = Int(Rnd * 2)
If r = 0 Then
Mid(s, j) = "["
Else
Mid(s, j) = "]"
End If
Next j
Print s; Tab(10); IIf(isBalanced(s), "OK", "NOT OK")
Next i
Print
Print "Press any key to quit"
Sleep |
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file | Append a record to the end of a text file | Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment.
This feature is most useful in the case of log files, where many jobs may be appending to the log file at the same time, or where care must be taken to avoid concurrently overwriting the same record from another job.
Task
Given a two record sample for a mythical "passwd" file:
Write these records out in the typical system format.
Ideally these records will have named fields of various types.
Close the file, then reopen the file for append.
Append a new record to the file and close the file again.
Take appropriate care to avoid concurrently overwrites from another job.
Open the file and demonstrate the new record has indeed written to the end.
Source record field types and contents.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
jsmith
x
1001
1000
Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]
/home/jsmith
/bin/bash
jdoe
x
1002
1000
Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]
/home/jdoe
/bin/bash
Record to be appended.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
xyz
x
1003
1000
X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]
/home/xyz
/bin/bash
Resulting file format: should mimic Linux's /etc/passwd file format with particular attention to the "," separator used in the GECOS field. But if the specific language has a particular or unique format of storing records in text file, then this format should be named and demonstrated with an additional example.
Expected output:
Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash
Finally: Provide a summary of the language's "append record" capabilities in a table. eg.
Append Capabilities.
Data Representation
IO
Library
Append
Possible
Automatic
Append
Multi-tasking
Safe
In core
On disk
C struct
CSV text file
glibc/stdio
☑
☑
☑ (Not all, eg NFS)
Alternatively: If the language's appends can not guarantee its writes will always append, then note this restriction in the table. If possible, provide an actual code example (possibly using file/record locking) to guarantee correct concurrent appends.
| #Perl | Perl | use strict;
use warnings;
use Fcntl qw( :flock SEEK_END );
use constant {
RECORD_FIELDS => [qw( account password UID GID GECOS directory shell )],
GECOS_FIELDS => [qw( fullname office extension homephone email )],
RECORD_SEP => ':',
GECOS_SEP => ',',
PASSWD_FILE => 'passwd.txt',
};
# here's our three records
my $records_to_write = [
{
account => 'jsmith',
password => 'x',
UID => 1001,
GID => 1000,
GECOS => {
fullname => 'John Smith',
office => 'Room 1007',
extension => '(234)555-8917',
homephone => '(234)555-0077',
email => '[email protected]',
},
directory => '/home/jsmith',
shell => '/bin/bash',
},
{
account => 'jdoe',
password => 'x',
UID => 1002,
GID => 1000,
GECOS => {
fullname => 'Jane Doe',
office => 'Room 1004',
extension => '(234)555-8914',
homephone => '(234)555-0044',
email => '[email protected]',
},
directory => '/home/jdoe',
shell => '/bin/bash',
},
];
my $record_to_append = {
account => 'xyz',
password => 'x',
UID => 1003,
GID => 1000,
GECOS => {
fullname => 'X Yz',
office => 'Room 1003',
extension => '(234)555-8913',
homephone => '(234)555-0033',
email => '[email protected]',
},
directory => '/home/xyz',
shell => '/bin/bash',
};
sub record_to_string {
my $rec = shift;
my $sep = shift // RECORD_SEP;
my $fields = shift // RECORD_FIELDS;
my @ary;
for my $field (@$fields) {
my $r = $rec->{$field};
die "Field '$field' not found" unless defined $r; # simple sanity check
push @ary, ( $field eq 'GECOS' ? record_to_string( $r, GECOS_SEP, GECOS_FIELDS ) : $r );
}
return join $sep, @ary;
}
sub write_records_to_file {
my $records = shift;
my $filename = shift // PASSWD_FILE;
open my $fh, '>>', $filename or die "Can't open $filename: $!";
flock( $fh, LOCK_EX ) or die "Can't lock $filename: $!";
# if someone appended while we were waiting...
seek( $fh, 0, SEEK_END ) or die "Can't seek $filename: $!" ;
print $fh record_to_string($_), "\n" for @$records;
flock( $fh, LOCK_UN ) or die "Can't unlock $filename: $!";
# note: the file is closed automatically when function returns (and refcount of $fh becomes 0)
}
# write two records to file
write_records_to_file( $records_to_write );
# append one more record to file
write_records_to_file( [$record_to_append] );
# test
{
use Test::Simple tests => 1;
open my $fh, '<', PASSWD_FILE or die "Can't open ", PASSWD_FILE, ": $!";
my @lines = <$fh>;
chomp @lines;
ok(
$lines[-1] eq
'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash',
"Appended record: $lines[-1]"
);
}
|
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
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
| #C.23 | C# | System.Collections.HashTable map = new System.Collections.HashTable();
map["key1"] = "foo"; |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #jq | jq |
# Compute the number of divisors, without calling sqrt
def ndivisors:
def sum(s): reduce s as $x (null; .+$x);
if . == 1 then 1
else . as $n
| sum( label $out
| range(1; $n) as $i
| ($i * $i) as $i2
| if $i2 > $n then break $out
else if $i2 == $n
then 1
elif ($n % $i) == 0
then 2
else empty
end
end)
end;
# Emit the antiprimes as a stream
def antiprimes:
1,
foreach range(2; infinite; 2) as $i ({maxfactors: 1};
.emit = null
| ($i | ndivisors) as $nfactors
| if $nfactors > .maxfactors
then .emit = $i
| .maxfactors = $nfactors
else .
end;
select(.emit).emit);
"The first 20 anti-primes are:", limit(20; antiprimes)
|
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #Julia | Julia | using Primes, Combinatorics
function antiprimes(N, maxn = 2000000)
antip = [1] # special case: 1 is antiprime
count = 1
maxfactors = 1
for i in 2:2:maxn # antiprimes > 2 should be even
lenfac = length(unique(sort(collect(combinations(factor(Vector, i)))))) + 1
if lenfac > maxfactors
push!(antip, i)
if length(antip) >= N
return antip
end
maxfactors = lenfac
end
end
antip
end
println("The first 20 anti-primes are:\n", antiprimes(20))
println("The first 40 anti-primes are:\n", antiprimes(40))
|
http://rosettacode.org/wiki/Atomic_updates | Atomic updates |
Task
Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to:
get the current value of any bucket
remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the transferred amount to ensure the values remain non-negative
In order to exercise this data type, create one set of buckets, and start three concurrent tasks:
As often as possible, pick two buckets and make their values closer to equal.
As often as possible, pick two buckets and arbitrarily redistribute their values.
At whatever rate is convenient, display (by any means) the total value and, optionally, the individual values of each bucket.
The display task need not be explicit; use of e.g. a debugger or trace tool is acceptable provided it is simple to set up to provide the display.
This task is intended as an exercise in atomic operations. The sum of the bucket values must be preserved even if the two tasks attempt to perform transfers simultaneously, and a straightforward solution is to ensure that at any time, only one transfer is actually occurring — that the transfer operation is atomic.
| #Swift | Swift | import Foundation
final class AtomicBuckets: CustomStringConvertible {
var count: Int {
return buckets.count
}
var description: String {
return withBucketsLocked { "\(buckets)" }
}
var total: Int {
return withBucketsLocked { buckets.reduce(0, +) }
}
private let lock = DispatchSemaphore(value: 1)
private var buckets: [Int]
subscript(n: Int) -> Int {
return withBucketsLocked { buckets[n] }
}
init(with buckets: [Int]) {
self.buckets = buckets
}
func transfer(amount: Int, from: Int, to: Int) {
withBucketsLocked {
let transferAmount = buckets[from] >= amount ? amount : buckets[from]
buckets[from] -= transferAmount
buckets[to] += transferAmount
}
}
private func withBucketsLocked<T>(do: () -> T) -> T {
let ret: T
lock.wait()
ret = `do`()
lock.signal()
return ret
}
}
let bucks = AtomicBuckets(with: [21, 39, 40, 20])
let order = DispatchSource.makeTimerSource()
let chaos = DispatchSource.makeTimerSource()
let printer = DispatchSource.makeTimerSource()
printer.setEventHandler {
print("\(bucks) = \(bucks.total)")
}
printer.schedule(deadline: .now(), repeating: .seconds(1))
printer.activate()
order.setEventHandler {
let (b1, b2) = (Int.random(in: 0..<bucks.count), Int.random(in: 0..<bucks.count))
let (v1, v2) = (bucks[b1], bucks[b2])
guard v1 != v2 else {
return
}
if v1 > v2 {
bucks.transfer(amount: (v1 - v2) / 2, from: b1, to: b2)
} else {
bucks.transfer(amount: (v2 - v1) / 2, from: b2, to: b1)
}
}
order.schedule(deadline: .now(), repeating: .milliseconds(5))
order.activate()
chaos.setEventHandler {
let (b1, b2) = (Int.random(in: 0..<bucks.count), Int.random(in: 0..<bucks.count))
bucks.transfer(amount: Int.random(in: 0..<(bucks[b1] + 1)), from: b1, to: b2)
}
chaos.schedule(deadline: .now(), repeating: .milliseconds(5))
chaos.activate()
dispatchMain() |
http://rosettacode.org/wiki/Atomic_updates | Atomic updates |
Task
Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to:
get the current value of any bucket
remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the transferred amount to ensure the values remain non-negative
In order to exercise this data type, create one set of buckets, and start three concurrent tasks:
As often as possible, pick two buckets and make their values closer to equal.
As often as possible, pick two buckets and arbitrarily redistribute their values.
At whatever rate is convenient, display (by any means) the total value and, optionally, the individual values of each bucket.
The display task need not be explicit; use of e.g. a debugger or trace tool is acceptable provided it is simple to set up to provide the display.
This task is intended as an exercise in atomic operations. The sum of the bucket values must be preserved even if the two tasks attempt to perform transfers simultaneously, and a straightforward solution is to ensure that at any time, only one transfer is actually occurring — that the transfer operation is atomic.
| #Tcl | Tcl | package require Thread
package require Tk
# Make the shared state
canvas .c ;# So we can allocate the display lines in one loop
set m [thread::mutex create]
for {set i 0} {$i<100} {incr i} {
set bucket b$i ;# A handle for every bucket...
tsv::set buckets $bucket 50
lappend buckets $bucket
lappend lines [.c create line 0 0 0 0]
}
tsv::set still going 1
# Make the "make more equal" task
lappend tasks [thread::create {
# Perform an atomic update of two cells
proc transfer {b1 b2 val} {
variable m
thread::mutex lock $m
set v [tsv::get buckets $b1]
if {$val > $v} {
set val $v
}
tsv::incr buckets $b1 [expr {-$val}]
tsv::incr buckets $b2 $val
thread::mutex unlock $m
}
# The task itself; we loop this round frequently
proc task {mutex buckets} {
variable m $mutex b $buckets i 0
while {[tsv::get still going]} {
set b1 [lindex $b $i]
if {[incr i] == [llength $b]} {set i 0}
set b2 [lindex $b $i]
if {[tsv::get buckets $b1] > [tsv::get buckets $b2]} {
transfer $b1 $b2 1
} else {
transfer $b1 $b2 -1
}
}
}
thread::wait
}]
# Make the "mess things up" task
lappend tasks [thread::create {
# Utility to pick a random item from a list
proc pick list {
lindex $list [expr {int(rand() * [llength $list])}]
}
proc transfer {b1 b2 val} {
variable m
thread::mutex lock $m
set v [tsv::get buckets $b1]
if {$val > $v} {
set val $v
}
tsv::incr buckets $b1 [expr {-$val}]
tsv::incr buckets $b2 $val
thread::mutex unlock $m
}
# The task to move a large amount between two random buckets
proc task {mutex buckets} {
variable m $mutex b $buckets
while {[tsv::get still going]} {
set b1 [pick $b]
set b2 [pick $b]
transfer $b1 $b2 [expr {[tsv::get buckets $b1] / 3}]
}
}
thread::wait
}]
# The "main" task; we keep GUI operations in the main thread
proc redisplay {} {
global m buckets lines
thread::mutex lock $m
set i 1
foreach b $buckets l $lines {
.c coords $l $i 0 $i [tsv::get buckets $b]
incr i 2
}
thread::mutex unlock $m
after 100 redisplay
}
# Start tasks and display
.c configure -width 201 -height 120
pack .c
redisplay
foreach t $tasks {
thread::send -async $t [list task $m $buckets]
}
# Wait for user to close window, then tidy up
tkwait window .
tsv::set still going 0
thread::broadcast thread::exit |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Racket | Racket | #lang racket
(define/contract x
(=/c 42) ; make sure x = 42
42)
(define/contract f
(-> number? (or/c 'yes 'no)) ; function contract
(lambda (x)
(if (= 42 x) 'yes 'no)))
(f 42) ; succeeds
(f "foo") ; contract error!
|
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Raku | Raku | my $a = (1..100).pick;
$a == 42 or die '$a ain\'t 42'; |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #REXX | REXX | /* REXX ***************************************************************
* There's no assert feature in Rexx. That's how I'd implement it
* 10.08.2012 Walter Pachl
**********************************************************************/
x.=42
x.2=11
Do i=1 By 1
Call assert x.i,42
End
Exit
assert:
Parse Arg assert_have,assert_should_have
If assert_have\==assert_should_have Then Do
Say 'Assertion fails in line' sigl
Say 'expected:' assert_should_have
Say ' found:' assert_have
Say sourceline(sigl)
Say 'Look around'
Trace ?R
Nop
Signal Syntax
End
Return
Syntax: Say 'program terminated' |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #ERRE | ERRE |
PROGRAM CALLBACK
!
! for rosettacode.org
!
DIM A[5]
FUNCTION CBACK(X)
CBACK=2*X-1
END FUNCTION
PROCEDURE PROCMAP(ZETA,DUMMY(X)->OUTP)
OUTP=DUMMY(ZETA)
END PROCEDURE
BEGIN
A[1]=1 A[2]=2 A[3]=3 A[4]=4 A[5]=5
FOR I%=1 TO 5 DO
PROCMAP(A[I%],CBACK(X)->OUTP)
PRINT(OUTP;)
END FOR
PRINT
END PROGRAM
|
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Euphoria | Euphoria | function apply_to_all(sequence s, integer f)
-- apply a function to all elements of a sequence
sequence result
result = {}
for i = 1 to length(s) do
-- we can call add1() here although it comes later in the program
result = append(result, call_func(f, {s[i]}))
end for
return result
end function
function add1(atom x)
return x + 1
end function
-- add1() is visible here, so we can ask for its routine id
? apply_to_all({1, 2, 3}, routine_id("add1"))
-- displays {2,3,4} |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #R | R | statmode <- function(v) {
a <- sort(table(v), decreasing=TRUE)
r <- c()
for(i in 1:length(a)) {
if ( a[[1]] == a[[i]] ) {
r <- c(r, as.integer(names(a)[i]))
} else break; # since it's sorted, once we find
# a different value, we can stop
}
r
}
print(statmode(c(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17)))
print(statmode(c(1, 1, 2, 4, 4))) |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Racket | Racket | #lang racket
(define (mode seq)
(define frequencies (make-hash))
(for ([s seq])
(hash-update! frequencies
s
(lambda (freq) (add1 freq))
0))
(for/fold ([ms null]
[freq 0])
([(k v) (in-hash frequencies)])
(cond [(> v freq)
(values (list k) v)]
[(= v freq)
(values (cons k ms) freq)]
[else
(values ms freq)]))) |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
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 | myMap := map[string]int {
"hello": 13,
"world": 31,
"!" : 71 }
// iterating over key-value pairs:
for key, value := range myMap {
fmt.Printf("key = %s, value = %d\n", key, value)
}
// iterating over keys:
for key := range myMap {
fmt.Printf("key = %s\n", key)
}
// iterating over values:
for _, value := range myMap {
fmt.Printf("value = %d\n", value)
} |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
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
| #Groovy | Groovy | def map = [lastName: "Anderson", firstName: "Thomas", nickname: "Neo", age: 24, address: "everywhere"]
println "Entries:"
map.each { println it }
println()
println "Keys:"
map.keySet().each { println it }
println()
println "Values:"
map.values().each { println it } |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Go | Go | package main
import (
"fmt"
"math"
)
func mean(v []float64) (m float64, ok bool) {
if len(v) == 0 {
return
}
// an algorithm that attempts to retain accuracy
// with widely different values.
var parts []float64
for _, x := range v {
var i int
for _, p := range parts {
sum := p + x
var err float64
switch ax, ap := math.Abs(x), math.Abs(p); {
case ax < ap:
err = x - (sum - p)
case ap < ax:
err = p - (sum - x)
}
if err != 0 {
parts[i] = err
i++
}
x = sum
}
parts = append(parts[:i], x)
}
var sum float64
for _, x := range parts {
sum += x
}
return sum / float64(len(v)), true
}
func main() {
for _, v := range [][]float64{
[]float64{}, // mean returns ok = false
[]float64{math.Inf(1), math.Inf(1)}, // answer is +Inf
// answer is NaN, and mean returns ok = true, indicating NaN
// is the correct result
[]float64{math.Inf(1), math.Inf(-1)},
[]float64{3, 1, 4, 1, 5, 9},
// large magnitude numbers cancel. answer is mean of small numbers.
[]float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},
[]float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},
[]float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},
} {
fmt.Println("Vector:", v)
if m, ok := mean(v); ok {
fmt.Printf("Mean of %d numbers is %g\n\n", len(v), m)
} else {
fmt.Println("Mean undefined\n")
}
}
} |
http://rosettacode.org/wiki/Attractive_numbers | Attractive numbers | A number is an attractive number if the number of its prime factors (whether distinct or not) is also prime.
Example
The number 20, whose prime decomposition is 2 × 2 × 5, is an attractive number because the number of its prime factors (3) is also prime.
Task
Show sequence items up to 120.
Reference
The OEIS entry: A063989: Numbers with a prime number of prime divisors.
| #Python | Python | from sympy import sieve # library for primes
def get_pfct(n):
i = 2; factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return len(factors)
sieve.extend(110) # first 110 primes...
primes=sieve._list
pool=[]
for each in xrange(0,121):
pool.append(get_pfct(each))
for i,each in enumerate(pool):
if each in primes:
print i, |
http://rosettacode.org/wiki/Averages/Mean_time_of_day | Averages/Mean time of day | Task[edit]
A particular activity of bats occurs at these times of the day:
23:00:17, 23:40:20, 00:12:45, 00:17:19
Using the idea that there are twenty-four hours in a day,
which is analogous to there being 360 degrees in a circle,
map times of day to and from angles;
and using the ideas of Averages/Mean angle
compute and show the average time of the nocturnal activity
to an accuracy of one second of time.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Swift | Swift | import Foundation
@inlinable public func d2r<T: FloatingPoint>(_ f: T) -> T { f * .pi / 180 }
@inlinable public func r2d<T: FloatingPoint>(_ f: T) -> T { f * 180 / .pi }
public func meanOfAngles(_ angles: [Double]) -> Double {
let cInv = 1 / Double(angles.count)
let (y, x) =
angles.lazy
.map(d2r)
.map({ (sin($0), cos($0)) })
.reduce(into: (0.0, 0.0), { $0.0 += $1.0; $0.1 += $1.1 })
return r2d(atan2(cInv * y, cInv * x))
}
struct DigitTime {
var hour: Int
var minute: Int
var second: Int
init?(fromString str: String) {
let split = str.components(separatedBy: ":").compactMap(Int.init)
guard split.count == 3 else {
return nil
}
(hour, minute, second) = (split[0], split[1], split[2])
}
init(fromDegrees angle: Double) {
let totalSeconds = 24 * 60 * 60 * angle / 360
second = Int(totalSeconds.truncatingRemainder(dividingBy: 60))
minute = Int((totalSeconds.truncatingRemainder(dividingBy: 3600) - Double(second)) / 60)
hour = Int(totalSeconds / 3600)
}
func toDegrees() -> Double {
return 360 * Double(hour) / 24.0 + 360 * Double(minute) / (24 * 60.0) + 360 * Double(second) / (24 * 3600.0)
}
}
extension DigitTime: CustomStringConvertible {
var description: String { String(format: "%02i:%02i:%02i", hour, minute, second) }
}
let times = ["23:00:17", "23:40:20", "00:12:45", "00:17:19"].compactMap(DigitTime.init(fromString:))
guard times.count == 4 else {
fatalError()
}
let meanTime = DigitTime(fromDegrees: 360 + meanOfAngles(times.map({ $0.toDegrees() })))
print("Given times \(times), the mean time is \(meanTime)") |
http://rosettacode.org/wiki/Averages/Mean_time_of_day | Averages/Mean time of day | Task[edit]
A particular activity of bats occurs at these times of the day:
23:00:17, 23:40:20, 00:12:45, 00:17:19
Using the idea that there are twenty-four hours in a day,
which is analogous to there being 360 degrees in a circle,
map times of day to and from angles;
and using the ideas of Averages/Mean angle
compute and show the average time of the nocturnal activity
to an accuracy of one second of time.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Tcl | Tcl | proc meanTime {times} {
set secsPerRad [expr {60 * 60 * 12 / atan2(0,-1)}]
set sumSin [set sumCos 0.0]
foreach t $times {
# Convert time to count of seconds from midnight
scan $t "%02d:%02d:%02d" h m s
incr s [expr {[incr m [expr {$h * 60}]] * 60}]
# Feed into averaging
set sumSin [expr {$sumSin + sin($s / $secsPerRad)}]
set sumCos [expr {$sumCos + cos($s / $secsPerRad)}]
}
# Don't need to divide by counts; atan2() cancels that out
set a [expr {round(atan2($sumSin, $sumCos) * $secsPerRad)}]
# Convert back to human-readable
format "%02d:%02d:%02d" [expr {$a / 60 / 60 % 24}] [expr {$a / 60 % 60}] [expr {$a % 60}]
}
puts [meanTime {23:00:17 23:40:20 00:12:45 00:17:19}] |
http://rosettacode.org/wiki/Averages/Mean_angle | Averages/Mean angle | When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle.
If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the second was of 10 degrees then the average of the numbers is 180 degrees, whereas if you can note that 350 degrees is equivalent to -10 degrees and so you have two readings at 10 degrees either side of zero degrees leading to a more fitting mean angle of zero degrees.
To calculate the mean angle of several angles:
Assume all angles are on the unit circle and convert them to complex numbers expressed in real and imaginary form.
Compute the mean of the complex numbers.
Convert the complex mean to polar coordinates whereupon the phase of the complex mean is the required angular mean.
(Note that, since the mean is the sum divided by the number of numbers, and division by a positive real number does not affect the angle, you can also simply compute the sum for step 2.)
You can alternatively use this formula:
Given the angles
α
1
,
…
,
α
n
{\displaystyle \alpha _{1},\dots ,\alpha _{n}}
the mean is computed by
α
¯
=
atan2
(
1
n
⋅
∑
j
=
1
n
sin
α
j
,
1
n
⋅
∑
j
=
1
n
cos
α
j
)
{\displaystyle {\bar {\alpha }}=\operatorname {atan2} \left({\frac {1}{n}}\cdot \sum _{j=1}^{n}\sin \alpha _{j},{\frac {1}{n}}\cdot \sum _{j=1}^{n}\cos \alpha _{j}\right)}
Task[edit]
write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle.
(You should use a built-in function if you have one that does this for degrees or radians).
Use the function to compute the means of these lists of angles (in degrees):
[350, 10]
[90, 180, 270, 360]
[10, 20, 30]
Show your output here.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #VBA | VBA | Option Base 1
Private Function mean_angle(angles As Variant) As Double
Dim sins() As Double, coss() As Double
ReDim sins(UBound(angles))
ReDim coss(UBound(angles))
For i = LBound(angles) To UBound(angles)
sins(i) = Sin(WorksheetFunction.Radians(angles(i)))
coss(i) = Cos(WorksheetFunction.Radians(angles(i)))
Next i
mean_angle = WorksheetFunction.Degrees( _
WorksheetFunction.Atan2( _
WorksheetFunction.sum(coss), _
WorksheetFunction.sum(sins)))
End Function
Public Sub main()
Debug.Print Format(mean_angle([{350,10}]), "##0")
Debug.Print Format(mean_angle([{90, 180, 270, 360}]), "##0")
Debug.Print Format(mean_angle([{10, 20, 30}]), "##0")
End Sub |
http://rosettacode.org/wiki/Averages/Mean_angle | Averages/Mean angle | When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle.
If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the second was of 10 degrees then the average of the numbers is 180 degrees, whereas if you can note that 350 degrees is equivalent to -10 degrees and so you have two readings at 10 degrees either side of zero degrees leading to a more fitting mean angle of zero degrees.
To calculate the mean angle of several angles:
Assume all angles are on the unit circle and convert them to complex numbers expressed in real and imaginary form.
Compute the mean of the complex numbers.
Convert the complex mean to polar coordinates whereupon the phase of the complex mean is the required angular mean.
(Note that, since the mean is the sum divided by the number of numbers, and division by a positive real number does not affect the angle, you can also simply compute the sum for step 2.)
You can alternatively use this formula:
Given the angles
α
1
,
…
,
α
n
{\displaystyle \alpha _{1},\dots ,\alpha _{n}}
the mean is computed by
α
¯
=
atan2
(
1
n
⋅
∑
j
=
1
n
sin
α
j
,
1
n
⋅
∑
j
=
1
n
cos
α
j
)
{\displaystyle {\bar {\alpha }}=\operatorname {atan2} \left({\frac {1}{n}}\cdot \sum _{j=1}^{n}\sin \alpha _{j},{\frac {1}{n}}\cdot \sum _{j=1}^{n}\cos \alpha _{j}\right)}
Task[edit]
write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle.
(You should use a built-in function if you have one that does this for degrees or radians).
Use the function to compute the means of these lists of angles (in degrees):
[350, 10]
[90, 180, 270, 360]
[10, 20, 30]
Show your output here.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Visual_Basic_.NET | Visual Basic .NET | Imports System.Math
Module Module1
Function MeanAngle(angles As Double()) As Double
Dim x = angles.Sum(Function(a) Cos(a * PI / 180)) / angles.Length
Dim y = angles.Sum(Function(a) Sin(a * PI / 180)) / angles.Length
Return Atan2(y, x) * 180 / PI
End Function
Sub Main()
Dim printMean = Sub(x As Double()) Console.WriteLine("{0:0.###}", MeanAngle(x))
printMean({350, 10})
printMean({90, 180, 270, 360})
printMean({10, 20, 30})
End Sub
End Module |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches to this. One is to sort the elements, and then pick the element(s) in the middle.
Sorting would take at least O(n logn). Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s). This would also take O(n logn). The best solution is to use the selection algorithm to find the median in O(n) time.
See also
Quickselect_algorithm
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Maple | Maple |
> Statistics:-Median( [ 1, 5, 3, 2, 4 ] );
3.
> Statistics:-Median( [ 1, 5, 3, 6, 2, 4 ] );
3.50000000000000
|
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches to this. One is to sort the elements, and then pick the element(s) in the middle.
Sorting would take at least O(n logn). Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s). This would also take O(n logn). The best solution is to use the selection algorithm to find the median in O(n) time.
See also
Quickselect_algorithm
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | Median[{1, 5, 3, 2, 4}]
Median[{1, 5, 3, 6, 4, 2}] |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of positive integers.
The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
A
(
x
1
,
…
,
x
n
)
=
x
1
+
⋯
+
x
n
n
{\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}}
The geometric mean is the
n
{\displaystyle n}
th root of the product of the list:
G
(
x
1
,
…
,
x
n
)
=
x
1
⋯
x
n
n
{\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}}
The harmonic mean is
n
{\displaystyle n}
divided by the sum of the reciprocal of each item in the list:
H
(
x
1
,
…
,
x
n
)
=
n
1
x
1
+
⋯
+
1
x
n
{\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
numeric digits 20
a1 = ArrayList(Arrays.asList([Rexx 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]))
say "Arithmetic =" arithmeticMean(a1)", Geometric =" geometricMean(a1)", Harmonic =" harmonicMean(a1)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method arithmeticMean(numbers = java.util.List) public static returns Rexx
-- somewhat arbitrary return for ooRexx
if numbers.isEmpty then return "NaN"
mean = 0
number = Rexx
loop number over numbers
mean = mean + number
end
return mean / numbers.size
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method geometricMean(numbers = java.util.List) public static returns Rexx
-- somewhat arbitrary return for ooRexx
if numbers.isEmpty then return "NaN"
mean = 1
number = Rexx
loop number over numbers
mean = mean * number
end
return Math.pow(mean, 1 / numbers.size)
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method harmonicMean(numbers = java.util.List) public static returns Rexx
-- somewhat arbitrary return for ooRexx
if numbers.isEmpty then return "NaN"
mean = 0
number = Rexx
loop number over numbers
if number = 0 then return "Nan"
mean = mean + (1 / number)
end
-- problem here...
return numbers.size / mean
|
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function Right6Digits(num As Long) As Long
Dim asString = num.ToString()
If asString.Length < 6 Then
Return num
End If
Dim last6 = asString.Substring(asString.Length - 6)
Return Long.Parse(last6)
End Function
Sub Main()
Dim bnSq = 0 'the base number squared
Dim bn = 0 'the number to be squared
Do
bn = bn + 1
bnSq = bn * bn
Loop While Right6Digits(bnSq) <> 269696
Console.WriteLine("The smallest integer whose square ends in 269,696 is {0}", bn)
Console.WriteLine("The square is {0}", bnSq)
End Sub
End Module |
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #Gambas | Gambas | 'Altered to prevent lines starting with ']' or ending with '[' being generated as they can't work
siNumberOfBrackets As Short = 20 'Maximum amount of brackets in a line
siNumberOfLines As Short = 20 'Amount of lines to test
'----
Public Sub Main()
Dim sBrks As String[] = GenerateBrackets() 'Get random array to check
Dim sTemp, sHold, sWork As String 'Working variables
Dim siCount As Short 'Counter
For Each sTemp In sBrks 'For each line in the sBrk array (e.g. '[][][][[[[]][]]]')
sWork = sTemp 'Make sWork = sTemp
Repeat 'Repeat
sHold = sWork 'Make sHold = sWork
sWork = Replace(sWork, "[]", "") 'Remove all brackets that match '[]'
Until sHold = sWork 'If sHold = sWork then there are no more '[]' matches
If sWork = "" Then 'So if all the brackets 'Nested' correctly sWork will be empty
Print " OK "; 'Print 'OK'
Else 'Else they did not all match
Print "NOT OK "; 'So print 'NOT OK'
Endif
For siCount = 1 To Len(sTemp) 'Loop through the line of brackets
Print Mid(sTemp, siCount, 1) & " "; 'Print each bracket + a space to make it easier to read
Next
Print 'Print a new line
Next
End
'----
Public Sub GenerateBrackets() As String[] 'Generates an array of random quantities of '[' and ']'
Dim siQty As New Short[] 'To store the random number (of brackets) to put in a line
Dim sBrk As New String[] 'To store the lines of brackets
Dim siNum, siEnd, siLoop As Short 'Various counters
Dim sTemp As String 'Temp string
Repeat 'Repeat
siNum = Rand(0, siNumberOfBrackets) 'Pick a number between 0 and the total number of brackets requested
If Even(siNum) Then siQty.Add(siNum) 'If the number is even then add the number to siQty
Until siQty.Count = siNumberOfLines 'Keep going until we have the number of lines requested
For Each siNum In siQty 'For each number in siQty..(e.g. 6)
Do
siEnd = Rand(0, 1) 'Generate a 0 or a 1
If siEnd = 0 Then sTemp &= "[" 'If '0' then add a '[' bracket
If siEnd = 1 Then sTemp &= "]" 'If '1' then add a ']' bracket
If siNum = 0 Then 'If siNum = 0 then..
sBrk.Add("") 'Add '0' to the array
sTemp = "" 'Clear sTemp
Break 'Exit the Do Loop
Endif
If Len(sTemp) = siNum Then 'If the length of sTemp = the required amount then..
If sTemp Not Begins "]" And sTemp Not Ends "[" Then 'Check to see that sTemp does not start with "]" and does not end with a "["
sBrk.Add(sTemp) 'Add it to the array
sTemp = "" 'Clear sTemp
Break 'Exit the Do Loop
Else 'Else
sTemp = "" 'Clear sTemp
End If 'Try again!
Endif
Loop
Next
Return sBrk 'Return the sBrk array
End |
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file | Append a record to the end of a text file | Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment.
This feature is most useful in the case of log files, where many jobs may be appending to the log file at the same time, or where care must be taken to avoid concurrently overwriting the same record from another job.
Task
Given a two record sample for a mythical "passwd" file:
Write these records out in the typical system format.
Ideally these records will have named fields of various types.
Close the file, then reopen the file for append.
Append a new record to the file and close the file again.
Take appropriate care to avoid concurrently overwrites from another job.
Open the file and demonstrate the new record has indeed written to the end.
Source record field types and contents.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
jsmith
x
1001
1000
Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]
/home/jsmith
/bin/bash
jdoe
x
1002
1000
Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]
/home/jdoe
/bin/bash
Record to be appended.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
xyz
x
1003
1000
X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]
/home/xyz
/bin/bash
Resulting file format: should mimic Linux's /etc/passwd file format with particular attention to the "," separator used in the GECOS field. But if the specific language has a particular or unique format of storing records in text file, then this format should be named and demonstrated with an additional example.
Expected output:
Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash
Finally: Provide a summary of the language's "append record" capabilities in a table. eg.
Append Capabilities.
Data Representation
IO
Library
Append
Possible
Automatic
Append
Multi-tasking
Safe
In core
On disk
C struct
CSV text file
glibc/stdio
☑
☑
☑ (Not all, eg NFS)
Alternatively: If the language's appends can not guarantee its writes will always append, then note this restriction in the table. If possible, provide an actual code example (possibly using file/record locking) to guarantee correct concurrent appends.
| #Phix | Phix | without js -- (file i/o, sleep, task_yield, wait_key)
constant filename = "passwd.txt"
integer fn
constant
rec1 = {"jsmith","x",1001,1000,{"Joe Smith","Room 1007","(234)555-8917","(234)555-0077","[email protected]"},"/home/jsmith","/bin/bash"},
rec2 = {"jdoe","x",1002,1000,{"Jane Doe","Room 1004","(234)555-8914","(234)555-0044","[email protected]"},"/home/jdoe","/bin/bash"},
rec3 = {"xyz","x",1003,1000,{"X Yz","Room 1003","(234)555-8913","(234)555-0033","[email protected]"},"/home/xyz","/bin/bash"}
function tostring(sequence record)
record[3] = sprintf("%d",{record[3]})
record[4] = sprintf("%d",{record[4]})
record[5] = join(record[5],",")
record = join(record,":")
return record
end function
procedure wait(string what)
?sprintf("wait (%s)",{what})
sleep(1)
task_yield()
end procedure
if not file_exists(filename) then
fn = open(filename,"w")
if fn!=-1 then -- (someone else just beat us to it?)
printf(fn,"account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell\n")
printf(fn,"%s\n",{tostring(rec1)})
printf(fn,"%s\n",{tostring(rec2)})
close(fn)
end if
end if
while 1 do
fn = open(filename,"a")
if fn!=-1 then exit end if
wait("append")
end while
--?"file open in append mode"; {} = wait_key()
while 1 do
if lock_file(fn,LOCK_EXCLUSIVE,{}) then exit end if
wait("lock")
end while
--?"file locked"; {} = wait_key()
printf(fn,"%s\n",{tostring(rec3)})
unlock_file(fn,{})
close(fn)
while 1 do
fn = open(filename,"r")
if fn!=-1 then exit end if
wait("read")
end while
?gets(fn)
while 1 do
object line = gets(fn)
if atom(line) then exit end if
?line
{line} = scanf(line,"%s:%s:%d:%d:%s:%s:%s\n")
line[5] = split(line[5],',')
?line
end while
close(fn)
|
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
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
| #C.2B.2B | C++ | #include <map> |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #Kotlin | Kotlin | // Version 1.3.10
fun countDivisors(n: Int): Int {
if (n < 2) return 1;
var count = 2 // 1 and n
for (i in 2..n / 2) {
if (n % i == 0) count++
}
return count;
}
fun main(args: Array<String>) {
println("The first 20 anti-primes are:")
var maxDiv = 0
var count = 0
var n = 1
while (count < 20) {
val d = countDivisors(n)
if (d > maxDiv) {
print("$n ")
maxDiv = d
count++
}
n++
}
println()
} |
http://rosettacode.org/wiki/Atomic_updates | Atomic updates |
Task
Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to:
get the current value of any bucket
remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the transferred amount to ensure the values remain non-negative
In order to exercise this data type, create one set of buckets, and start three concurrent tasks:
As often as possible, pick two buckets and make their values closer to equal.
As often as possible, pick two buckets and arbitrarily redistribute their values.
At whatever rate is convenient, display (by any means) the total value and, optionally, the individual values of each bucket.
The display task need not be explicit; use of e.g. a debugger or trace tool is acceptable provided it is simple to set up to provide the display.
This task is intended as an exercise in atomic operations. The sum of the bucket values must be preserved even if the two tasks attempt to perform transfers simultaneously, and a straightforward solution is to ensure that at any time, only one transfer is actually occurring — that the transfer operation is atomic.
| #Wren | Wren | import "random" for Random
import "scheduler" for Scheduler
import "timer" for Timer
import "/math" for Nums
var Rnd = Random.new()
var NUM_BUCKETS = 10
var MAX_VALUE = 9999
class Buckets {
construct new(data) {
_data = data.toList
_running = true
}
[index] { _data[index] }
transfer(srcIndex, dstIndex, amount) {
if (amount < 0) Fiber.abort("Negative amount: %(amount)")
if (amount == 0) return 0
var a = amount
if (_data[srcIndex] - a < 0) a = _data[srcIndex]
if (_data[dstIndex] + a < 0) a = MAX_VALUE - _data[dstIndex]
if (a < 0) Fiber.abort("Negative amount: %(a)")
_data[srcIndex] = _data[srcIndex] - a
_data[dstIndex] = _data[dstIndex] + a
return a
}
buckets { _data.toList }
transferRandomAmount() {
while (_running) {
var srcIndex = Rnd.int(NUM_BUCKETS)
var dstIndex = Rnd.int(NUM_BUCKETS)
var amount = Rnd.int(MAX_VALUE + 1)
transfer(srcIndex, dstIndex, amount)
Timer.sleep(1)
}
}
equalize() {
while (_running) {
var srcIndex = Rnd.int(NUM_BUCKETS)
var dstIndex = Rnd.int(NUM_BUCKETS)
var amount = ((this[srcIndex] - this[dstIndex])/2).truncate
if (amount >= 0) transfer(srcIndex, dstIndex, amount)
Timer.sleep(1)
}
}
stop() { _running = false }
print() {
Timer.sleep(1000) // one second delay between prints
var bucketValues = buckets
System.print("Current values: %(Nums.sum(bucketValues)) %(bucketValues)")
}
}
var values = List.filled(NUM_BUCKETS, 0)
for (i in 0...NUM_BUCKETS) values[i] = Rnd.int(MAX_VALUE + 1)
System.print("Initial array : %(Nums.sum(values)) %(values)")
var buckets = Buckets.new(values)
var count = 0
while (true) {
Scheduler.add {
buckets.equalize()
}
buckets.print()
Scheduler.add {
buckets.transferRandomAmount()
}
buckets.print()
count = count + 2
if (count == 10) { // stop after 10 prints, say
buckets.stop()
break
}
} |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Ring | Ring |
x = 42
assert( x = 42 )
assert( x = 100 )
|
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #RLaB | RLaB |
// test if 'a' is 42, and if not stop the execution of the code and print
// some error message
if (a != 42)
{
stop("a is not 42 as expected, therefore I stop until this issue is resolved!");
}
|
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Ruby | Ruby | require "test/unit/assertions"
include Test::Unit::Assertions
n = 5
begin
assert_equal(42, n)
rescue Exception => e
# Ruby 1.8: e is a Test::Unit::AssertionFailedError
# Ruby 1.9: e is a MiniTest::Assertion
puts e
end |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Rust | Rust |
let x = 42;
assert!(x == 42);
assert_eq!(x, 42);
|
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #F.23 | F# | let evenp x = x % 2 = 0
let result = Array.map evenp [| 1; 2; 3; 4; 5; 6 |] |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Factor | Factor | { 1 2 3 4 } [ sq . ] each |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Raku | Raku | sub mode (*@a) {
my %counts := @a.Bag;
my $max = %counts.values.max;
%counts.grep(*.value == $max).map(*.key);
}
# Testing with arrays:
say mode [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];
say mode [1, 1, 2, 4, 4]; |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.