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/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
| #Gambas | Gambas | // declare a nil map variable, for maps from string to int
var x map[string]int
// make an empty map
x = make(map[string]int)
// make an empty map with an initial capacity
x = make(map[string]int, 42)
// set a value
x["foo"] = 3
// getting values
y1 := x["bar"] // zero value returned if no map entry exists for the key
y2, ok := x["bar"] // ok is a boolean, true if key exists in the map
// removing keys
delete(x, "foo")
// make a map with a literal
x = map[string]int{
"foo": 2, "bar": 42, "baz": -1,
} |
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
| #zkl | zkl | fcn properDivsN(n) //--> count of proper divisors. 1-->1, wrong but OK here
{ [1.. (n + 1)/2 + 1].reduce('wrap(p,i){ p + (n%i==0 and n!=i) }) }
fcn antiPrimes{ // -->iterator
Walker.chain([2..59],[60..*,30]).tweak(fcn(c,rlast){
last,mx := rlast.value, properDivsN(c);
if(mx<=last) return(Void.Skip);
rlast.set(mx);
c
}.fp1(Ref(0))).push(1); // 1 has no proper 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.
| #NetLogo | NetLogo |
;; NetLogo “anonymous procedures”
;; stored in a variable, just to show it can be done.
let callback [ [ x ] x * x ]
show (map callback [ 1 2 3 4 5 ])
|
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.
| #NewLISP | NewLISP | > (map (fn (x) (* x x)) '(1 2 3 4))
(1 4 9 16)
|
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
| #PostScript | PostScript |
% over keys and values
<</a 1 /b 2 /c 3>> {= =} forall
% just keys
<</a 1 /b 2 /c 3>> {= } forall
% just values
<</a 1 /b 2 /c 3>> {pop =} forall
|
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
| #Potion | Potion | mydictionary = (red=0xff0000, green=0x00ff00, blue=0x0000ff)
mydictionary each (key, val): (key, ":", val, "\n") join print.
mydictionary each (key): (key, "\n") join print. |
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
| #Nim | Nim | import strutils
proc mean(xs: openArray[float]): float =
for x in xs:
result += x
result = result / float(xs.len)
var v = @[1.0, 2.0, 2.718, 3.0, 3.142]
for i in 0..5:
echo "mean of first ", v.len, " = ", formatFloat(mean(v), precision = 0)
if v.len > 0: v.setLen(v.high) |
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
| #Niue | Niue |
[ [ , len 1 - at ! ] len 3 - times swap , ] 'map ; ( a Lisp like map, to sum the stack )
[ len 'n ; [ + ] 0 n swap-at map n / ] 'avg ;
1 2 3 4 5 avg .
=> 3
3.4 2.3 .01 2.0 2.1 avg .
=> 1.9619999999999997
|
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
| #Scheme | Scheme | (define (median l)
(* (+ (list-ref (bubble-sort l >) (round (/ (- (length l) 1) 2)))
(list-ref (bubble-sort l >) (round (/ (length l) 2)))) 0.5)) |
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
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
const type: floatList is array float;
const func float: median (in floatList: floats) is func
result
var float: median is 0.0;
local
var floatList: sortedFloats is 0 times 0.0;
begin
sortedFloats := sort(floats);
if odd(length(sortedFloats)) then
median := sortedFloats[succ(length(sortedFloats)) div 2];
else
median := 0.5 * (sortedFloats[length(sortedFloats) div 2] +
sortedFloats[succ(length(sortedFloats) div 2)]);
end if;
end func;
const proc: main is func
local
const floatList: flist1 is [] (5.1, 2.6, 6.2, 8.8, 4.6, 4.1);
const floatList: flist2 is [] (5.1, 2.6, 8.8, 4.6, 4.1);
begin
writeln("flist1 median is " <& median(flist1) digits 2 lpad 7); # 4.85
writeln("flist2 median is " <& median(flist2) digits 2 lpad 7); # 4.60
end func; |
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
| #Run_BASIC | Run BASIC | bXsum = 1
for i = 1 to 10
sum = sum + i ' sum of 1 -> 10
bXsum = bXsum * i ' sum i * i
sum1i = sum1i + (1/i) ' sum 1/i
next
average = sum / 10
geometric = bXsum ^ (1/10)
harmonic = 10/sum1i
print "ArithmeticMean:";average
print "Geometric Mean:";geometric
print " Harmonic Mean:";harmonic
if (average >= geometric) and (geometric >= harmonic) then print "True" else print "False" |
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
| #Nim | Nim |
from random import random, randomize, shuffle
from strutils import repeat
randomize()
proc gen(n: int): string =
result = "[]".repeat(n)
shuffle(result)
proc balanced(txt: string): bool =
var b = 0
for c in txt:
case c
of '[':
inc(b)
of ']':
dec(b)
if b < 0: return false
else: discard
b == 0
for n in 0..9:
let s = gen(n)
echo "'", s, "' is ", (if balanced(s): "balanced" else: "not balanced") |
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
| #Go | Go | // declare a nil map variable, for maps from string to int
var x map[string]int
// make an empty map
x = make(map[string]int)
// make an empty map with an initial capacity
x = make(map[string]int, 42)
// set a value
x["foo"] = 3
// getting values
y1 := x["bar"] // zero value returned if no map entry exists for the key
y2, ok := x["bar"] // ok is a boolean, true if key exists in the map
// removing keys
delete(x, "foo")
// make a map with a literal
x = map[string]int{
"foo": 2, "bar": 42, "baz": -1,
} |
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.
| #NGS | NGS | {
[1, 2, 3, 4, 5].map(F(x) x*x)
} |
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.
| #Nial | Nial | each (* [first, first] ) 1 2 3 4
=1 4 9 16 |
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
| #PowerShell | PowerShell | $h = @{ 'a' = 1; 'b' = 2; 'c' = 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
| #Prolog | Prolog |
assert( mymap(key1,value1) ).
assert( mymap(key2,value1) ).
|
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
| #Oberon-2 | Oberon-2 |
MODULE AvgMean;
IMPORT Out;
CONST MAXSIZE = 10;
PROCEDURE Avg(a: ARRAY OF REAL; items: INTEGER): REAL;
VAR
i: INTEGER;
total: REAL;
BEGIN
total := 0.0;
FOR i := 0 TO LEN(a) - 1 DO
total := total + a[i]
END;
RETURN total/LEN(a)
END Avg;
VAR
ary: ARRAY MAXSIZE OF REAL;
BEGIN
ary[0] := 10.0;
ary[1] := 11.01;
ary[2] := 12.02;
ary[3] := 13.03;
ary[4] := 14.04;
ary[5] := 15.05;
ary[6] := 16.06;
ary[7] := 17.07;
ary[8] := 18.08;
ary[9] := 19.09;
Out.Fixed(Avg(ary),4,2);Out.Ln
END AvgMean.
|
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
| #SenseTalk | SenseTalk | put the median of [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2]
put the median of [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2, 6.6]
put customMedian of [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2]
put customMedian of [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2, 6.6]
to handle customMedian of list
sort list
if the number of items in list is an even number then
set lowMid to the number of items in list divided by 2
return (item lowMid of list + item lowMid+1 of list) / 2
else
return the middle item of list
end if
end customMedian |
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
| #Sidef | Sidef | func median(arry) {
var srtd = arry.sort;
var alen = srtd.length;
srtd[(alen-1)/2]+srtd[alen/2] / 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
| #Rust | Rust | fn main() {
let mut sum = 0.0;
let mut prod = 1;
let mut recsum = 0.0;
for i in 1..11{
sum += i as f32;
prod *= i;
recsum += 1.0/(i as f32);
}
let avg = sum/10.0;
let gmean = (prod as f32).powf(0.1);
let hmean = 10.0/recsum;
println!("Average: {}, Geometric mean: {}, Harmonic mean: {}", avg, gmean, hmean);
assert!( ( (avg >= gmean) && (gmean >= hmean) ), "Incorrect calculation");
}
|
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
| #Scala | Scala | def arithmeticMean(n: Seq[Int]) = n.sum / n.size.toDouble
def geometricMean(n: Seq[Int]) = math.pow(n.foldLeft(1.0)(_*_), 1.0 / n.size.toDouble)
def harmonicMean(n: Seq[Int]) = n.size / n.map(1.0 / _).sum
var nums = 1 to 10
var a = arithmeticMean(nums)
var g = geometricMean(nums)
var h = harmonicMean(nums)
println("Arithmetic mean " + a)
println("Geometric mean " + g)
println("Harmonic mean " + h)
assert(a >= g && 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
| #Oberon-2 | Oberon-2 |
MODULE BalancedBrackets;
IMPORT
Object,
Object:Boxed,
ADT:LinkedList,
ADT:Storable,
IO,
Out := NPCT:Console;
TYPE
(* CHAR is not boxed in the standard lib *)
(* so make a boxed char *)
Character* = POINTER TO CharacterDesc;
CharacterDesc* = RECORD
(Boxed.ObjectDesc)
c: CHAR;
END;
(* Method for a boxed char *)
PROCEDURE (c: Character) INIT*(x: CHAR);
BEGIN
c.c := x;
END INIT;
PROCEDURE NewCharacter*(c: CHAR): Character;
VAR
x: Character;
BEGIN
NEW(x);x.INIT(c);RETURN x
END NewCharacter;
PROCEDURE (c: Character) ToString*(): STRING;
BEGIN
RETURN Object.NewLatin1Char(c.c);
END ToString;
PROCEDURE (c: Character) Load*(r: Storable.Reader) RAISES IO.Error;
BEGIN
r.ReadChar(c.c);
END Load;
PROCEDURE (c: Character) Store*(w: Storable.Writer) RAISES IO.Error;
BEGIN
w.WriteChar(c.c);
END Store;
PROCEDURE (c: Character) Cmp*(o: Object.Object): LONGINT;
BEGIN
IF c.c < o(Character).c THEN RETURN -1
ELSIF c.c = o(Character).c THEN RETURN 0
ELSE RETURN 1
END
END Cmp;
(* end of methods for a boxed char *)
PROCEDURE CheckBalance(str: STRING): BOOLEAN;
VAR
s: LinkedList.LinkedList(Character);
chars: Object.CharsLatin1;
n, x: Boxed.Object;
i,len: LONGINT;
BEGIN
i := 0;
chars := str(Object.String8).CharsLatin1();
len := str.length;
s := NEW(LinkedList.LinkedList(Character));
WHILE (i < len) & (chars[i] # 0X) DO
IF s.IsEmpty() THEN
s.Append(NewCharacter(chars[i])) (* Push character *)
ELSE
n := s.GetLast(); (* top character *)
WITH
n: Character DO
IF (chars[i] = ']') & (n.c = '[') THEN
x := s.RemoveLast(); (* Pop character *)
x := NIL
ELSE
s.Append(NewCharacter(chars[i]))
END
ELSE RETURN FALSE
END (* WITH *)
END;
INC(i)
END;
RETURN s.IsEmpty()
END CheckBalance;
PROCEDURE Do;
VAR
str: STRING;
BEGIN
str := "[]";Out.String(str + ":> "); Out.Bool(CheckBalance(str));Out.Ln;
str := "[][]";Out.String(str + ":> ");Out.Bool(CheckBalance(str));Out.Ln;
str := "[[][]]";Out.String(str + ":> ");Out.Bool(CheckBalance(str));Out.Ln;
str := "][";Out.String(str + ":> ");Out.Bool(CheckBalance(str));Out.Ln;
str := "][][";Out.String(str + ":> ");Out.Bool(CheckBalance(str));Out.Ln;
str := "[]][[]";Out.String(str + ":> ");Out.Bool(CheckBalance(str));Out.Ln;
END Do;
BEGIN
Do
END BalancedBrackets.
|
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
| #Gosu | Gosu | // empty map
var emptyMap = new HashMap<String, Integer>()
// map initialization
var map = {"Scott"->50, "Carson"->40, "Luca"->30, "Kyle"->38}
// map key/value assignment
map["Scott"] = 51
// get a value
var x = map["Scott"]
// remove an entry
map.remove("Scott")
// loop and maps
for(entry in map.entrySet()) {
print("Key: ${entry.Key}, Value: ${entry.Value}")
}
// functional iteration
map.eachKey(\ k ->print(map[k]))
map.eachValue(\ v ->print(v))
map.eachKeyAndValue(\ k, v -> print("Key: ${v}, Value: ${v}"))
var filtered = map.filterByValues(\ v ->v < 50)
// any object can be treated as an associative array
class Person {
var name: String
var age: int
}
// access properties on Person dynamically via associative array syntax
var scott = new Person()
scott["name"] = "Scott"
scott["age"] = 29 |
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.
| #Nim | Nim | var arr = @[1,2,3,4]
arr.apply proc(some: var int) = echo(some, " squared = ", some*some) |
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.
| #Oberon-2 | Oberon-2 |
MODULE ApplyCallBack;
IMPORT
Out := NPCT:Console;
TYPE
Fun = PROCEDURE (x: LONGINT): LONGINT;
Ptr2Ary = POINTER TO ARRAY OF LONGINT;
VAR
a: ARRAY 5 OF LONGINT;
x: ARRAY 3 OF LONGINT;
r: Ptr2Ary;
PROCEDURE Min(x,y: LONGINT): LONGINT;
BEGIN
IF x <= y THEN RETURN x ELSE RETURN y END;
END Min;
PROCEDURE Init(VAR a: ARRAY OF LONGINT);
BEGIN
a[0] := 0;
a[1] := 1;
a[2] := 2;
a[3] := 3;
a[4] := 4;
END Init;
PROCEDURE Fun1(x: LONGINT): LONGINT;
BEGIN
RETURN x * 2
END Fun1;
PROCEDURE Fun2(x: LONGINT): LONGINT;
BEGIN
RETURN x DIV 2;
END Fun2;
PROCEDURE Fun3(x: LONGINT): LONGINT;
BEGIN
RETURN x + 3;
END Fun3;
PROCEDURE Map(F: Fun; VAR x: ARRAY OF LONGINT);
VAR
i: LONGINT;
BEGIN
FOR i := 0 TO LEN(x) - 1 DO
x[i] := F(x[i])
END
END Map;
PROCEDURE Map2(F: Fun; a: ARRAY OF LONGINT; VAR r: ARRAY OF LONGINT);
VAR
i,l: LONGINT;
BEGIN
l := Min(LEN(a),LEN(x));
FOR i := 0 TO l - 1 DO
r[i] := F(a[i])
END
END Map2;
PROCEDURE Map3(F: Fun; a: ARRAY OF LONGINT): Ptr2Ary;
VAR
r: Ptr2Ary;
i: LONGINT;
BEGIN
NEW(r,LEN(a));
FOR i := 0 TO LEN(a) - 1 DO
r[i] := F(a[i]);
END;
RETURN r
END Map3;
PROCEDURE Show(a: ARRAY OF LONGINT);
VAR
i: LONGINT;
BEGIN
FOR i := 0 TO LEN(a) - 1 DO
Out.Int(a[i],4)
END;
Out.Ln
END Show;
BEGIN
Init(a);Map(Fun1,a);Show(a);
Init(a);Map2(Fun2,a,x);Show(x);
Init(a);r := Map3(Fun3,a);Show(r^);
END ApplyCallBack.
|
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
| #PureBasic | PureBasic | NewMap dict.s()
dict("de") = "German"
dict("en") = "English"
dict("fr") = "French"
ForEach dict()
Debug MapKey(dict()) + ":" + dict()
Next |
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
| #Python | Python | myDict = { "hello": 13,
"world": 31,
"!" : 71 }
# iterating over key-value pairs:
for key, value in myDict.items():
print ("key = %s, value = %s" % (key, value))
# iterating over keys:
for key in myDict:
print ("key = %s" % key)
# (is a shortcut for:)
for key in myDict.keys():
print ("key = %s" % key)
# iterating over values:
for value in myDict.values():
print ("value = %s" % value) |
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
| #Objeck | Objeck |
function : native : PrintAverage(values : FloatVector) ~ Nil {
values->Average()->PrintLine();
}
|
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
| #OCaml | OCaml | let mean_floats = function
| [] -> 0.
| xs -> List.fold_left (+.) 0. xs /. float_of_int (List.length xs)
let mean_ints xs = mean_floats (List.map float_of_int xs) |
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
| #Slate | Slate | s@(Sequence traits) median
[
s isEmpty
ifTrue: [Nil]
ifFalse:
[| sorted |
sorted: s sort.
sorted length `cache isEven
ifTrue: [(sorted middle + (sorted at: sorted indexMiddle - 1)) / 2]
ifFalse: [sorted middle]]
]. |
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
| #Smalltalk | Smalltalk | OrderedCollection extend [
median [
self size = 0
ifFalse: [ |s l|
l := self size.
s := self asSortedCollection.
(l rem: 2) = 0
ifTrue: [ ^ ((s at: (l//2 + 1)) + (s at: (l//2))) / 2 ]
ifFalse: [ ^ s at: (l//2 + 1) ]
]
ifTrue: [ ^nil ]
]
]. |
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
| #Scheme | Scheme | (define (a-mean l)
(/ (apply + l) (length l)))
(define (g-mean l)
(expt (apply * l) (/ (length l))))
(define (h-mean l)
(/ (length l) (apply + (map / l))))
(define (iota start stop)
(if (> start stop)
(list)
(cons start (iota (+ start 1) stop))))
(let* ((l (iota 1 10)) (a (a-mean l)) (g (g-mean l)) (h (h-mean l)))
(display a)
(display " >= ")
(display g)
(display " >= ")
(display h)
(newline)
(display (>= a g h))
(newline)) |
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
| #Objeck | Objeck |
bundle Default {
class Balanced {
function : IsBalanced(text : String) ~ Bool {
level := 0;
each(i : text) {
character := text->Get(i);
if(character = ']') {
if(level = 0) {
return false;
};
level -= 1;
};
if(character = '[') {
level += 1;
};
};
return level = 0;
}
function : Main(args : String[]) ~ Nil {
": "->Print(); IsBalanced("")->PrintLine();
"[]: "->Print(); IsBalanced("[]")->PrintLine();
"[][]: "->Print(); IsBalanced("[][]")->PrintLine();
"[[][]]: "->Print(); IsBalanced("[[][]]")->PrintLine();
"][: "->Print(); IsBalanced("][")->PrintLine();
"][][: "->Print(); IsBalanced("][][")->PrintLine();
"[]][[]: "->Print(); IsBalanced("[]][[]")->PrintLine();
}
}
}
|
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
| #Groovy | Groovy | map = [:]
map[7] = 7
map['foo'] = 'foovalue'
map.put('bar', 'barvalue')
map.moo = 'moovalue'
assert 7 == map[7]
assert 'foovalue' == map.foo
assert 'barvalue' == map['bar']
assert 'moovalue' == map.get('moo') |
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.
| #Objeck | Objeck |
use Structure;
bundle Default {
class Test {
function : Main(args : String[]) ~ Nil {
Run();
}
function : native : Run() ~ Nil {
values := IntVector->New([1, 2, 3, 4, 5]);
squares := values->Apply(Square(Int) ~ Int);
each(i : squares) {
squares->Get(i)->PrintLine();
};
}
function : Square(value : Int) ~ Int {
return value * value;
}
}
}
|
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #QB64 | QB64 |
'dictionary is not native data type of QB64
' here a dictionary engine using a string to store data
Dim Shared Skey As String * 1, SValue As String * 1, EValue As String * 1
Skey = Chr$(0)
SValue = Chr$(1)
EValue = Chr$(255)
'Demo area---------------->
Dim MyDictionary As String
If ChangeValue(MyDictionary, "a", "Ananas") Then Print "added new couple key value"
If ChangeValue(MyDictionary, "b", "Banana") Then Print "added new couple key value"
If ChangeValue(MyDictionary, "c", "cherry") Then Print "added new couple key value"
If ChangeValue(MyDictionary, "d", "Drake") Then Print "added new couple key value"
If ChangeValue(MyDictionary, "e", "Elm") Then Print "added new couple key value"
If ChangeValue(MyDictionary, "f", "Fire") Then Print "added new couple key value"
Print LenDict(MyDictionary)
Print "to key e there is "; GetDict$(MyDictionary, "e")
Print "to key e there is "; GetDict$(MyDictionary, "a")
If ChangeValue(MyDictionary, "e", "Elephant") Then Print " changed value of key passed"
Print "to key e there is "; GetDict$(MyDictionary, "e")
If Not (EraseKeyValue(MyDictionary, "e")) Then Print " Failed to erase key value passed" Else Print "Erased key value passed"
If GetDict$(MyDictionary, "e") = "" Then Print " No couple key value found for key value 'e'"
If ChangeKey(MyDictionary, "e", "f") = 0 Then
Print "key -a- has value "; GetDict$(MyDictionary, "a")
Print "we change key a to key e "
If ChangeKey(MyDictionary, "a", "e") = -1 Then
Print "key -a- has value "; GetDict$(MyDictionary, "a")
Print "key -e- has value "; GetDict$(MyDictionary, "e")
End If
End If
If InsertCouple(MyDictionary, "c", "m", "mellon") = -1 Then
Print " New couple inserted after key -c- "; GetDict$(MyDictionary, "c")
Print " new couple is key -m- "; GetDict$(MyDictionary, "m")
End If
Print LenDict(MyDictionary)
' End demo area --------------->
End
' it returns value/s for a key
Function GetDict$ (dict As String, Keys As String)
Dim StartK As Integer, StartV As Integer, EndV As Integer
StartK = InStr(dict, Skey + Keys + SValue)
StartV = InStr(StartK, dict, SValue)
EndV = InStr(StartV, dict, EValue)
If StartK = 0 Then GetDict$ = "" Else GetDict = Mid$(dict, StartV + 1, EndV - StartV)
End Function
' it changes value of a key or append the couple key, newvalue if key is new
Function ChangeValue (dict As String, Keys As String, NewValue As String)
ChangeValue = 0
Dim StartK As Integer, StartV As Integer, EndV As Integer
StartK = InStr(dict, Skey + Keys + SValue)
StartV = InStr(StartK, dict, SValue)
EndV = InStr(StartV, dict, EValue)
If StartK = 0 Then
dict = dict + Skey + Keys + SValue + NewValue + EValue
Else
dict = Left$(dict, StartV) + NewValue + Right$(dict, Len(dict) - EndV + 1)
End If
ChangeValue = -1
End Function
'it changes a key if it is in the dictionary
Function ChangeKey (dict As String, Keys As String, NewKey As String)
ChangeKey = 0
Dim StartK As Integer, StartV As Integer
StartK = InStr(dict, Skey + Keys + SValue)
StartV = InStr(StartK, dict, SValue)
If StartK = 0 Then
Print "Key " + Keys + " not found"
Exit Function
Else
dict = Left$(dict, StartK) + NewKey + Right$(dict, Len(dict) - StartV + 1)
End If
ChangeKey = -1
End Function
'it erases the couple key value
Function EraseKeyValue (dict As String, keys As String)
EraseKeyValue = 0
Dim StartK As Integer, StartV As Integer, EndV As Integer
StartK = InStr(dict, Skey + keys + SValue)
StartV = InStr(StartK, dict, SValue)
EndV = InStr(StartV, dict, EValue)
If StartK = 0 Then
Exit Function
Else
dict = Left$(dict, StartK - 1) + Right$(dict, Len(dict) - EndV + 1)
End If
EraseKeyValue = -1
End Function
'it inserts a couple after a defined key, if key is not in dictionary it append couple key value
Function InsertCouple (dict As String, SKeys As String, Keys As String, Value As String)
InsertCouple = 0
Dim StartK As Integer, StartV As Integer, EndV As Integer
StartK = InStr(dict, Skey + SKeys + SValue)
StartV = InStr(StartK, dict, SValue)
EndV = InStr(StartV, dict, EValue)
If StartK = 0 Then
dict = dict + Skey + Keys + SValue + Value + EValue
Else
dict = Left$(dict, EndV) + Skey + Keys + SValue + Value + EValue + Right$(dict, Len(dict) - EndV + 1)
End If
InsertCouple = -1
End Function
Function LenDict (dict As String)
LenDict = 0
Dim a As Integer, count As Integer
If Len(dict) <= 0 Then Exit Function
While a <= Len(dict)
a = InStr(a + 1, dict, EValue)
If a > 0 Then count = count + 1 Else Exit While
Wend
LenDict = count
End Function
|
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
| #R | R | > env <- new.env()
> env[["x"]] <- 123
> env[["x"]] |
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
| #Octave | Octave | function m = omean(l)
if ( numel(l) == 0 )
m = 0;
else
m = mean(l);
endif
endfunction
disp(omean([]));
disp(omean([1,2,3])); |
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
| #Oforth | Oforth | : avg ( x -- avg )
x sum
x size dup ifZero: [ 2drop null ] else: [ >float / ]
; |
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
| #Stata | Stata | set obs 100000
gen x=rbeta(0.2,1.3)
quietly summarize x, detail
display r(p50) |
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
| #Tcl | Tcl | proc median args {
set list [lsort -real $args]
set len [llength $list]
# Odd number of elements
if {$len & 1} {
return [lindex $list [expr {($len-1)/2}]]
}
# Even number of elements
set idx2 [expr {$len/2}]
set idx1 [expr {$idx2-1}]
return [expr {
([lindex $list $idx1] + [lindex $list $idx2])/2.0
}]
}
puts [median 3.0 4.0 1.0 -8.4 7.2 4.0 1.0 1.2]; # --> 2.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
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
const array float: numbers is [] (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0);
const func proc: main is func
local
var float: number is 0.0;
var float: sum is 0.0;
var float: product is 1.0;
var float: reciprocalSum is 0.0;
begin
for number range numbers do
sum +:= number;
product *:= number;
reciprocalSum +:= 1.0 / number;
end for;
writeln("Arithmetic mean: " <& sum / flt(length(numbers)));
writeln("Geometric mean: " <& product ** (1.0 / flt(length(numbers))));
writeln("Harmonic mean: " <& flt(length(numbers)) / reciprocalSum);
end func; |
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
| #OCaml | OCaml | let generate_brackets n =
let rec aux i acc =
if i <= 0 then acc else
aux (pred i) ('['::']'::acc)
in
let brk = aux n [] in
List.sort (fun _ _ -> (Random.int 3) - 1) brk
let is_balanced brk =
let rec aux = function
| [], 0 -> true
| '['::brk, level -> aux (brk, succ level)
| ']'::brk, 0 -> false
| ']'::brk, level -> aux (brk, pred level)
| _ -> assert false
in
aux (brk, 0)
let () =
let n = int_of_string Sys.argv.(1) in
Random.self_init();
let brk = generate_brackets n in
List.iter print_char brk;
Printf.printf " %B\n" (is_balanced brk);
;; |
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
| #Harbour | Harbour | arr := { => }
arr[ 10 ] := "Val_10"
arr[ "foo" ] := "foovalue" |
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.
| #OCaml | OCaml | Array.map |
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.
| #Octave | Octave | function e = f(x, y)
e = x^2 + exp(-1/(y+1));
endfunction
% f([2,3], [1,4]) gives and error, but
arrayfun(@f, [2, 3], [1,4])
% works |
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
| #Racket | Racket |
#lang racket
(define dict1 #hash((apple . 5) (orange . 10))) ; hash table
(define dict2 '((apple . 5) (orange . 10))) ; a-list
(define dict3 (vector "a" "b" "c")) ; vector (integer keys)
(dict-keys dict1) ; => '(orange apple)
(dict-values dict2) ; => '(5 10)
(for/list ([(k v) (in-dict dict3)]) ; => '("0 -> a" "1 -> b" "2 -> c")
(format "~a -> ~a" 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
| #Raku | Raku | my %pairs = hello => 13, world => 31, '!' => 71;
for %pairs.kv -> $k, $v {
say "(k,v) = ($k, $v)";
}
# Stable order
for %pairs.sort(*.value)>>.kv -> ($k, $v) {
say "(k,v) = ($k, $v)";
}
{ say "$^a => $^b" } for %pairs.kv;
say "key = $_" for %pairs.keys;
say "value = $_" for %pairs.values; |
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
| #ooRexx | ooRexx |
call testAverage .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
call testAverage .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11)
call testAverage .array~of(10, 20, 30, 40, 50, -100, 4.7, -11e2)
call testAverage .array~new
::routine testAverage
use arg numbers
say "numbers =" numbers~toString("l", ", ")
say "average =" average(numbers)
say
::routine average
use arg numbers
-- return zero for an empty list
if numbers~isempty then return 0
sum = 0
do number over numbers
sum += number
end
return sum/numbers~items
|
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
| #Oz | Oz | declare
fun {Mean Xs}
{FoldL Xs Number.'+' 0.0} / {Int.toFloat {Length Xs}}
end
in
{Show {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
| #TI-83_BASIC | TI-83 BASIC | median({1.1, 2.5, 0.3241}) |
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
| #TI-89_BASIC | TI-89 BASIC | median({3, 4, 1, -8.4, 7.2, 4, 1, 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
| #Sidef | Sidef | func A(a) { a.sum / a.len }
func G(a) { a.prod.root(a.len) }
func H(a) { a.len / a.map{1/_}.sum } |
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
| #Oforth | Oforth | String method: isBalanced
| c |
0 self forEach: c [
c '[' == ifTrue: [ 1+ continue ]
c ']' <> ifTrue: [ continue ]
1- dup 0 < ifTrue: [ drop false return ]
]
0 == ;
: genBrackets(n)
"" #[ "[" "]" 2 rand 2 == ifTrue: [ swap ] rot + swap + ] times(n) ; |
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
| #Haskell | Haskell | import Data.Map
dict = fromList [("key1","val1"), ("key2","val2")]
ans = Data.Map.lookup "key2" dict -- evaluates to Just "val2"
|
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.
| #Oforth | Oforth | 0 #+ [ 1, 2, 3, 4, 5 ] apply |
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.
| #Ol | Ol |
(for-each
(lambda (element)
(display element))
'(1 2 3 4 5))
; ==> 12345
|
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
| #REXX | REXX | /*REXX program demonstrates how to set and display values for an associative array. */
/*╔════════════════════════════════════════════════════════════════════════════════════╗
║ The (below) two REXX statements aren't really necessary, but it shows how to ║
║ define any and all entries in a associative array so that if a "key" is used that ║
║ isn't defined, it can be displayed to indicate such, or its value can be checked ║
║ to determine if a particular associative array element has been set (defined). ║
╚════════════════════════════════════════════════════════════════════════════════════╝*/
stateF.= ' [not defined yet] ' /*sets any/all state former capitals.*/
stateN.= ' [not defined yet] ' /*sets any/all state names. */
w = 0 /*the maximum length of a state name.*/
stateL =
/*╔════════════════════════════════════════════════════════════════════════════════════╗
║ The list of states (empty as of now). It's convenient to have them in alphabetic ║
║ order; they'll be listed in the order as they are in the REXX program below). ║
║ In REXX, when a key is used (for a stemmed array, as they are called in REXX), ║
║ and the key isn't assigned a value, the key's name is stored (internally) as ║
║ uppercase (Latin) characters (as in the examples below. If the key has a ║
║ a value, the key's value is used as is (i.e.: no upper translation is performed).║
║ Actually, any characters can be used, including blank(s) and non─displayable ║
║ characters (including '00'x, 'ff'x, commas, periods, quotes, ···). ║
╚════════════════════════════════════════════════════════════════════════════════════╝*/
call setSC 'al', "Alabama" , 'Tuscaloosa'
call setSC 'ca', "California" , 'Benicia'
call setSC 'co', "Colorado" , 'Denver City'
call setSC 'ct', "Connecticut" , 'Hartford and New Haven (jointly)'
call setSC 'de', "Delaware" , 'New-Castle'
call setSC 'ga', "Georgia" , 'Milledgeville'
call setSC 'il', "Illinois" , 'Vandalia'
call setSC 'in', "Indiana" , 'Corydon'
call setSC 'ia', "Iowa" , 'Iowa City'
call setSC 'la', "Louisiana" , 'New Orleans'
call setSC 'me', "Maine" , 'Portland'
call setSC 'mi', "Michigan" , 'Detroit'
call setSC 'ms', "Mississippi" , 'Natchez'
call setSC 'mo', "Missouri" , 'Saint Charles'
call setSC 'mt', "Montana" , 'Virginia City'
call setSC 'ne', "Nebraska" , 'Lancaster'
call setSC 'nh', "New Hampshire" , 'Exeter'
call setSC 'ny', "New York" , 'New York'
call setSC 'nc', "North Carolina" , 'Fayetteville'
call setSC 'oh', "Ohio" , 'Chillicothe'
call setSC 'ok', "Oklahoma" , 'Guthrie'
call setSC 'pa', "Pennsylvania" , 'Lancaster'
call setSC 'sc', "South Carolina" , 'Charlestown'
call setSC 'tn', "Tennessee" , 'Murfreesboro'
call setSC 'vt', "Vermont" , 'Windsor'
do j=1 for words(stateL) /*show all capitals that were defined. */
$= word(stateL, j) /*get the next (USA) state in the list.*/
say 'the former capital of ('$") " left(stateN.$, w) " was " stateC.$
end /*j*/ /* [↑] show states that were defined.*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
setSC: parse arg code,name,cap; upper code /*get code, name & cap.; uppercase code*/
stateL= stateL code /*keep a list of all the US state codes*/
stateN.code= name; w= max(w,length(name)) /*define the state's name; max width. */
stateC.code= cap /* " " " code to the capital*/
return /*return to invoker, SETSC is finished.*/ |
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
| #PARI.2FGP | PARI/GP | avg(v)={
if(#v,vecsum(v)/#v)
}; |
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
| #Pascal | Pascal | Program Mean;
function DoMean(vector: array of double): double;
var
sum: double;
i, len: integer;
begin
sum := 0;
len := length(vector);
if len > 0 then
begin
for i := low(vector) to high(vector) do
sum := sum + vector[i];
sum := sum / len;
end;
DoMean := sum;
end;
const
vector: array [3..8] of double = (3.0, 1.0, 4.0, 1.0, 5.0, 9.0);
var
i: integer;
begin
writeln('Calculating the arithmetic mean of a series of numbers:');
write('Numbers: [ ');
for i := low(vector) to high(vector) do
write (vector[i]:3:1, ' ');
writeln (']');
writeln('Mean: ', DoMean(vector):10:8);
end. |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches to this. One is to sort the elements, and then pick the element(s) in the middle.
Sorting would take at least O(n logn). Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s). This would also take O(n logn). The best solution is to use the selection algorithm to find the median in O(n) time.
See also
Quickselect_algorithm
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Ursala | Ursala | #import std
#import flo
median = fleq-<; @K30K31X eql?\~&rh div\2.+ plus@lzPrhPX |
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
| #Vala | Vala | int compare_numbers(void* a_ref, void* b_ref) {
double a = *(double*) a_ref;
double b = *(double*) b_ref;
return a > b ? 1 : a < b ? -1 : 0;
}
double median(double[] elements) {
double[] clone = elements;
Posix.qsort(clone, clone.length, sizeof(double), compare_numbers);
double middle = clone.length / 2.0;
int first = (int) Math.floor(middle);
int second = (int) Math.ceil(middle);
return (clone[first] + clone[second]) / 2;
}
void main() {
double[] array1 = {2, 4, 6, 1, 7, 3, 5};
double[] array2 = {2, 4, 6, 1, 7, 3, 5, 8};
print(@"$(median(array1)) $(median(array2))\n");
} |
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
| #Smalltalk | Smalltalk | Collection extend
[
arithmeticMean
[
^ (self fold: [:a :b| a + b ]) / (self size)
]
geometricMean
[
^ (self fold: [:a :b| a * b]) raisedTo: (self size reciprocal)
]
harmonicMean
[
^ (self size) / ((self collect: [:x|x reciprocal]) fold: [:a :b| a + b ] )
]
]
|a|
a := #(1 2 3 4 5 6 7 8 9 10).
a arithmeticMean asFloat displayNl.
a geometricMean asFloat displayNl.
a harmonicMean asFloat displayNl.
((a arithmeticMean) >= (a geometricMean)) displayNl.
((a geometricMean) >= (a harmonicMean)) displayNl. |
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
| #ooRexx | ooRexx |
tests = .array~of("", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]")
-- add some randomly generated tests
loop i = 1 to 8
tests~append(generateBrackets(i))
end
loop test over tests
say test":" checkbrackets(test)
end
::routine checkBrackets
use arg input
-- counter of bracket groups. Must be 0 at end to be valid
groups = 0
-- loop over all of the characters
loop c over input~makearray("")
if c == '[' then groups += 1
else if c == ']' then groups -= 1
else return .false -- non-bracket char found
-- check for a close occurring before an open
if groups < 0 then return .false
end
-- should be zero at the end
return groups == 0
-- generate a string with n pairs of brackets
::routine generateBrackets
use arg n
answer = .mutablebuffer~new(,2*n)
openBracketsNeeded = n
unclosedBrackets = 0
loop while answer~length < 2 * n
if random(0, 1) & openBracketsNeeded > 0 | unclosedBrackets == 0 then do
answer~append('[')
openBracketsNeeded -= 1
unclosedBrackets += 1
end
else do
answer~append(']')
unclosedBrackets -= 1
end
end
return answer~string
|
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
| #hexiscript | hexiscript | let d dict 2 # Initial estimated size
let d["test"] "test" # Strings can be used as index
let d[123] 123 # Integers can also be used as index
println d["test"]
println d[123] |
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
| #Icon_and_Unicon | Icon and Unicon | procedure main()
local t
t := table()
t["foo"] := "bar"
write(t["foo"])
end |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #ooRexx | ooRexx | start = .array~of("Rick", "Mike", "David", "Mark")
new = map(start, .routines~reversit)
call map new, .routines~sayit
-- a function to perform an iterated callback over an array
-- using the provided function. Returns an array containing
-- each function result
::routine map
use strict arg array, function
resultArray = .array~new(array~items)
do item over array
resultArray~append(function~call(item))
end
return resultArray
::routine reversit
use arg string
return string~reverse
::routine sayit
use arg string
say string
return .true -- called as a function, so a result is required |
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.
| #Order | Order | #include <order/interpreter.h>
ORDER_PP( 8tuple_map(8fn(8X, 8times(8X, 8X)), 8tuple(1, 2, 3, 4, 5)) )
// -> (1,4,9,16,25)
ORDER_PP( 8seq_map(8fn(8X, 8times(8X, 8X)), 8seq(1, 2, 3, 4, 5)) )
// -> (1)(4)(9)(16)(25)
ORDER_PP( 8seq_for_each(8fn(8X, 8print(8X 8comma)), 8seq(1, 2, 3, 4, 5)) )
// prints 1,2,3,4,5, and returns 8nil |
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
| #Ring | Ring |
# Project : Associative array/Iteration
lst = [["hello", 13], ["world", 31], ["!", 71]]
for n = 1 to len(lst)
see lst[n][1] + " : " + lst[n][2] + nl
next
|
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
| #RLaB | RLaB |
x = <<>>; // create an empty list
x.hello = 1;
x.world = 2;
x.["!"] = 3;
// to iterate over identifiers of a list one needs to use the function ''members''
// the identifiers are returned as a lexicographically ordered string row-vector
// here ["!", "hello", "world"]
for(i in members(x))
{ printf("%s %g\n", i, x.[i]); }
// occasionally one needs to check if there exists member of a list
y = members(x); // y contains ["!", "hello", "world"]
clear(x.["!"]); // remove member with identifier "!" from the list "x"
for(i in y)
{ printf("%s %g\n", i, x.[i]); } // this produces error because x.["!"] does not exist
for(i in y)
{
if (exist(x.[i]))
{ printf("%s %g\n", i, x.[i]); } // we print a member of the list "x" only if it exists
}
|
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
| #Perl | Perl | sub avg {
@_ or return 0;
my $sum = 0;
$sum += $_ foreach @_;
return $sum/@_;
}
print avg(qw(3 1 4 1 5 9)), "\n"; |
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
| #Phix | Phix | with javascript_semantics
function mean(sequence s)
if length(s)=0 then return 0 end if
return sum(s)/length(s)
end function
? mean({1, 2, 5, -5, -9.5, 3.14159})
|
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
| #VBA | VBA | Private Function medianq(s As Variant) As Double
Dim res As Double, tmp As Integer
Dim l As Integer, k As Integer
res = 0
l = UBound(s): k = WorksheetFunction.Floor_Precise((l + 1) / 2, 1)
If l Then
res = quick_select(s, k)
If l Mod 2 = 0 Then
tmp = quick_select(s, k + 1)
res = (res + tmp) / 2
End If
End If
medianq = res
End Function
Public Sub main2()
s = [{4, 2, 3, 5, 1, 6}]
Debug.Print medianq(s)
End Sub |
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
| #Vedit_macro_language | Vedit macro language | Sort(0, File_Size, NOCOLLATE+NORESTORE)
EOF Goto_Line(Cur_Line/2)
Reg_Copy(10, 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
| #SQL | SQL |
--setup
CREATE TABLE averages (val INTEGER);
INSERT INTO averages VALUES (1);
INSERT INTO averages VALUES (2);
INSERT INTO averages VALUES (3);
INSERT INTO averages VALUES (4);
INSERT INTO averages VALUES (5);
INSERT INTO averages VALUES (6);
INSERT INTO averages VALUES (7);
INSERT INTO averages VALUES (8);
INSERT INTO averages VALUES (9);
INSERT INTO averages VALUES (10);
-- calculate means
SELECT
1/avg(1/val) AS harm,
avg(val) AS arith
FROM
averages;
|
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
| #OxygenBasic | OxygenBasic | function CheckBrackets(string s) as bool
'=======================================
sys co, le=len s
byte b at strptr s
indexbase 0
for i=0 to <le
select b(i)
case "[" : co++
case "]" : co--
end select
if co<0 then return 0
next
if co=0 then return 1
end function
'TEST
'====
print CheckBrackets "" '1
print CheckBrackets "[" '0
print CheckBrackets "]" '0
print CheckBrackets "[]" '1
print CheckBrackets "[[]" '0
print CheckBrackets "[]]" '0
print CheckBrackets "[][]"'1
print CheckBrackets "][" '0
|
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
| #Inform_7 | Inform 7 | Hash Bar is a room.
Connection relates various texts to one number. The verb to be connected to implies the connection relation.
"foo" is connected to 12.
"bar" is connected to 34.
"baz" is connected to 56.
When play begins:
[change values]
now "bleck" is connected to 78;
[check values]
if "foo" is connected to 12, say "good.";
if "bar" is not connected to 56, say "good.";
[retrieve values]
let V be the number that "baz" relates to by the connection relation;
say "'baz' => [V].";
end the story. |
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
| #Ioke | Ioke | {a: "a", b: "b"} |
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.
| #Oz | Oz | declare
fun{Square A}
A*A
end
Lst = [1 2 3 4 5]
%% apply a PROCEDURE to every element
{ForAll Lst Show}
%% apply a FUNCTION to every element
Result = {Map Lst Square}
{Show Result} |
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.
| #PARI.2FGP | PARI/GP | callback(n)=n+n;
apply(callback, [1,2,3,4,5]) |
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
| #Ruby | Ruby | my_dict = { "hello" => 13,
"world" => 31,
"!" => 71 }
# iterating over key-value pairs:
my_dict.each {|key, value| puts "key = #{key}, value = #{value}"}
# or
my_dict.each_pair {|key, value| puts "key = #{key}, value = #{value}"}
# iterating over keys:
my_dict.each_key {|key| puts "key = #{key}"}
# iterating over values:
my_dict.each_value {|value| puts "value =#{value}"} |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Rust | Rust | use std::collections::HashMap;
fn main() {
let mut olympic_medals = HashMap::new();
olympic_medals.insert("United States", (1072, 859, 749));
olympic_medals.insert("Soviet Union", (473, 376, 355));
olympic_medals.insert("Great Britain", (246, 276, 284));
olympic_medals.insert("Germany", (252, 260, 270));
for (country, medals) in olympic_medals {
println!("{} has had {} gold medals, {} silver medals, and {} bronze medals",
country, medals.0, medals.1, medals.2);
}
} |
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
| #Phixmonti | Phixmonti | 1 2 5 -5 -9.5 3.14159 stklen tolist
len swap sum swap / print |
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
| #PHP | PHP | $nums = array(3, 1, 4, 1, 5, 9);
if ($nums)
echo array_sum($nums) / count($nums), "\n";
else
echo "0\n"; |
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
| #Vlang | Vlang | fn main() {
println(median([3, 1, 4, 1])) // prints 2
println(median([3, 1, 4, 1, 5])) // prints 3
}
fn median(aa []int) int {
mut a := aa.clone()
a.sort()
half := a.len / 2
mut m := a[half]
if a.len%2 == 0 {
m = (m + a[half-1]) / 2
}
return m
} |
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
| #Wortel | Wortel | @let {
; iterative
med1 &l @let {a @sort l s #a i @/s 2 ?{%%s 2 ~/ 2 +`-i 1 a `i a `i a}}
; tacit
med2 ^(\~/2 @sum @(^(\&![#~f #~c] \~/2 \~-1 #) @` @id) @sort)
[[
!med1 [4 2 5 2 1]
!med1 [4 5 2 1]
!med2 [4 2 5 2 1]
!med2 [4 5 2 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
| #Stata | Stata | clear all
set obs 10
gen x=_n
ameans x
Variable | Type Obs Mean [95% Conf. Interval]
-------------+---------------------------------------------------------------
x | Arithmetic 10 5.5 3.334149 7.665851
| Geometric 10 4.528729 2.680672 7.650836
| Harmonic 10 3.414172 2.035664 10.57602
----------------------------------------------------------------------------- |
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
| #Tcl | Tcl | proc arithmeticMean list {
set sum 0.0
foreach value $list { set sum [expr {$sum + $value}] }
return [expr {$sum / [llength $list]}]
}
proc geometricMean list {
set product 1.0
foreach value $list { set product [expr {$product * $value}] }
return [expr {$product ** (1.0/[llength $list])}]
}
proc harmonicMean list {
set sum 0.0
foreach value $list { set sum [expr {$sum + 1.0/$value}] }
return [expr {[llength $list] / $sum}]
}
set nums {1 2 3 4 5 6 7 8 9 10}
set A10 [arithmeticMean $nums]
set G10 [geometricMean $nums]
set H10 [harmonicMean $nums]
puts "A10=$A10, G10=$G10, H10=$H10"
if {$A10 >= $G10} { puts "A10 >= G10" }
if {$G10 >= $H10} { puts "G10 >= H10" } |
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
| #PARI.2FGP | PARI/GP | balanced(s)={
my(n=0,v=Vecsmall(s));
for(i=1,#v,
if(v[i]==91,
n++
,
if(v[i]==93 && n, n--, return(0))
)
);
!n
};
rnd(n)=Strchr(vectorsmall(n,i,if(random(2),91,93)))
forstep(n=0,10,2,s=rnd(n);print(s"\t"if(balanced(s),"true","false"))) |
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
| #J | J | coclass 'assocArray'
encode=: 'z', (a.{~;48 65 97(+ i.)&.>10 26 26) {~ 62x #.inv 256x #. a.&i.
get=: ".@encode
has=: 0 <: nc@<@encode
set=:4 :'(encode x)=:y' |
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.
| #Pascal | Pascal | # create array
my @a = (1, 2, 3, 4, 5);
# create callback function
sub mycallback {
return 2 * shift;
}
# use array indexing
for (my $i = 0; $i < scalar @a; $i++) {
print "mycallback($a[$i]) = ", mycallback($a[$i]), "\n";
}
# using foreach
foreach my $x (@a) {
print "mycallback($x) = ", mycallback($x), "\n";
}
# using map (useful for transforming an array)
my @b = map mycallback($_), @a; # @b is now (2, 4, 6, 8, 10)
# and the same using an anonymous function
my @c = map { $_ * 2 } @a; # @c is now (2, 4, 6, 8, 10)
# use a callback stored in a variable
my $func = \&mycallback;
my @d = map $func->($_), @a; # @d is now (2, 4, 6, 8, 10)
# filter an array
my @e = grep { $_ % 2 == 0 } @a; # @e is now (2, 4) |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Scala | Scala | val m = Map("Amsterdam" -> "Netherlands", "New York" -> "USA", "Heemstede" -> "Netherlands")
println(f"Key->Value: ${m.mkString(", ")}%s")
println(f"Pairs: ${m.toList.mkString(", ")}%s")
println(f"Keys: ${m.keys.mkString(", ")}%s")
println(f"Values: ${m.values.mkString(", ")}%s")
println(f"Unique values: ${m.values.toSet.mkString(", ")}%s") |
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
| #Scheme | Scheme |
;; Create an associative array (hash-table) whose keys are strings:
(define table (hash-table 'string=?
'("hello" . 0) '("world" . 22) '("!" . 999)))
;; Iterate over the table, passing the key and the value of each entry
;; as arguments to a function:
(hash-table-for-each
table
;; Create by "partial application" a function that accepts 2 arguments,
;; the key and the value:
(pa$ format #t "Key = ~a, Value = ~a\n")) |
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
| #PicoLisp | PicoLisp | (de mean (Lst)
(if (atom Lst)
0
(/ (apply + Lst) (length 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
| #PL.2FI | PL/I | arithmetic_mean = sum(A)/dimension(A,1); |
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
| #Wren | Wren | import "/sort" for Sort, Find
import "/math" for Nums
import "/queue" for PriorityQueue
var lists = [
[5, 3, 4],
[3, 4, 1, -8.4, 7.2, 4, 1, 1.2]
]
for (l in lists) {
// sort and then find median
var l2 = Sort.merge(l)
System.print(Nums.median(l2))
// using a priority queue
var pq = PriorityQueue.new()
for (e in l) pq.push(e, -e)
var c = pq.count
var v = pq.values
var m = (c % 2 == 1) ? v[(c/2).floor] : (v[c/2] + v[c/2-1])/2
System.print(m)
// using quickselect
if (c % 2 == 1) {
System.print(Find.quick(l, (c/2).floor))
} else {
var m1 = Find.quick(l, c/2-1)
var m2 = Find.quick(l, c/2)
System.print((m1 + m2)/2)
}
System.print()
} |
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
| #Ursala | Ursala | #import std
#import flo
data = ari10(1.,10.) # arithmetic progression, length 10 with endpoints 1 and 10
a = mean data
g = exp mean ln* data
h = div/1. mean div/*1. data
#cast %eLbX
main = ^(~&,ordered not fleq) <a,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
| #Pascal | Pascal | sub generate {
my $n = shift;
my $str = '[' x $n;
substr($str, rand($n + $_), 0) = ']' for 1..$n;
return $str;
}
sub balanced {
shift =~ /^ (\[ (?1)* \])* $/x;
}
for (0..8) {
my $input = generate($_);
print balanced($input) ? " ok:" : "bad:", " '$input'\n";
} |
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
| #Java | Java | Map<String, Integer> map = new HashMap<String, Integer>();
map.put("foo", 5);
map.put("bar", 10);
map.put("baz", 15);
map.put("foo", 6); |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.