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/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
| #Lasso | Lasso | define average(a::array) => {
not #a->size ? return 0
local(x = 0.0)
with i in #a do => { #x += #i }
return #x / #a->size
}
average(array(1,2,5,17,7.4)) //6.48 |
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
| #LFE | LFE |
(defun mean (data)
(/ (lists:sum data)
(length data)))
|
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.
| #Vlang | Vlang | fn is_prime(n int) bool {
if n < 2 {
return false
}
else if n%2 == 0 {
return n == 2
}
else if n%3 == 0 {
return n == 3
}
else {
mut d := 5
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
}
fn count_prime_factors(n int) int {
mut nn := n
if n == 1 {
return 0
}
else if is_prime(nn) {
return 1
}
else {
mut count, mut f := 0, 2
for {
if nn%f == 0 {
count++
nn /= f
if nn == 1{
return count
}
if is_prime(nn) {
f = nn
}
} else if f >= 3{
f += 2
} else {
f = 3
}
}
return count
}
}
fn main() {
max := 120
println('The attractive numbers up to and including $max are:')
mut count := 0
for i in 1 .. max+1 {
n := count_prime_factors(i)
if is_prime(n) {
print('${i:4}')
count++
if count%20 == 0 {
println('')
}
}
}
} |
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.
| #Wren | Wren | import "/fmt" for Fmt
import "/math" for Int
var max = 120
System.print("The attractive numbers up to and including %(max) are:")
var count = 0
for (i in 1..max) {
var n = Int.primeFactors(i).count
if (Int.isPrime(n)) {
System.write(Fmt.d(4, i))
count = count + 1
if (count%20 == 0) System.print()
}
}
System.print() |
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
| #Oz | Oz | declare
fun {Median Xs}
Len = {Length Xs}
Mid = Len div 2 + 1 %% 1-based index
Sorted = {Sort Xs Value.'<'}
in
if {IsOdd Len} then {Nth Sorted Mid}
else ({Nth Sorted Mid} + {Nth Sorted Mid-1}) / 2.0
end
end
in
{Show {Median [4.1 5.6 7.2 1.7 9.3 4.4 3.2]}}
{Show {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
| #Perl | Perl | sub A
{
my $a = 0;
$a += $_ for @_;
return $a / @_;
}
sub G
{
my $p = 1;
$p *= $_ for @_;
return $p**(1/@_); # power of 1/n == root of n
}
sub H
{
my $h = 0;
$h += 1/$_ for @_;
return @_/$h;
}
my @ints = (1..10);
my $a = A(@ints);
my $g = G(@ints);
my $h = H(@ints);
print "A=$a\nG=$g\nH=$h\n";
die "Error" unless $a >= $g and $g >= $h; |
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
| #K | K |
gen_brackets:{"[]"@x _draw 2}
check:{r:(-1;1)@"["=x; *(0=+/cs<'0)&(0=-1#cs:+\r)}
{(x;check x)}' gen_brackets' 2*1+!10
(("[[";0)
("[][]";1)
("][][]]";0)
("[[][[][]";0)
("][]][[[[[[";0)
("]]][[]][]]][";0)
("[[[]][[[][[[][";0)
("[[]][[[]][]][][]";1)
("][[][[]]][[]]]][][";0)
("]][[[[]]]][][][[]]]]";0))
|
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.
| #UNIX_Shell | UNIX Shell | 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
)
filename=./passwd-ish
# use parentheses to run the commands in a subshell, so the
# current shell's IFS variable is not changed
(
IFS=:
echo "${rec1[*]}"
echo "${rec2[*]}"
) > "$filename"
echo before appending:
cat "$filename"
# appending, use the ">>" redirection symbol
IFS=:
echo "${rec3[*]}" >> "$filename"
echo after appending:
cat "$filename" |
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.
| #Ursa | Ursa | # ursa appends to files by default when the out function is used
# create new passwd in working directory
decl file f
f.create "passwd"
f.open "passwd"
out "account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell" endl f
out "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash" endl f
out "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash" endl f
f.close
# display the created file
f.open "passwd"
out "initial file:" endl console
while (f.hasline)
out (in string f) endl console
end while
# append the new record
out "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash" endl f
f.close
# output the new file contents
f.open "passwd"
out endl endl "file after append:" endl console
while (f.hasline)
out (in string f) endl console
end while |
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
| #Delphi | Delphi | program AssociativeArrayCreation;
{$APPTYPE CONSOLE}
uses Generics.Collections;
var
lDictionary: TDictionary<string, Integer>;
begin
lDictionary := TDictionary<string, Integer>.Create;
try
lDictionary.Add('foo', 5);
lDictionary.Add('bar', 10);
lDictionary.Add('baz', 15);
lDictionary.AddOrSetValue('foo', 6); // replaces value if it exists
finally
lDictionary.Free;
end;
end. |
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
| #Processing | Processing | void setup() {
int most_factors = 0;
IntList anti_primes = new IntList();
int n = 1;
while (anti_primes.size() < 20) {
int counter = 1;
for (int i = 1; i <= n / 2; i++) {
if (n % i == 0) {
counter++;
}
}
if (counter > most_factors) {
anti_primes.append(n);
most_factors = counter;
}
n++;
}
for (int num : anti_primes) {
print(num + " ");
}
} |
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
| #Prolog | Prolog |
divcount(N, Count) :- divcount(N, 1, 0, Count).
divcount(N, D, C, C) :- D*D > N, !.
divcount(N, D, C, Count) :-
succ(D, D2),
divs(N, D, A), plus(A, C, C2),
divcount(N, D2, C2, Count).
divs(N, D, 0) :- N mod D =\= 0, !.
divs(N, D, 1) :- D*D =:= N, !.
divs(_, _, 2).
antiprimes(N, L) :- antiprimes(N, 1, 0, [], L).
antiprimes(0, _, _, L, R) :- reverse(L, R), !.
antiprimes(N, M, Max, L, R) :-
divcount(M, Count),
succ(M, M2),
(Count > Max
-> succ(N0, N), antiprimes(N0, M2, Count, [M|L], R)
; antiprimes(N, M2, Max, L, R)).
main :-
antiprimes(20, X),
write("The first twenty anti-primes are "), write(X), nl,
halt.
?- main.
|
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.
| #Java | Java | public class ArrayCallback7 {
interface IntConsumer {
void run(int x);
}
interface IntToInt {
int run(int x);
}
static void forEach(int[] arr, IntConsumer consumer) {
for (int i : arr) {
consumer.run(i);
}
}
static void update(int[] arr, IntToInt mapper) {
for (int i = 0; i < arr.length; i++) {
arr[i] = mapper.run(arr[i]);
}
}
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
forEach(numbers, new IntConsumer() {
public void run(int x) {
System.out.println(x);
}
});
update(numbers, new IntToInt() {
@Override
public int run(int x) {
return x * x;
}
});
forEach(numbers, new IntConsumer() {
public void run(int x) {
System.out.println(x);
}
});
}
} |
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
| #UNIX_Shell | UNIX Shell | #!/bin/bash
function mode {
declare -A map
max=0
for x in "$@"; do
tmp=$((${map[$x]} + 1))
map[$x]=$tmp
((tmp > max)) && max=$tmp
done
for x in "${!map[@]}"; do
[[ ${map[$x]} == $max ]] && echo -n "$x "
done
echo
} |
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
| #Lua | Lua | local t = {
["foo"] = "bar",
["baz"] = 6,
fortytwo = 7
}
for key,val in pairs(t) do
print(string.format("%s: %s", key, val))
end |
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
| #M2000_Interpreter | M2000 Interpreter |
Module checkit {
\\ Inventories are objects with keys and values, or keys (used as read only values)
\\ They use hash function.
\\ Function TwoKeys return Inventory object (as a pointer to object)
Function TwoKeys {
Inventory Alfa="key1":=100, "key2":=200
=Alfa
}
M=TwoKeys()
Print Type$(M)="Inventory"
\\ Normal Use:
\\ Inventories Keys are case sensitive
\\ M2000 identifiers are not case sensitive
Print M("key1"), m("key2")
\\ numeric values can convert to strings
Print M$("key1"), m$("key2")
\\ Iteration
N=Each(M)
While N {
Print Eval(N) ' prints 100, 200 as number
Print M(N^!) ' The same using index N^
}
N=Each(M)
While N {
Print Eval$(N) ' prints 100, 200 as strings
Print M$(N^!) ' The same using index N^
}
N=Each(M)
While N {
Print Eval$(N, N^) ' Prints Keys
}
\\ double iteration
Append M, "key3":=500
N=Each(M, 1, -1) ' start to end
N1=Each(M, -1, 1) ' end to start
\\ 3x3 prints
While N {
While N1 {
Print format$("{0}*{1}={2}", Eval(N1), Eval(N), Eval(N1)*Eval(N))
}
}
\\ sort results from lower product to greater product (3+2+1, 6 prints only)
N=Each(M, 1, -1)
While N {
N1=Each(M, N^+1, -1)
While N1 {
Print format$("{0}*{1}={2}", Eval(N1), Eval(N), Eval(N1)*Eval(N))
}
}
N=Each(M)
N1=Each(M,-2, 1) ' from second from end to start
\\ print only 2 values. While block ends when one iterator finish
While N, N1 {
Print Eval(N1)*Eval(N)
}
}
Checkit
|
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
| #Liberty_BASIC | Liberty BASIC | total=17
dim nums(total)
for i = 1 to total
nums(i)=i-1
next
for j = 1 to total
sum=sum+nums(j)
next
if total=0 then mean=0 else mean=sum/total
print "Arithmetic mean: ";mean
|
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
| #Limbo | Limbo | implement Command;
include "sys.m";
sys: Sys;
include "draw.m";
include "sh.m";
init(nil: ref Draw->Context, nil: list of string)
{
sys = load Sys Sys->PATH;
a := array[] of {1.0, 2.0, 500.0, 257.0};
sys->print("mean of a: %f\n", getmean(a));
}
getmean(a: array of real): real
{
n: real = 0.0;
for (i := 0; i < len a; i++)
n += a[i];
return n / (real len a);
} |
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.
| #XPL0 | XPL0 | func IsPrime(N); \Return 'true' if N is prime
int N, I;
[if N <= 2 then return N = 2;
if (N&1) = 0 then \even >2\ return false;
for I:= 3 to sqrt(N) do
[if rem(N/I) = 0 then return false;
I:= I+1;
];
return true;
];
func Factors(N); \Return number of factors for N
int N, Cnt, F;
[Cnt:= 0;
F:= 2;
repeat if rem(N/F) = 0 then
[Cnt:= Cnt+1;
N:= N/F;
]
else F:= F+1;
until F > N;
return Cnt;
];
int C, N;
[C:= 0;
for N:= 4 to 120 do
if IsPrime(Factors(N)) then
[IntOut(0, N);
C:= C+1;
if rem(C/10) then ChOut(0, 9\tab\) else CrLf(0);
];
] |
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.
| #zkl | zkl | var [const] BI=Import("zklBigNum"); // libGMP
fcn attractiveNumber(n){ BI(primeFactors(n).len()).probablyPrime() }
println("The attractive numbers up to and including 120 are:");
[1..120].filter(attractiveNumber)
.apply("%4d".fmt).pump(Void,T(Void.Read,19,False),"println"); |
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
| #PARI.2FGP | PARI/GP | median(v)={
vecsort(v)[#v\2]
}; |
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
| #Pascal | Pascal | Program AveragesMedian(output);
type
TDoubleArray = array of double;
procedure bubbleSort(var list: TDoubleArray);
var
i, j, n: integer;
t: double;
begin
n := length(list);
for i := n downto 2 do
for j := 0 to i - 1 do
if list[j] > list[j + 1] then
begin
t := list[j];
list[j] := list[j + 1];
list[j + 1] := t;
end;
end;
function Median(aArray: TDoubleArray): double;
var
lMiddleIndex: integer;
begin
bubbleSort(aArray);
lMiddleIndex := (high(aArray) - low(aArray)) div 2;
if Odd(Length(aArray)) then
Median := aArray[lMiddleIndex + 1]
else
Median := (aArray[lMiddleIndex + 1] + aArray[lMiddleIndex]) / 2;
end;
var
A: TDoubleArray;
i: integer;
begin
randomize;
setlength(A, 7);
for i := low(A) to high(A) do
begin
A[i] := 100 * random;
write (A[i]:7:3, ' ');
end;
writeln;
writeln('Median: ', Median(A):7:3);
setlength(A, 6);
for i := low(A) to high(A) do
begin
A[i] := 100 * random;
write (A[i]:7:3, ' ');
end;
writeln;
writeln('Median: ', Median(A):7:3);
end. |
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
| #Phix | Phix | with javascript_semantics
function arithmetic_mean(sequence s)
return sum(s)/length(s)
end function
function geometric_mean(sequence s)
return power(product(s),1/length(s))
end function
function harmonic_mean(sequence s)
return length(s)/sum(sq_div(1,s))
end function
constant s = {1,2,3,4,5,6,7,8,9,10}
constant arithmetic = arithmetic_mean(s),
geometric = geometric_mean(s),
harmonic = harmonic_mean(s)
printf(1,"Arithmetic: %.10g\n", arithmetic)
printf(1,"Geometric: %.10g\n", geometric)
printf(1,"Harmonic: %.10g\n", harmonic)
printf(1,"Arithmetic>=Geometric>=Harmonic: %t\n", {arithmetic>=geometric and geometric>=harmonic})
|
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
| #Klingphix | Klingphix | "[[]][]]"
%acc 0 !acc
%flag false !flag
len [
get tochar dup
"[" == [$acc 1 + !acc] if
"]" == [$acc 1 - !acc] if
$acc 0 < [true !flag] if
] for
print
$acc 0 # $flag or ( [" is NOT ok"] [" is OK"] ) if
print
" " input |
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.
| #Visual_Basic_.NET | Visual Basic .NET | Imports System.IO
Module Module1
Class PasswordRecord
Public account As String
Public password As String
Public fullname As String
Public office As String
Public extension As String
Public homephone As String
Public email As String
Public directory As String
Public shell As String
Public UID As Integer
Public GID As Integer
Public Sub New(account As String, password As String, UID As Integer, GID As Integer, fullname As String, office As String, extension As String, homephone As String, email As String, directory As String, shell As String)
Me.account = account
Me.password = password
Me.UID = UID
Me.GID = GID
Me.fullname = fullname
Me.office = office
Me.extension = extension
Me.homephone = homephone
Me.email = email
Me.directory = directory
Me.shell = shell
End Sub
Public Overrides Function ToString() As String
Dim gecos = String.Join(",", New String() {fullname, office, extension, homephone, email})
Return String.Join(":", New String() {account, password, UID.ToString(), GID.ToString(), gecos, directory, shell})
End Function
End Class
Sub Main()
Dim jsmith As New PasswordRecord("jsmith", "x", 1001, 1000, "Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "[email protected]", "/home/jsmith", "/bin/bash")
Dim jdoe As New PasswordRecord("jdoe", "x", 1002, 1000, "Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "[email protected]", "/home/jdoe", "/bin/bash")
Dim xyz As New PasswordRecord("xyz", "x", 1003, 1000, "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "[email protected]", "/home/xyz", "/bin/bash")
' Write these records out in the typical system format.
File.WriteAllLines("passwd.txt", New String() {jsmith.ToString(), jdoe.ToString()})
' Append a new record to the file and close the file again.
File.AppendAllText("passwd.txt", xyz.ToString())
' Open the file and demonstrate the new record has indeed been written to the end.
Dim lines = File.ReadAllLines("passwd.txt")
Console.WriteLine("Appended record: {0}", lines(2))
End Sub
End Module |
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
| #Dyalect | Dyalect | var t = (x: 1, y: 2, z: 3)
print(t.Keys().ToArray()) |
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
| #PureBasic | PureBasic | Procedure.i cntDiv(n.i)
Define.i i, count
If n < 2 : ProcedureReturn 1 : EndIf
count = 2 : i = 2
While i <= n / 2
If n % i = 0 : count + 1 : EndIf
i + 1
Wend
ProcedureReturn count
EndProcedure
; - - - MAIN - - -
Define.i n = 1, d, maxDiv = 0, count = 0
If OpenConsole("")
PrintN("The first 20 anti-primes are: ")
While count < 20
d = cntDiv(n)
If d > maxDiv
Print(Str(n) + " ")
maxDiv = d : count + 1
EndIf
n + 1
Wend
PrintN("")
Input()
EndIf
End 0 |
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
| #Python | Python | from itertools import chain, count, cycle, islice, accumulate
def factors(n):
def prime_powers(n):
for c in accumulate(chain([2, 1, 2], cycle([2,4]))):
if c*c > n: break
if n%c: continue
d,p = (), c
while not n%c:
n,p,d = n//c, p*c, d+(p,)
yield d
if n > 1: yield n,
r = [1]
for e in prime_powers(n):
r += [a*b for a in r for b in e]
return r
def antiprimes():
mx = 0
yield 1
for c in count(2,2):
if c >= 58: break
ln = len(factors(c))
if ln > mx:
yield c
mx = ln
for c in count(60,30):
ln = len(factors(c))
if ln > mx:
yield c
mx = ln
if __name__ == '__main__':
print(*islice(antiprimes(), 40))) |
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.
| #JavaScript | JavaScript | function map(a, func) {
var ret = [];
for (var i = 0; i < a.length; i++) {
ret[i] = func(a[i]);
}
return ret;
}
map([1, 2, 3, 4, 5], function(v) { return v * v; }); |
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.
| #Joy | Joy | [1 2 3 4 5] [dup *] map. |
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
| #Ursala | Ursala | #import std
mode = ~&hS+ leql$^&h+ eql|=@K2
#cast %nLW
examples = mode~~ (<1,3,6,6,6,7,7,12,12,17>,<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
| #VBA | VBA | Public Sub main()
s = [{1,2,3,3,3,4,4,4,5,5,6}]
t = WorksheetFunction.Mode_Mult(s)
For Each x In t
Debug.Print x;
Next x
End Sub |
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
| #M4 | M4 | divert(-1)
define(`for',
`ifelse($#,0,``$0'',
`ifelse(eval($2<=$3),1,
`pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')')
define(`new',`define(`$1[size]key',0)')
define(`asize',`defn(`$1[size]key')')
define(`aget',`defn(`$1[$2]')')
define(`akget',`defn(`$1[$2]key')')
define(`avget',`aget($1,akget($1,$2))')
define(`aset',
`ifdef($1[$2],
`',
`define(`$1[size]key',incr(asize(`$1')))`'define($1[asize(`$1')]key,$2)')`'define($1[$2],$3)')
define(`dquote', ``$@'')
define(`akeyvalue',`dquote(akget($1,$2),aget($1,akget($1,$2)))')
define(`akey',`dquote(akget($1,$2))')
define(`avalue',`dquote(aget($1,akget($1,$2)))')
divert
new(`a')
aset(`a',`wow',5)
aset(`a',`wow',flame)
aset(`a',`bow',7)
key-value pairs
for(`x',1,asize(`a'),
`akeyvalue(`a',x)
')
keys
for(`x',1,asize(`a'),
`akey(`a',x)
')
values
for(`x',1,asize(`a'),
`avalue(`a',x)
') |
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
| #Maple | Maple |
> T := table( [ "A" = 1, "B" = 2, "C" = 3, "D" = 4 ] );
> for i in indices( T, nolist ) do print(i ) end:
"A"
"B"
"C"
"D"
|
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
| #Lingo | Lingo | -- v can be (2D) point, (3D) vector or list of integers/floats
on mean (v)
case ilk(v) of
#point: cnt = 2
#vector: cnt = 3
#list: cnt = v.count
otherwise: return
end case
sum = 0
repeat with i = 1 to cnt
sum = sum + v[i]
end repeat
return float(sum)/cnt
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
| #LiveCode | LiveCode | average(1,2,3,4,5) -- 3
average(empty) -- 0 |
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
| #Perl | Perl | sub median {
my @a = sort {$a <=> $b} @_;
return ($a[$#a/2] + $a[@a/2]) / 2;
} |
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
| #Phix | Phix | with javascript_semantics
function median(sequence s)
atom res=0
integer l = length(s), k = floor((l+1)/2)
if l then
s = sort(s)
res = s[k]
if remainder(l,2)=0 then
res = (res+s[k+1])/2
end if
end if
return res
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
| #PHP | PHP | <?php
// Created with PHP 7.0
function ArithmeticMean(array $values)
{
return array_sum($values) / count($values);
}
function GeometricMean(array $values)
{
return array_product($values) ** (1 / count($values));
}
function HarmonicMean(array $values)
{
$sum = 0;
foreach ($values as $value) {
$sum += 1 / $value;
}
return count($values) / $sum;
}
$values = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
echo "Arithmetic: " . ArithmeticMean($values) . "\n";
echo "Geometric: " . GeometricMean($values) . "\n";
echo "Harmonic: " . HarmonicMean($values) . "\n";
|
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
| #Kotlin | Kotlin | import java.util.Random
fun isBalanced(s: String): Boolean {
if (s.isEmpty()) return true
var countLeft = 0 // number of left brackets so far unmatched
for (c in s) {
if (c == '[') countLeft++
else if (countLeft > 0) countLeft--
else return false
}
return countLeft == 0
}
fun main(args: Array<String>) {
println("Checking examples in task description:")
val brackets = arrayOf("", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]")
for (b in brackets) {
print(if (b != "") b else "(empty)")
println("\t " + if (isBalanced(b)) "OK" else "NOT OK")
}
println()
println("Checking 7 random strings of brackets of length 8:")
val r = Random()
(1..7).forEach {
var s = ""
for (j in 1..8) {
s += if (r.nextInt(2) == 0) '[' else ']'
}
println("$s " + if (isBalanced(s)) "OK" else "NOT OK")
}
} |
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.
| #Wren | Wren | import "io" for File, FileFlags
var records = [
"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"
]
// Write records to a new file called "passwd.csv" and close it.
var fileName = "passwd.csv"
File.create(fileName) {|file|
records.each { |r| file.writeBytes(r + "\n") }
}
// Check file has been created correctly.
var contents = File.read(fileName)
System.print("Initial records:\n")
System.print(contents)
var newRec = "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash"
// Append the new record to the file and close it.
File.openWithFlags(fileName, FileFlags.writeOnly) { |file|
file.writeBytes(newRec + "\n")
}
// Check the new record has been appended correctly.
contents = File.read(fileName)
System.print("Records after appending new one:\n")
System.print(contents) |
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
| #E | E | [].asMap() # immutable, empty
["one" => 1, "two" => 2] # immutable, 2 mappings
[].asMap().diverge() # mutable, empty
["one" => 2].diverge(String, float64) # mutable, initial contents,
# typed (coerces to float) |
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
| #Quackery | Quackery | 0 temp put
[] 0
[ 1+ dup factors size
dup temp share > iff
[ temp replace
dup dip join ]
else drop
over size 20 = until ]
temp release
drop echo |
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
| #R | R | # Antiprimes
max_divisors <- 0
findFactors <- function(x){
myseq <- seq(x)
myseq[(x %% myseq) == 0]
}
antiprimes <- vector()
x <- 1
n <- 1
while(length(antiprimes) < 20){
y <- findFactors(x)
if (length(y) > max_divisors){
antiprimes <- c(antiprimes, x)
max_divisors <- length(y)
n <- n + 1
}
x <- x + 1
}
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
| #Racket | Racket | #lang racket
(require racket/generator
math/number-theory)
(define (get-divisors n)
(apply * (map (λ (factor) (add1 (second factor))) (factorize n))))
(define antiprimes
(in-generator
(for/fold ([prev 0]) ([i (in-naturals 1)])
(define divisors (get-divisors i))
(when (> divisors prev) (yield i))
(max prev divisors))))
(for/list ([i (in-range 20)] [antiprime antiprimes]) antiprime) |
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.
| #jq | jq | # Illustration of map/1 using the builtin filter: exp
map(exp) # exponentiate each item in the input list
# A compound expression can be specified as the argument to map, e.g.
map( (. * .) + sqrt ) # x*x + sqrt(x)
# The compound expression can also be a composition of filters, e.g.
map( sqrt|floor ) # the floor of the sqrt
# Array comprehension
reduce .[] as $n ([]; . + [ exp ])
# Elementwise operation
[.[] + 1 ] # add 1 to each element of the input array
|
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.
| #Jsish | Jsish | /* Apply callback, in Jsish using array.map() */
;[1, 2, 3, 4, 5].map(function(v,i,a) { return v * v; });
/*
=!EXPECTSTART!=
[1, 2, 3, 4, 5].map(function(v,i,a) { return v * v; }) ==> [ 1, 4, 9, 16, 25 ]
=!EXPECTEND!=
*/ |
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
| #Vedit_macro_language | Vedit macro language | BOF // Copy all data to a new buffer
Reg_Copy(10, ALL)
Buf_Switch(Buf_Free)
Reg_Ins(10)
Sort(0, File_Size) // Sort the data
BOF
repeat(ALL) { // Count & delete duplicate lines
#1 = 1
while(Match("^{.*}\N\1$", REGEXP)==0) {
Del_Line(1)
#1++
}
Num_Ins(#1, NOCR) // Insert item count at the beginning of line
Ins_Char(9) // TAB
Line(1, ERRBREAK) // Next (different) line
}
Sort(0, File_Size, REVERSE) // Sort according to the count
BOF // Display the results
Reg_Copy_Block(10, CP, EOL_pos)
Buf_Quit(OK)
Statline_Message(@10) |
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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | keys=DownValues[#,Sort->False][[All,1,1,1]]&;
hashes=#/@keys[#]&;
a[2]="string";a["sometext"]=23;
keys[a]
->{2,sometext}
hashes[a]
->{string,23} |
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
| #MATLAB_.2F_Octave | MATLAB / Octave | keys = fieldnames(hash);
for k=1:length(keys),
key = keys{k};
value = getfield(hash,key); % get value of key
hash = setfield(hash,key,-value); % set value of key
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
| #Logo | Logo | to average :l
if empty? :l [output 0]
output quotient apply "sum :l count :l
end
print average [1 2 3 4] ; 2.5 |
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
| #Logtalk | Logtalk |
:- object(averages).
:- public(arithmetic/2).
% fails for empty vectors
arithmetic([X| Xs], Mean) :-
sum_and_count([X| Xs], 0, Sum, 0, Count),
Mean is Sum / Count.
% use accumulators to make the predicate tail-recursive
sum_and_count([], Sum, Sum, Count, Count).
sum_and_count([X| Xs], Sum0, Sum, Count0, Count) :-
Sum1 is Sum0 + X,
Count1 is Count0 + 1,
sum_and_count(Xs, Sum1, Sum, Count1, Count).
:- end_object.
|
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
| #Phixmonti | Phixmonti | include ..\Utilitys.pmt
def median /# l -- n #/
sort len 2 / >ps
tps .5 + int 2 slice nip
ps> dup int != if
1 get nip
else
sum 2 /
endif
enddef
( 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 ) median ? |
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
| #PHP | PHP |
function median($arr)
{
sort($arr);
$count = count($arr); //count the number of values in array
$middleval = floor(($count-1)/2); // find the middle value, or the lowest middle value
if ($count % 2) { // odd number, middle is the median
$median = $arr[$middleval];
} else { // even number, calculate avg of 2 medians
$low = $arr[$middleval];
$high = $arr[$middleval+1];
$median = (($low+$high)/2);
}
return $median;
}
echo median(array(4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2)) . "\n"; // 4.4
echo median(array(4.1, 7.2, 1.7, 9.3, 4.4, 3.2)) . "\n"; // 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
| #PicoLisp | PicoLisp | (load "@lib/math.l")
(let (Lst (1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0) Len (length Lst))
(prinl "Arithmetic mean: "
(format
(/ (apply + Lst) Len)
*Scl ) )
(prinl "Geometric mean: "
(format
(pow (*/ (apply * Lst) (** 1.0 (dec Len))) (/ 1.0 Len))
*Scl ) )
(prinl "Harmonic mean: "
(format
(*/ (* 1.0 Len) 1.0 (sum '((N) (*/ 1.0 1.0 N)) Lst))
*Scl ) ) ) |
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
| #L.2B.2B | L++ | (include "string")
(defn bool balanced (std::string s)
(def bal 0)
(foreach c s
(if (== c #\[) (++ bal)
(if (== c #\]) (-- bal)))
(if (< bal 0) (return false)))
(return (== bal 0)))
(main
(decl std::string (at tests) |{"", "[]", "[][]", "[[][]]", "][", "][][", "[]][[]"}|)
(pr std::boolalpha)
(foreach x tests
(prn x "\t" (balanced x)))) |
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.
| #Yabasic | Yabasic | a = open("passwd", "a") // Open the file for appending, i.e. what you write to the file will be appended after its initial contents.
// If the file does not exist, it will be created.
print #a "account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell"
print #a "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash"
print #a "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash"
close #a
a = open("passwd", "a")
if not a error "Could not open 'passwd' for appending"
print #a "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash"
close #a
if (not open(a,"passwd")) error "Could not open 'passwd' for reading"
dim nameField$(1), contentField$(1)
line input #a a$
n = token(a$, nameField$(), ":,")
for i = 1 to n
if nameField$(i) = "account" field1 = i
if nameField$(i) = "homephone" field2 = i
next
print upper$(nameField$(field1)), "\t", upper$(nameField$(field2))
print
while(not eof(#a))
line input #a a$
n = token(a$, contentField$(), ":,")
print contentField$(field1), "\t", contentField$(field2)
wend
close #a |
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.
| #zkl | zkl | var [const]
gnames=T("fullname","office","extension","homephone","email"),
pnames=T("account","password","uid","gid","gecos","directory","shell");
class Gecos{
var fullname, office, extension, homephone, email;
fcn init(str){ gnames.zipWith(setVar,vm.arglist) }
fcn toString { gnames.apply(setVar).concat(",") }
}
class Passwd{
var account,password,uid,gid,gecos,directory,shell;
fcn init(str){ pnames.zipWith(setVar,vm.arglist) }
fcn toString { pnames.apply(setVar).concat(":") }
} |
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
| #EchoLisp | EchoLisp |
(lib 'hash) ;; needs hash.lib
(define H (make-hash)) ;; new hash table
;; keys may be symbols, numbers, strings ..
;; values may be any lisp object
(hash-set H 'simon 'antoniette)
→ antoniette
(hash-set H 'antoinette 'albert)
→ albert
(hash-set H "Elvis" 42)
→ 42
(hash-ref H 'Elvis)
→ #f ;; not found. Elvis is not "Elvis"
(hash-ref H "Elvis")
→ 42
(hash-ref H 'simon)
→ antoniette
(hash-count H)
→ 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
| #Raku | Raku | sub propdiv (\x) {
my @l = 1 if x > 1;
(2 .. x.sqrt.floor).map: -> \d {
unless x % d { @l.push: d; my \y = x div d; @l.push: y if y != d }
}
@l
}
my $last = 0;
my @anti-primes = lazy 1, |(|(2..59), 60, *+60 … *).grep: -> $c {
my \mx = +propdiv($c);
next if mx <= $last;
$last = mx;
$c
}
my $upto = 5e5;
put "First 20 anti-primes:\n{ @anti-primes[^20] }";
put "\nCount of anti-primes <= $upto: {+@anti-primes[^(@anti-primes.first: * > $upto, :k)]}"; |
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
| #Red | Red | Red []
inc: func ['v] [set v 1 + get v] ;; shortcut function for n: n + 1
n: 0 found: 0 max_div: 0
print "the first 20 anti-primes are:"
while [ inc n] [
nDiv: 1 ;; count n / n extra
if n > 1 [ repeat div n / 2 [ if n % div = 0 [inc nDiv] ] ]
if nDiv > max_div [
max_div: nDiv
prin [n ""]
if 20 <= inc found [halt]
]
]
|
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.
| #Julia | Julia | numbers = [1, 3, 5, 7]
@show [n ^ 2 for n in numbers] # list comprehension
square(x) = x ^ 2; @show map(square, numbers) # functional form
@show map(x -> x ^ 2, numbers) # functional form with anonymous function
@show [n * n for n in numbers] # no need for a function,
@show numbers .* numbers # element-wise operation
@show numbers .^ 2 # includes .+, .-, ./, comparison, and bitwise operations as well |
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.
| #Kotlin | Kotlin | fun main(args: Array<String>) {
val array = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) // build
val function = { i: Int -> i * i } // function to apply
val list = array.map { function(it) } // process each item
println(list) // print results
} |
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
| #Vlang | Vlang | fn main() {
println(mode([2, 7, 1, 8, 2]))
println(mode([2, 7, 1, 8, 2, 8]))
}
fn mode(a []int) []int {
mut m := map[int]int{}
for v in a {
m[v]++
}
mut mode := []int{}
mut n := 0
for k, v in m {
match true {
v > n {
n = v
mode = [k]
}
v<n{}
else {
mode << k
}
}
}
return mode
} |
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
| #Wren | Wren | class Arithmetic {
static mode(arr) {
var map = {}
for (e in arr) {
if (map[e] == null) map[e] = 0
map[e] = map[e] + 1
}
var max = map.values.reduce {|x, y| x > y ? x : y}
return map.keys.where {|x| map[x] == max}.toList
}
}
System.print(Arithmetic.mode([1,2,3,4,5,5,51,2,3])) |
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
| #Maxima | Maxima | h[1]: 6$
h[9]: 2$
/* iterate over values */
for val in listarray(h) do (
print(val))$
/* iterate over the keys */
for key in rest(arrayinfo(h), 2) do (
val: arrayapply(h, key),
print(key, val))$ |
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
| #MiniScript | MiniScript | d = { 3: "test", "foo": 3 }
for keyVal in d
print keyVal // produces results like: { "key": 3, "value": "test" }
end for
for key in d.indexes
print key
end for
for val in d.values
print val
end for |
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
| #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/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
| #Lua | Lua | function mean (numlist)
if type(numlist) ~= 'table' then return numlist end
num = 0
table.foreach(numlist,function(i,v) num=num+v end)
return num / #numlist
end
print (mean({3,1,4,1,5,9})) |
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
| #Picat | Picat | go =>
Lists = [
[1.121,10.3223,3.41,12.1,0.01],
1..10,
1..11,
[3],
[3,4],
[],
[4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2],
[4.1, 7.2, 1.7, 9.3, 4.4, 3.2],
[5.1, 2.6, 6.2, 8.8, 4.6, 4.1],
[5.1, 2.6, 8.8, 4.6, 4.1]],
foreach(List in Lists)
println([List, median=median(List)])
end,
nl.
median([]) = undef.
median([X]) = X.
median(L) = cond(Len mod 2 == 1, LL[H+1], avg([LL[H],LL[H+1]])) =>
Len = L.length,
H = Len // 2,
LL = sort(L). |
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
| #PicoLisp | PicoLisp | (de median (Lst)
(let N (length Lst)
(if (bit? 1 N)
(get (sort Lst) (/ (inc N) 2))
(setq Lst (nth (sort Lst) (/ N 2)))
(/ (+ (car Lst) (cadr Lst)) 2) ) ) )
(scl 2)
(prinl (round (median (1.0 2.0 3.0))))
(prinl (round (median (1.0 2.0 3.0 4.0))))
(prinl (round (median (5.1 2.6 6.2 8.8 4.6 4.1))))
(prinl (round (median (5.1 2.6 8.8 4.6 4.1)))) |
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
| #PL.2FI | PL/I |
declare n fixed binary,
(Average, Geometric, Harmonic) float;
declare A(10) float static initial (1,2,3,4,5,6,7,8,9,10);
n = hbound(A,1);
/* compute the average */
Average = sum(A)/n;
/* Compute the geometric mean: */
Geometric = prod(A)**(1/n);
/* Compute the Harmonic mean: */
Harmonic = n / sum(1/A);
put skip data (Average);
put skip data (Geometric);
put skip data (Harmonic);
if Average < Geometric then put skip list ('Error');
if Geometric < Harmonic then put skip list ('Error');
|
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
| #PostScript | PostScript |
/pythamean{
/x exch def
/sum 0 def
/prod 1 def
/invsum 0 def
/i 1 def
x{
/sum sum i add def
/prod prod i mul def
/invsum invsum i -1 exp add def
/i i 1 add def
}repeat
(Arithmetic Mean : ) print
sum x div =
(Geometric Mean : ) print
prod x -1 exp exp =
(Harmonic Mean : ) print
x invsum div =
}def
10 pythamean
|
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
| #Lasso | Lasso | define randomparens(num::integer,open::string='[',close::string=']') => {
local(out) = array
with i in 1 to #num do {
#out->insert(']', integer_random(1,#out->size || 1))
#out->insert('[', integer_random(1,#out->size || 1))
}
return #out->join
}
define validateparens(input::string,open::string='[',close::string=']') => {
local(i) = 0
#input->foreachcharacter => {
#1 == #open ? #i++
#1 == #close && --#i < 0 ? return false
}
return #i == 0 ? true | false
}
with i in 1 to 10
let input = randomparens(#i)
select #input + ' = ' + validateparens(#input) |
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
| #Elena | Elena | import system'collections;
public program()
{
// 1. Create
var map := Dictionary.new();
map["key"] := "foox";
map["key"] := "foo";
map["key2"]:= "foo2";
map["key3"]:= "foo3";
map["key4"]:= "foo4";
} |
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
| #Elixir | Elixir | defmodule RC do
def test_create do
IO.puts "< create Map.new >"
m = Map.new #=> creates an empty Map
m1 = Map.put(m,:foo,1)
m2 = Map.put(m1,:bar,2)
print_vals(m2)
print_vals(%{m2 | foo: 3})
end
defp print_vals(m) do
IO.inspect m
Enum.each(m, fn {k,v} -> IO.puts "#{inspect k} => #{v}" end)
end
end
RC.test_create |
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
| #REXX | REXX | /*REXX program finds and displays N number of anti─primes or highly─composite numbers.*/
parse arg N . /*obtain optional argument from the CL.*/
if N=='' | N=="," then N= 20 /*Not specified? Then use the default.*/
maxD= 0 /*the maximum number of divisors so far*/
say '─index─ ──anti─prime──' /*display a title for the numbers shown*/
#= 0 /*the count of anti─primes found " " */
do once=1 for 1
do i=1 for 59 /*step through possible numbers by twos*/
d= #divs(i); if d<=maxD then iterate /*get # divisors; Is too small? Skip.*/
#= # + 1; maxD= d /*found an anti─prime #; set new minD.*/
say center(#, 7) right(i, 10) /*display the index and the anti─prime.*/
if #>=N then leave once /*if we have enough anti─primes, done. */
end /*i*/
do j=60 by 20 /*step through possible numbers by 20. */
d= #divs(j); if d<=maxD then iterate /*get # divisors; Is too small? Skip.*/
#= # + 1; maxD= d /*found an anti─prime #; set new minD.*/
say center(#, 7) right(j, 10) /*display the index and the anti─prime.*/
if #>=N then leave /*if we have enough anti─primes, done. */
end /*j*/
end /*once*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
#divs: procedure; parse arg x 1 y /*X and Y: both set from 1st argument.*/
if x<3 then return x /*handle special cases for one and two.*/
if x==4 then return 3 /* " " " " four. */
if x<6 then return 2 /* " " " " three or five*/
odd= x // 2 /*check if X is odd or not. */
if odd then #= 1 /*Odd? Assume Pdivisors count of 1.*/
else do; #= 3; y= x % 2 /*Even? " " " " 3.*/
end /* [↑] start with known num of Pdivs.*/
do k=3 for x%2-3 by 1+odd while k<y /*for odd numbers, skip evens.*/
if x//k==0 then do; #= # + 2 /*if no remainder, then found a divisor*/
y= x % k /*bump # Pdivs, calculate limit Y. */
if k>=y then do; #= # - 1; leave; end /*limit?*/
end /* ___ */
else if k*k>x then leave /*only divide up to √ x */
end /*k*/ /* [↑] this form of DO loop is faster.*/
return #+1 /*bump "proper divisors" to "divisors".*/ |
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.
| #Klingphix | Klingphix | include ..\Utilitys.tlhy
( 1 2 3 4 ) [dup *] map
pstack
" " input |
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.
| #Lambdatalk | Lambdatalk |
{A.map {lambda {:x} {* :x :x}} {A.new 1 2 3 4 5 6 7 8 9 10}}
-> [1,4,9,16,25,36,49,64,81,100]
|
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
| #XEmacs_Lisp | XEmacs Lisp | (defun mode ( predicate &rest values)
"Finds the mode of all values passed in.
Uses `predicate' to compare items."
(let ((modes nil) ; Declare local variables
(mode-count 0)
(value-list nil)
current-value)
(loop for value in values do
(if (setq current-value (assoc* value value-list :test predicate)) ; Construct a linked list of cons cells, (value . count)
(incf (cdr current-value))
(push (cons value 1) value-list)))
(loop for (value . count) in value-list do ; Find modes in linked list
(if (> count mode-count)
(setq modes (list value)
mode-count count)
(when (eq count mode-count)
(push value modes))))
modes)) |
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
| #Yabasic | Yabasic | sub floor(x)
return int(x + .05)
end sub
SUB ASort$(matriz$())
local last, gap, first, tempi$, tempj$, i, j
last = arraysize(matriz$(), 1)
gap = floor(last / 10) + 1
while(TRUE)
first = gap + 1
for i = first to last
tempi$ = matriz$(i)
j = i - gap
while(TRUE)
tempj$ = matriz$(j)
if (tempi$ >= tempj$) then
j = j + gap
break
end if
matriz$(j+gap) = tempj$
if j <= gap then
break
end if
j = j - gap
wend
matriz$(j) = tempi$
next i
if gap = 1 then
return
else
gap = floor(gap / 3.5) + 1
end if
wend
END SUB
sub getMode$(list$) // returns mode and count
local m$(1), n, i, mode$, count, maxM$, maxC
n = token(list$, m$(), ", ")
ASort$(m$())
for i = 1 to n
if m$(i) <> mode$ then
if count > maxC then
maxM$ = mode$
maxC = count
end if
count = 1
mode$ = m$(i)
else
count = count + 1
end if
next i
return maxM$ + "," + str$(maxC)
end sub
result$ = getMode$("1,3,6,6,6,6,7,7,12,12,17")
n = instr(result$, ",")
print "mode ", left$(result$, n - 1), " occur(s) ", right$(result$, len(result$) - n), " times."
result$ = getMode$("a, a, b, d, d")
print "mode ", left$(result$, n - 1), " occur(s) ", right$(result$, len(result$) - n), " times." |
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
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols
surname = 'Unknown' -- default value
surname['Fred'] = 'Bloggs'
surname['Davy'] = 'Jones'
try = 'Fred'
say surname[try] surname['Bert']
-- extract the keys
loop fn over surname
say fn.right(10) ':' surname[fn]
end fn |
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
| #NewLISP | NewLISP | ;; using an association list:
(setq alist '(("A" "a") ("B" "b") ("C" "c")))
;; list keys
(map first alist)
;; list values
(map last alist)
;; loop over the assocation list:
(dolist (elem alist)
(println (format "%s -> %s" (first elem) (last elem)))) |
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
| #Lucid | Lucid | avg(x)
where
sum = first(x) fby sum + next(x);
n = 1 fby n + 1;
avg = sum / n;
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
| #M4 | M4 | define(`extractdec', `ifelse(eval(`$1%100 < 10'),1,`0',`')eval($1%100)')dnl
define(`fmean', `eval(`($2/$1)/100').extractdec(eval(`$2/$1'))')dnl
define(`mean', `rmean(`$#', $@)')dnl
define(`rmean', `ifelse(`$3', `', `fmean($1,$2)',dnl
`rmean($1, eval($2+$3), shift(shift(shift($@))))')')dnl |
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
| #PL.2FI | PL/I | call sort(A);
n = dimension(A,1);
if iand(n,1) = 1 then /* an odd number of elements */
median = A(n/2);
else /* an even number of elements */
median = (a(n/2) + a(trunc(n/2)+1) )/2; |
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
| #PowerShell | PowerShell |
function Measure-Data
{
[CmdletBinding()]
[OutputType([PSCustomObject])]
Param
(
[Parameter(Mandatory=$true,
Position=0)]
[double[]]
$Data
)
Begin
{
function Get-Mode ([double[]]$Data)
{
if ($Data.Count -gt ($Data | Select-Object -Unique).Count)
{
$groups = $Data | Group-Object | Sort-Object -Property Count -Descending
return ($groups | Where-Object {[double]$_.Count -eq [double]$groups[0].Count}).Name | ForEach-Object {[double]$_}
}
else
{
return $null
}
}
function Get-StandardDeviation ([double[]]$Data)
{
$variance = 0
$average = $Data | Measure-Object -Average | Select-Object -Property Count, Average
foreach ($number in $Data)
{
$variance += [Math]::Pow(($number - $average.Average),2)
}
return [Math]::Sqrt($variance / ($average.Count-1))
}
function Get-Median ([double[]]$Data)
{
if ($Data.Count % 2)
{
return $Data[[Math]::Floor($Data.Count/2)]
}
else
{
return ($Data[$Data.Count/2], $Data[$Data.Count/2-1] | Measure-Object -Average).Average
}
}
}
Process
{
$Data = $Data | Sort-Object
$Data | Measure-Object -Maximum -Minimum -Sum -Average |
Select-Object -Property Count,
Sum,
Minimum,
Maximum,
@{Name='Range'; Expression={$_.Maximum - $_.Minimum}},
@{Name='Mean' ; Expression={$_.Average}} |
Add-Member -MemberType NoteProperty -Name Median -Value (Get-Median $Data) -PassThru |
Add-Member -MemberType NoteProperty -Name StandardDeviation -Value (Get-StandardDeviation $Data) -PassThru |
Add-Member -MemberType NoteProperty -Name Mode -Value (Get-Mode $Data) -PassThru
}
}
|
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
| #PowerShell | PowerShell | $A = 0
$LogG = 0
$InvH = 0
$ii = 1..10
foreach($i in $ii) {
# Arithmetic mean is computed directly
$A += $i / $ii.Count
# Geometric mean is computed using Logarithms
$LogG += [Math]::Log($i) / $ii.Count
# Harmonic mean is computed using its inverse
$InvH += 1 / ($i * $ii.Count)
}
$G = [Math]::Exp($LogG)
$H = 1/$InvH
write-host "Arithmetic mean: A = $A"
write-host "Geometric mean: G = $G"
write-host "Harmonic mean: H = $H"
write-host "Is A >= G ? $($A -ge $G)"
write-host "Is G >= H ? $($G -ge $H)" |
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
| #Liberty_BASIC | Liberty BASIC |
print "Supplied examples"
for i =1 to 7
read test$
print "The string '"; test$; "' is "; validString$( test$)
next i
print
data "", "[]", "][","[][]","][][","[[][]]","[]][[]"
print "Random generated examples"
for example =1 to 10
test$ =generate$( int( 1 +10 *rnd(1)))
print "The string '"; test$; "' is "; validString$( test$)
next example
end
function validString$( in$)
if left$( in$, 1) <>"[" and len( test$) <>0 then
validString$ ="not OK. Opens wrongly."
exit function
end if
paired =0
for i =1 to len( in$)
c$ =mid$( in$, i, 1)
if c$ ="[" then paired =paired +1
if c$ ="]" then paired =paired -1
if paired <0 then
exit for
end if
next i
if ( lBr =rBr) and ( paired >=0) then validString$ ="OK." else validString$ ="not OK. Unbalanced."
end function
function generate$( N)
lBr =0
rBr =0
' choose at random until N of one type generated
while ( lBr <N) and ( rBr <N)
select case int( 1.5 +rnd( 1))
case 1
lBr =lBr +1
generate$ =generate$ +"["
case 2
rBr =rBr +1
generate$ =generate$ +"]"
end select
wend
' now pad with the remaining other brackets
if lBr =N then
generate$ =generate$ +string$( N -rBr, "]")
else
generate$ =generate$ +string$( N -lBr, "[")
end if
end function
function string$( n, c$)
for i =1 to n
op$ =op$ +c$
next i
string$ =op$
end function
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
| #Emacs_Lisp | Emacs Lisp | (setq my-table (make-hash-table))
(puthash 'key 'value my-table) |
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
| #Ring | Ring |
# Project : Anti-primes
see "working..." + nl
see "wait for done..." + nl + nl
see "the first 20 anti-primes are:" + nl + nl
maxDivisor = 0
num = 0
n = 0
result = list(20)
while num < 20
n = n + 1
div = factors(n)
if (div > maxDivisor)
maxDivisor = div
num = num + 1
result[num] = n
ok
end
see "["
for n = 1 to len(result)
if n < len(result)
see string(result[n]) + ","
else
see string(result[n]) + "]" + nl + nl
ok
next
see "done..." + nl
func factors(an)
ansum = 2
if an < 2
return(1)
ok
for nr = 2 to an/2
if an%nr = 0
ansum = ansum+1
ok
next
return ansum
|
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
| #Ruby | Ruby | require 'prime'
def num_divisors(n)
n.prime_division.inject(1){|prod, (_p,n)| prod *= (n + 1) }
end
anti_primes = Enumerator.new do |y| # y is the yielder
max = 0
y << 1 # yield 1
2.step(nil,2) do |candidate| # nil is taken as Infinity
num = num_divisors(candidate)
if num > max
y << candidate # yield the candidate
max = num
end
end
end
puts anti_primes.take(20).join(" ")
|
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.
| #Lang5 | Lang5 | : square(*) dup * ;
[1 2 3 4 5] square . "\n" .
[1 2 3 4 5] 'square apply . "\n" . |
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.
| #langur | langur | writeln map f{^2}, 1..10 |
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
| #zkl | zkl | fcn mode(items){
d:=Dictionary(); foreach i in (items){ d.incV(i) }
m:=d.reduce(fcn(m,[(_,v)]){ v.max(m) },0);
d.filter('wrap([(_,v)]){ v==m }).apply("get",0);
} |
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
| #Nim | Nim |
import tables
var t: Table[int,string]
t[1] = "one"
t[2] = "two"
t[3] = "three"
t[4] = "four"
echo "t has " & $t.len & " elements"
echo "has t key 4? " & $t.hasKey(4)
echo "has t key 5? " & $t.hasKey(5)
#iterate keys
echo "key iteration:"
for k in t.keys:
echo "at[" & $k & "]=" & t[k]
#iterate pairs
echo "pair iteration:"
for k,v in t.pairs:
echo "at[" & $k & "]=" & v
|
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
| #Oberon-2 | Oberon-2 |
MODULE AssociativeArray;
IMPORT
ADT:Dictionary,
Object:Boxed,
Out;
TYPE
Key = STRING;
Value = Boxed.LongInt;
VAR
assocArray: Dictionary.Dictionary(Key,Value);
iterK: Dictionary.IterKeys(Key,Value);
iterV: Dictionary.IterValues(Key,Value);
aux: Value;
k: Key;
BEGIN
assocArray := NEW(Dictionary.Dictionary(Key,Value));
assocArray.Set("ten",NEW(Value,10));
assocArray.Set("eleven",NEW(Value,11));
aux := assocArray.Get("ten");
Out.LongInt(aux.value,0);Out.Ln;
aux := assocArray.Get("eleven");
Out.LongInt(aux.value,0);Out.Ln;Out.Ln;
(* Iterate keys *)
iterK := assocArray.IterKeys();
WHILE (iterK.Next(k)) DO
Out.Object(k);Out.Ln
END;
Out.Ln;
(* Iterate values *)
iterV := assocArray.IterValues();
WHILE (iterV.Next(aux)) DO
Out.LongInt(aux.value,0);Out.Ln
END
END AssociativeArray.
|
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
| #Maple | Maple |
mean := proc( a :: indexable )
local i;
Normalizer( add( i, i in a ) / numelems( a ) )
end proc:
|
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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | Unprotect[Mean];
Mean[{}] := 0 |
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
| #Processing | Processing | void setup() {
float[] numbers = {3.1, 4.1, 5.9, 2.6, 5.3, 5.8};
println(median(numbers));
numbers = shorten(numbers);
println(median(numbers));
}
float median(float[] nums) {
nums = sort(nums);
float median = (nums[(nums.length - 1) / 2] + nums[nums.length / 2]) / 2.0;
return median;
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.