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/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.
| #Perl | Perl | # 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
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const type: dictType is hash [string] integer;
var dictType: myDict is dictType.value;
const proc: main is func
local
var string: stri is "";
var integer: number is 0;
begin
myDict @:= ["hello"] 1;
myDict @:= ["world"] 2;
myDict @:= ["!"] 3;
# iterating over key-value pairs:
for number key stri range myDict do
writeln("key = " <& number <& ", value = " <& stri);
end for;
# iterating over keys:
for key stri range myDict do
writeln("key = " <& stri);
end for;
# iterating over values:
for number range myDict do
writeln("value = " <& number);
end for;
end func; |
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
| #SenseTalk | SenseTalk | put {name:"Fluffy", type:"Rabbit", color:"White"} into animal
put "Carries a watch" into animal's habits
put "The animal: " & animal
put "The keys: " & keys of animal
put "The values: " & animal's values
// Keys and Values
put ,"All Properties:"
repeat with each [key,value] in animal
put !"Key: [[key]] Value: [[value]]"
end repeat
// Keys only
put ,"Keys:"
repeat with each [key] in animal
put key
end repeat
// Values only
put ,"Values:"
repeat with each [,value] in animal
put value
end repeat
// Using an iterator
put ,"Treating the property list as an iterator:"
put animal's nextValue -- calling any of the "next" functions begins iteration
put animal's nextKeyValue
put animal's nextKey
put animal's nextKeyValue
put animal's nextValue -- walking off the end returns a unique endValue
|
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
| #Plain_English | Plain English | To run:
Start up.
Demonstrate finding the arithmetic mean.
Wait for the escape key.
Shut down.
An entry is a thing with a fraction.
A list is some entries.
A sum is a fraction.
A mean is a fraction.
To demonstrate finding the arithmetic mean:
Create an example list.
Write "A list: " then the example list on the console.
Find a mean of the example list.
Write "The list's mean: " then the mean on the console.
Destroy the example list.
To add a fraction to a list:
Allocate memory for an entry.
Put the fraction into the entry's fraction.
Append the entry to the list.
To create an example list:
Add 1/1 to the example list.
Add 2/1 to the example list.
Add 5-1/3 to the example list.
Add 7-1/2 to the example list.
To find a sum of a list:
Put 0 into the sum.
Get an entry from the list.
Loop.
If the entry is nil, exit.
Add the entry's fraction to the sum.
Put the entry's next into the entry.
Repeat.
To find a mean of a list:
Find a sum of the list.
Put the sum divided by the list's count into the mean.
To convert a list to a string:
Get an entry from the list.
Loop.
If the entry is nil, break.
Append the entry's fraction to the string.
If the entry's next is not nil, append ", " to the string.
Put the entry's next into the entry.
Repeat. |
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
| #Pop11 | Pop11 | define mean(v);
lvars n = length(v), i, s = 0;
if n = 0 then
return(0);
else
for i from 1 to n do
s + v(i) -> s;
endfor;
endif;
return(s/n);
enddefine; |
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
| #Yabasic | Yabasic | sub floor(x)
return int(x + .05)
end sub
sub ceil(x)
if x > int(x) x = x + 1
return x
end sub
SUB ASort$(matriz$())
local last, gap, first, tempi$, tempj$, i, j
last = arraysize(matriz$(), 1)
gap = floor(last / 10) + 1
while(TRUE)
first = gap + 1
for i = first to last
tempi$ = matriz$(i)
j = i - gap
while(TRUE)
tempj$ = matriz$(j)
if (tempi$ >= tempj$) then
j = j + gap
break
end if
matriz$(j+gap) = tempj$
if j <= gap then
break
end if
j = j - gap
wend
matriz$(j) = tempi$
next i
if gap = 1 then
return
else
gap = floor(gap / 3.5) + 1
end if
wend
END SUB
sub median(numlist$)
local numlist$(1), n
n = token(numlist$, numlist$(), ", ")
ASort$(numlist$())
if mod(n, 2) = 0 then return (val(numlist$(n / 2)) + val(numlist$(n / 2 + 1))) / 2 end if
return val(numlist$(ceil(n / 2)))
end sub
print median("4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2") // 4.4
print median("4.1, 7.2, 1.7, 9.3, 4.4, 3.2") // 4.25
|
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
| #zkl | zkl | var quickSelect=Import("quickSelect").qselect;
fcn median(xs){
n:=xs.len();
if (n.isOdd) return(quickSelect(xs,n/2));
( quickSelect(xs,n/2-1) + quickSelect(xs,n/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
| #Vala | Vala |
double arithmetic(int[] list){
double mean;
double sum = 0;
foreach(int number in list){
sum += number;
} // foreach
mean = sum / list.length;
return mean;
} // end arithmetic mean
double geometric(int[] list){
double mean;
double product = 1;
foreach(int number in list){
product *= number;
} // foreach
mean = Math.pow(product, (1 / (double) list.length));
return mean;
} // end geometric mean
double harmonic(int[] list){
double mean;
double sum_inverse = 0;
foreach(int number in list){
sum_inverse += (1 / (double) number);
} // foreach
mean = (double) list.length / sum_inverse;
return mean;
} // end harmonic mean
public static void main(){
int[] list = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
double arithmetic_mean = arithmetic(list);
double geometric_mean = geometric(list);
double harmonic_mean = harmonic(list);
// should be 5.5
stdout.printf("Arithmetic mean: %s\n", arithmetic_mean.to_string());
// should be 4.528728688116765
stdout.printf("Geometric mean: %s\n", geometric_mean.to_string());
// should be 4.528728688116765
stdout.printf("Harmonic mean: %s\n", harmonic_mean.to_string());
}
|
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
| #Perl | Perl | 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
| #JavaScript | JavaScript | var assoc = {};
assoc['foo'] = 'bar';
assoc['another-key'] = 3;
// dot notation can be used if the property name is a valid identifier
assoc.thirdKey = 'we can also do this!';
assoc[2] = "the index here is the string '2'";
//using JavaScript's object literal notation
var assoc = {
foo: 'bar',
'another-key': 3 //the key can either be enclosed by quotes or not
};
//iterating keys
for (var key in assoc) {
// hasOwnProperty() method ensures the property isn't inherited
if (assoc.hasOwnProperty(key)) {
alert('key:"' + key + '", value:"' + assoc[key] + '"');
}
} |
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.
| #Phix | Phix | requires("0.8.2")
function add1(integer x)
return x + 1
end function
?apply({1,2,3},add1)
|
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.
| #Phixmonti | Phixmonti | /# Rosetta Code problem: http://rosettacode.org/wiki/Apply_a_callback_to_an_array
by Galileo, 05/2022 #/
include ..\Utilitys.pmt
def ++
1 +
enddef
def square
dup *
enddef
( 1 2 3 ) dup
getid ++ map swap
getid square map
pstack |
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
| #Sidef | Sidef | var hash = Hash.new(
key1 => 'value1',
key2 => 'value2',
)
# Iterate over key-value pairs
hash.each { |key, value|
say "#{key}: #{value}";
}
# Iterate only over keys
hash.keys.each { |key|
say key;
}
# Iterate only over values
hash.values.each { |value|
say 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
| #Slate | Slate | define: #pairs -> ({'hello' -> 1. 'world' -> 2. '!' -> 3. 'another!' -> 3} as: Dictionary).
pairs keysAndValuesDo: [| :key :value |
inform: '(k, v) = (' ; key printString ; ', ' ; value printString ; ')'
].
pairs keysDo: [| :key |
inform: '(k, v) = (' ; key printString ; ', ' ; (pairs at: key) printString ; ')'
].
pairs do: [| :value |
inform: 'value = ' ; value printString
]. |
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
| #PostScript | PostScript |
/findmean{
/x exch def
/sum 0 def
/i 0 def
x length 0 eq
{}
{
x length{
/sum sum x i get add def
/i i 1 add def
}repeat
/sum sum x length div def
}ifelse
sum ==
}def
|
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
| #PowerShell | PowerShell | function mean ($x) {
if ($x.Count -eq 0) {
return 0
} else {
$sum = 0
foreach ($i in $x) {
$sum += $i
}
return $sum / $x.Count
}
} |
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
| #Zoea | Zoea |
program: median
case: 1
input: [4,5,6,8,9]
output: 6
case: 2
input: [2,5,6]
output: 5
case: 3
input: [2,5,6,8]
output: 5.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
| #Zoea_Visual | Zoea Visual |
module Averages;
type
Vector = array {math} * of real;
procedure Partition(var a: Vector; left, right: integer): integer;
var
pValue,aux: real;
store,i,pivot: integer;
begin
pivot := right;
pValue := a[pivot];
aux := a[right];a[right] := a[pivot];a[pivot] := aux; (* a[pivot] <-> a[right] *)
store := left;
for i := left to right -1 do
if a[i] <= pValue then
aux := a[store];a[store] := a[i];a[i]:=aux;
inc(store)
end
end;
aux := a[right];a[right] := a[store]; a[store] := aux;
return store
end Partition;
(* QuickSelect algorithm *)
procedure Select(a: Vector; left,right,k: integer;var r: real);
var
pIndex, pDist : integer;
begin
if left = right then r := a[left]; return end;
pIndex := Partition(a,left,right);
pDist := pIndex - left + 1;
if pDist = k then
r := a[pIndex];return
elsif k < pDist then
Select(a,left, pIndex - 1, k, r)
else
Select(a,pIndex + 1, right, k - pDist, r)
end
end Select;
procedure Median(a: Vector): real;
var
idx: integer;
r1,r2 : real;
begin
idx := len(a) div 2 + 1;
r1 := 0.0;r2 := 0.0;
Select(a,0,len(a) - 1,idx,r1);
if odd(len(a)) then return r1 end;
Select(a,0,len(a) - 1,idx - 1,r2);
return (r1 + r2) / 2;
end Median;
var
ary: Vector;
r: real;
begin
ary := new Vector(3);
ary := [5.0,3.0,4.0];
writeln(Median(ary):10:2);
ary := new Vector(4);
ary := [5.0,4.0,2.0,3.0];
writeln(Median(ary):10:2);
ary := new Vector(8);
ary := [3.0,4.0,1.0,-8.4,7.2,4.0,1.0,1.2];
writeln(Median(ary):10:2)
end Averages.
|
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
| #VBA | VBA | Private Function arithmetic_mean(s() As Variant) As Double
arithmetic_mean = WorksheetFunction.Average(s)
End Function
Private Function geometric_mean(s() As Variant) As Double
geometric_mean = WorksheetFunction.GeoMean(s)
End Function
Private Function harmonic_mean(s() As Variant) As Double
harmonic_mean = WorksheetFunction.HarMean(s)
End Function
Public Sub pythagorean_means()
Dim s() As Variant
s = [{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}]
Debug.Print "A ="; arithmetic_mean(s)
Debug.Print "G ="; geometric_mean(s)
Debug.Print "H ="; harmonic_mean(s)
End Sub |
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
| #Phix | Phix | with javascript_semantics
function check_brackets(sequence s)
integer level = 0
for i=1 to length(s) do
switch s[i]
case '[': level += 1
case ']': level -= 1
if level<0 then return false end if
end switch
end for
return (level=0)
end function
sequence s
constant ok = {"not ok","ok"}
for i=1 to 10 do
for j=1 to 2 do
s = shuffle(join(repeat("[]",i-1),""))
printf(1,"%s %s\n",{s,ok[check_brackets(s)+1]})
end for
end for
|
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
| #jq | jq | # An empty object:
{}
# Its type:
{} | type
# "object"
# An object literal:
{"a": 97, "b" : 98}
# Programmatic object construction:
reduce ("a", "b", "c", "d") as $c ({}; . + { ($c) : ($c|explode[.0])} )
# {"a":97,"c":99,"b":98,"d":100}
# Same as above:
reduce range (97;101) as $i ({}; . + { ([$i]|implode) : $i })
# Addition of a key/value pair by assignment:
{}["A"] = 65 # in this case, the object being added to is {}
# Alteration of the value of an existing key:
{"A": 65}["A"] = "AA" |
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
| #Jsish | Jsish | var assoc = {};
assoc['foo'] = 'bar';
assoc['another-key'] = 3;
// dot notation can be used if the property name is a valid identifier
assoc.thirdKey = 'we can also do this!';
assoc[2] = "the index here is the string '2'";
;assoc;
//using JavaScript's object literal notation
var assoc = {
foo: 'bar',
'another-key': 3 //the key can either be enclosed by quotes or not
};
//iterating keys
for (var key in assoc) {
// hasOwnProperty() method ensures the property isn't inherited
if (assoc.hasOwnProperty(key)) {
puts('key:"' + key + '", value:"' + assoc[key] + '"');
}
}
;assoc;
/*
=!EXPECTSTART!=
associativeArray.jsi:12: warn: duplicate var: assoc
assoc ==> { 2:"the index here is the string \'2\'", "another-key":3, foo:"bar", thirdKey:"we can also do this!" }
key:"another-key", value:"3"
key:"foo", value:"bar"
assoc ==> { "another-key":3, foo:"bar" }
=!EXPECTEND!=
*/ |
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.
| #PHP | PHP | function cube($n)
{
return($n * $n * $n);
}
$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($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.
| #Picat | Picat | go =>
L = 1..10,
% Using map/2 in different ways
println(L.map(fun)),
println(map(L,fun)),
println(map(fun,L)),
% List comprehensions
println([fun(I) : I in L]),
% Using apply/2
println([apply(fun,I) : I in L]),
% And using list comprehension with the function directly.
println([I*I : I in L]),
nl.
% Some function
fun(X) = X*X.
|
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Smalltalk | Smalltalk | |pairs|
pairs := Dictionary
from: { 'hello' -> 1. 'world' -> 2. '!' -> 3. 'another!' -> 3 }.
"iterate over keys and values"
pairs keysAndValuesDo: [ :k :v |
('(k, v) = (%1, %2)' % { k. v }) displayNl
].
"iterate over keys"
pairs keysDo: [ :key |
('key = %1, value = %2' % { key. pairs at: key }) displayNl
].
"iterate over values"
pairs do: [ :value |
('value = %1' % { value }) displayNl
]. |
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
| #SNOBOL4 | SNOBOL4 | * # Create sample table
t = table()
t<'cat'> = 'meow'
t<'dog'> = 'woof'
t<'pig'> = 'oink'
* # Convert table to key/value array
a = convert(t,'array')
* # Iterate pairs
ploop i = i + 1; output = a<i,1> ' -> ' a<i,2> :s(ploop)
* # Iterate keys
kloop j = j + 1; output = a<j,1> :s(kloop)
* # Iterate vals
vloop k = k + 1; output = a<k,2> :s(vloop)
end |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Processing | Processing | float mean(float[] arr) {
float out = 0;
for (float n : arr) {
out += n;
}
return out / arr.length;
} |
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
| #Prolog | Prolog |
mean(List, Mean) :-
length(List, Length),
sumlist(List, Sum),
Mean is Sum / Length.
|
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
| #zonnon | zonnon |
module Averages;
type
Vector = array {math} * of real;
procedure Partition(var a: Vector; left, right: integer): integer;
var
pValue,aux: real;
store,i,pivot: integer;
begin
pivot := right;
pValue := a[pivot];
aux := a[right];a[right] := a[pivot];a[pivot] := aux; (* a[pivot] <-> a[right] *)
store := left;
for i := left to right -1 do
if a[i] <= pValue then
aux := a[store];a[store] := a[i];a[i]:=aux;
inc(store)
end
end;
aux := a[right];a[right] := a[store]; a[store] := aux;
return store
end Partition;
(* QuickSelect algorithm *)
procedure Select(a: Vector; left,right,k: integer;var r: real);
var
pIndex, pDist : integer;
begin
if left = right then r := a[left]; return end;
pIndex := Partition(a,left,right);
pDist := pIndex - left + 1;
if pDist = k then
r := a[pIndex];return
elsif k < pDist then
Select(a,left, pIndex - 1, k, r)
else
Select(a,pIndex + 1, right, k - pDist, r)
end
end Select;
procedure Median(a: Vector): real;
var
idx: integer;
r1,r2 : real;
begin
idx := len(a) div 2 + 1;
r1 := 0.0;r2 := 0.0;
Select(a,0,len(a) - 1,idx,r1);
if odd(len(a)) then return r1 end;
Select(a,0,len(a) - 1,idx - 1,r2);
return (r1 + r2) / 2;
end Median;
var
ary: Vector;
r: real;
begin
ary := new Vector(3);
ary := [5.0,3.0,4.0];
writeln(Median(ary):10:2);
ary := new Vector(4);
ary := [5.0,4.0,2.0,3.0];
writeln(Median(ary):10:2);
ary := new Vector(8);
ary := [3.0,4.0,1.0,-8.4,7.2,4.0,1.0,1.2];
writeln(Median(ary):10:2)
end Averages.
|
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
| #VBScript | VBScript |
Function arithmetic_mean(arr)
sum = 0
For i = 0 To UBound(arr)
sum = sum + arr(i)
Next
arithmetic_mean = sum / (UBound(arr)+1)
End Function
Function geometric_mean(arr)
product = 1
For i = 0 To UBound(arr)
product = product * arr(i)
Next
geometric_mean = product ^ (1/(UBound(arr)+1))
End Function
Function harmonic_mean(arr)
sum = 0
For i = 0 To UBound(arr)
sum = sum + (1/arr(i))
Next
harmonic_mean = (UBound(arr)+1) / sum
End Function
WScript.StdOut.WriteLine arithmetic_mean(Array(1,2,3,4,5,6,7,8,9,10))
WScript.StdOut.WriteLine geometric_mean(Array(1,2,3,4,5,6,7,8,9,10))
WScript.StdOut.WriteLine harmonic_mean(Array(1,2,3,4,5,6,7,8,9,10))
|
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
| #Phixmonti | Phixmonti | "[[]][]"
0 var acc
len for
get dup
'[' == if acc 1 + var acc endif
']' == if acc 1 - var acc endif
acc 0 < if exitfor endif
endfor
print
acc 0 < if
" is NOT ok"
else
" is OK"
endif
print |
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
| #Julia | Julia | dict = Dict('a' => 97, 'b' => 98) # list keys/values
# Dict{Char,Int64} with 2 entries:
# 'b' => 98
# 'a' => 97
dict = Dict(c => Int(c) for c = 'a':'d') # dict comprehension
# Dict{Char,Int64} with 4 entries:
# 'b' => 98
# 'a' => 97
# 'd' => 100
# 'c' => 99
dict['é'] = 233; dict # add an element
# Dict{Char,Int64} with 3 entries:
# 'b' => 98
# 'a' => 97
# 'é' => 233
emptydict = Dict() # create an empty dict
# Dict{Any,Any} with 0 entries
dict["a"] = 1 # type mismatch
# ERROR: MethodError: Cannot `convert` an object of type String to an object of type Char
typeof(dict) # type is infered correctly
# Dict{Char,Int64}
|
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
| #K | K | / creating an dictionary
d1:.((`foo;1); (`bar;2); (`baz;3))
/ extracting a value
d1[`bar]
2 |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #PicoLisp | PicoLisp | : (mapc println (1 2 3 4 5)) # Print numbers
1
2
3
4
5
-> 5
: (mapcar '((N) (* N N)) (1 2 3 4 5)) # Calculate squares
-> (1 4 9 16 25)
: (mapcar ** (1 2 3 4 5) (2 .)) # Same, using a circular list
-> (1 4 9 16 25)
: (mapcar if '(T NIL T NIL) '(1 2 3 4) '(5 6 7 8)) # Conditional function
-> (1 6 3 8) |
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.
| #Pike | Pike | int cube(int n)
{
return n*n*n;
}
array(int) a = ({ 1,2,3,4,5 });
array(int) b = cube(a[*]); // automap operator
array(int) c = map(a, cube); // conventional map 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
| #Stata | Stata | mata
// Create an associative array
a=asarray_create()
asarray(a,"one",1)
asarray(a,"two",2)
// Loop over entries
loc=asarray_first(a)
do {
printf("%s %f\n",asarray_key(a,loc),asarray_contents(a,loc))
loc=asarray_next(a,loc)
} while(loc!=NULL)
end |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Swift | Swift | let myMap = [
"hello": 13,
"world": 31,
"!" : 71 ]
// iterating over key-value pairs:
for (key, value) in myMap {
println("key = \(key), value = \(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
| #PureBasic | PureBasic | Procedure.d mean(List number())
Protected sum=0
ForEach number()
sum + number()
Next
ProcedureReturn sum / ListSize(number())
; Depends on programm if zero check needed, returns nan on division by zero
EndProcedure |
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
| #Python | Python | from math import fsum
def average(x):
return fsum(x)/float(len(x)) if x else 0
print (average([0,0,3,1,4,1,5,9,0,0]))
print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20])) |
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
| #Visual_Basic_.NET | Visual Basic .NET | Imports System.Runtime.CompilerServices
Module Module1
<Extension()>
Function Gmean(n As IEnumerable(Of Double)) As Double
Return Math.Pow(n.Aggregate(Function(s, i) s * i), 1.0 / n.Count())
End Function
<Extension()>
Function Hmean(n As IEnumerable(Of Double)) As Double
Return n.Count() / n.Sum(Function(i) 1.0 / i)
End Function
Sub Main()
Dim nums = From n In Enumerable.Range(1, 10) Select CDbl(n)
Dim a = nums.Average()
Dim g = nums.Gmean()
Dim h = nums.Hmean()
Console.WriteLine("Arithmetic mean {0}", a)
Console.WriteLine(" Geometric mean {0}", g)
Console.WriteLine(" Harmonic mean {0}", h)
Debug.Assert(a >= g AndAlso g >= h)
End Sub
End Module |
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #PHP | PHP | #!/usr/bin/php
<?php
# brackets generator
function bgenerate ($n) {
if ($n==0) return '';
$s = str_repeat('[', $n) . str_repeat(']', $n);
return str_shuffle($s);
}
function printbool($b) {return ($b) ? 'OK' : 'NOT OK';}
function isbalanced($s) {
$bal = 0;
for ($i=0; $i < strlen($s); $i++) {
$ch = substr($s, $i, 1);
if ($ch == '[') {
$bal++;
} else {
$bal--;
}
if ($bal < 0) return false;
}
return ($bal == 0);
}
# test parameters are N (see spec)
$tests = array(0, 2,2,2, 3,3,3, 4,4,4,4);
foreach ($tests as $v) {
$s = bgenerate($v);
printf("%s\t%s%s", $s, printbool(isbalanced($s)), PHP_EOL);
}
|
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
| #Kotlin | Kotlin | fun main(args: Array<String>) {
// map definition:
val map = mapOf("foo" to 5,
"bar" to 10,
"baz" to 15,
"foo" to 6)
// retrieval:
println(map["foo"]) // => 6
println(map["invalid"]) // => null
// check keys:
println("foo" in map) // => true
println("invalid" in map) // => false
// iterate over keys:
for (k in map.keys) print("$k ")
println()
// iterate over values:
for (v in map.values) print("$v ")
println()
// iterate over key, value pairs:
for ((k, v) in map) println("$k => $v")
} |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #PL.2FI | PL/I | declare x(5) initial (1,3,5,7,8);
x = sqrt(x);
x = sin(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.
| #PL.2FSQL | PL/SQL | -- Let's create a generic class with one method to be used as an interface:
CREATE OR REPLACE
TYPE callback AS OBJECT (
-- A class needs at least one member even though we don't use it
-- There's no generic OBJECT type, so let's call it NUMBER
dummy NUMBER,
-- Here's our function, and since PL/SQL doesn't have generics,
-- let's use type NUMBER for our params
MEMBER FUNCTION exec(n NUMBER) RETURN NUMBER
) NOT FINAL NOT instantiable;
/
-- Now let's inherit from that, defining a class with one method. We'll have ours square a number.
-- We can pass this class into any function that takes type callback:
CREATE OR REPLACE TYPE CB_SQUARE under callback (
OVERRIDING MEMBER FUNCTION exec(n NUMBER) RETURN NUMBER
)
/
CREATE OR REPLACE
TYPE BODY CB_SQUARE AS
OVERRIDING MEMBER FUNCTION exec(n NUMBER) RETURN NUMBER IS
BEGIN
RETURN n * n;
END exec;
END;
/
-- And a package to hold our test
CREATE OR REPLACE
PACKAGE PKG_CALLBACK AS
myCallback cb_square;
TYPE intTable IS TABLE OF NUMBER INDEX BY BINARY_INTEGER;
ints intTable;
i PLS_INTEGER;
PROCEDURE test_callback;
END PKG_CALLBACK;
/
CREATE OR REPLACE PACKAGE BODY PKG_CALLBACK AS
-- Our generic mapping function that takes a "method" and a collection
-- Note that it takes the generic callback type
-- that doesn't know anything about squaring
PROCEDURE do_callback(myCallback IN callback, ints IN OUT intTable) IS
i PLS_INTEGER;
myInt NUMBER;
BEGIN
FOR i IN 1 .. ints.COUNT LOOP
myInt := ints(i);
-- PL/SQL call's the child's method
ints(i) := myCallback.exec(myInt);
END LOOP;
END do_callback;
PROCEDURE test_callback IS
BEGIN
myCallback := cb_square(NULL);
FOR i IN 1..5 LOOP
ints(i) := i;
END LOOP;
do_callback(myCallback, ints);
i := ints.FIRST;
WHILE i IS NOT NULL LOOP
DBMS_OUTPUT.put_line(ints(i));
i := ints.next(i);
END LOOP;
END test_callback;
END PKG_CALLBACK;
/
BEGIN
PKG_CALLBACK.TEST_CALLBACK();
END;
/ |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Tcl | Tcl | array set myAry {
# list items here...
}
# Iterate over keys and values
foreach {key value} [array get myAry] {
puts "$key -> $value"
}
# Iterate over just keys
foreach key [array names myAry] {
puts "key = $key"
}
# There is nothing for directly iterating over just the values
# Use the keys+values version and ignore the keys |
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
| #TXR | TXR | (defvarl h (hash))
(each ((k '(a b c))
(v '(1 2 3)))
(set [h k] v))
(dohash (k v h)
(put-line `@k -> @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
| #Q | Q | mean:{(sum x)%count 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
| #Quackery | Quackery | [ $ 'bigrat.qky' loadfile ] now!
[ [] swap times
[ 20001 random 10000 -
n->v 100 n->v v/
join nested join ] ] is makevector ( --> [ )
[ witheach
[ unpack
2 point$ echo$
i 0 > if
[ say ", " ] ] ] is echodecs ( [ --> )
[ dup size n->v rot
0 n->v rot
witheach
[ unpack v+ ]
2swap v/ ] is arithmean ( [ --> n/d )
[ 5 makevector
say "Internal representation of a randomly generated vector" cr
say "of five rational numbers. They are distributed between" cr
say "-100.00 and +100.00 and are multiples of 0.01."
cr cr dup echo cr cr
say "Shown as decimal fractions."
cr cr dup echodecs cr cr
arithmean
say "Arithmetic mean of vector as a decimal fraction to" cr
say "5 places after the point, as a rounded proper" cr
say "fraction with the denominator not exceeding 10, and" cr
say "finally as a vulgar fraction without rounding." cr cr
2dup 5 point$ echo$
say ", "
2dup proper 10 round improper
proper$ echo$
say ", "
vulgar$ echo$ cr cr
say "The same, but with a vector of 9973 rational numbers," cr
say "20 decimal places and a denominator not exceeding 100." cr cr
9973 makevector arithmean
2dup 20 point$ echo$
say ", "
2dup proper 100 round improper
proper$ echo$
say ", "
vulgar$ echo$ cr ] is demonstrate ( --> ) |
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
| #Vlang | Vlang | import math
fn main() {
mut sum := 0.0
mut prod :=1.0
mut recip_sum := 0.0
n := 10
for val in 1..(n + 1) {
sum += val
prod *= val
recip_sum = recip_sum + ( 1.0 / val )
}
a := sum / n
g := math.pow( prod, ( 1.0 / f32(n) ) )
h := n / recip_sum
result := 'Arithmetic Mean: ${a:3.2f} \nGeometric Mean: ${g:3.2f}\nHarmonic Mean: ${h:3.2f}'
println( result )
compare := if a >= g && g >= h { "Yes" } else { "Nope" }
println('Is A >= G >= H? $compare')
} |
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
| #Picat | Picat | go1 ?=>
tests(Tests),
member(Test,Tests),
printf("%s: ", Test),
( balanced_brackets(Test) ->
println("OK")
;
println("NOT OK")
),
fail,
nl.
go1 => true.
% Check if a string of [] is balanced
balanced_brackets(B) =>
C = 0,
foreach(I in 1..B.length, C >= 0)
C:= C + cond(B[I] = '[', 1, -1)
end,
C == 0.
tests(["","[]", "[][]", "[[][]]", "][",
"][][", "[]][[]", "[][][][][][][][][][]",
"[[[[[[[]]]]]]]", "[[[[[[[]]]]]]",
"[][[]][]","[[][]][]", "[][][[]][]"]). |
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
| #Lambdatalk | Lambdatalk |
1) a (currently) reduced set of functions:
HASH: [5] [H.lib, H.new, H.disp, H.get, H.set!]
2) building an associative array: {def H key value | ...}
{def capitals
{H.new nyk New York, United States |
lon London, United Kingdom |
par Paris, France |
mos Moscou, Russia }}
-> capitals
3) displaying: {H.disp hash}
{H.disp {capitals}}
->
[
nyk: New York, United States
lon: London, United Kingdom
par: Paris, France
mos: Moscou, Russia
]
4) getting a value from a key: {H.get hash key}
{H.get {capitals} nyk} -> New York, United States
{H.get {capitals} lon} -> London, United Kingdom
{H.get {capitals} par} -> Paris, France
{H.get {capitals} mos} -> Moscou, Russia
5) adding a new (key,value): {H.set! hash key value}
{H.disp {H.set! {capitals} bar Barcelona, Catalunya}}
->
[
nyk: New York, United States
lon: London, United Kingdom
par: Paris, France
mos: Moscou, Russia
bar: Barcelona, Catalunya
]
6) editing a key
{H.disp
{H.set! {capitals}
nyk
{H.get {capitals} nyk} of America}} // adding "of America" to nyk
->
[
nyk: New York, United States of America
lon: London, United Kingdom
par: Paris, France
mos: Moscou, Russia
bar: Barcelona, Catalunya
]
|
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.
| #Pop11 | Pop11 | ;;; Define a procedure
define proc(x);
printf(x*x, '%p,');
enddefine;
;;; Create array
lvars ar = { 1 2 3 4 5};
;;; Apply procedure to array
appdata(ar, proc); |
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.
| #PostScript | PostScript | [1 2 3 4 5] { dup mul = } 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
| #UNIX_Shell | UNIX Shell | typeset -A a=([key1]=value1 [key2]=value2)
# just keys
printf '%s\n' "${!a[@]}"
# just values
printf '%s\n' "${a[@]}"
# keys and values
for key in "${!a[@]}"; do
printf '%s => %s\n' "$key" "${a[$key]}"
done |
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
| #Vala | Vala |
using Gee;
void main(){
// declare HashMap
var map = new HashMap<string, double?>();
// set 3 entries
map["pi"] = 3.14;
map["e"] = 2.72;
map["golden"] = 1.62;
// iterate over (key,value) pair
foreach (var elem in map.entries){
string name = elem.key;
double num = elem.value;
stdout.printf("%s,%f\n", name, num);
}
// iterate over keys
foreach (string key in map.keys){
stdout.printf("%s\n", key);
}
// iterate over values
foreach (double num in map.values){
stdout.printf("%f\n", num);
}
}
|
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
| #R | R | omean <- function(v) {
m <- mean(v)
ifelse(is.na(m), 0, m)
} |
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
| #Racket | Racket |
#lang racket
(require math)
(mean (in-range 0 1000)) ; -> 499 1/2
(mean '(2 2 4 4)) ; -> 3
(mean #(3 4 5 8)) ; -> 5
|
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
| #Wren | Wren | var rng = 1..10
var count = rng.count
var A = rng.reduce { |acc, x| acc + x }/count
var G = rng.reduce { |prod, x| prod * x}.pow(1/count)
var H = rng.reduce { |acc, x| acc + 1/x}.pow(-1) * count
System.print("For the numbers %(rng):")
System.print(" Arithmetic mean = %(A)")
System.print(" Geometric mean = %(G)")
System.print(" Harmonic mean = %(H)")
System.print(" A >= G >= H = %(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
| #PicoLisp | PicoLisp | (load "@lib/simul.l") # For 'shuffle'
(de generateBrackets (N)
(shuffle (make (do N (link "[" "]")))) )
(de checkBrackets (S)
(let N 0
(for C S
(if (= C "[")
(inc 'N)
(if2 (= C "]") (=0 N)
(off N)
(dec 'N) ) ) )
(=0 N) ) )
(for N 10
(prinl (if (checkBrackets (prin (generateBrackets N))) " OK" "not OK")) ) |
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
| #Lang5 | Lang5 | : dip swap '_ set execute _ ; : nip swap drop ;
: first 0 extract nip ; : second 1 extract nip ;
: assoc-in swap keys eq ;
: assoc-index' over keys swap eq [1] index collapse ;
: at swap assoc-index' subscript collapse second ;
: delete-at swap assoc-index' first remove ;
: keys 1 transpose first ;
: set-at
over 'dup dip assoc-in '+ reduce if 'dup dip delete-at then
"swap 2 compress 1 compress" dip swap append ;
[['foo 5]]
10 'bar rot set-at
'bar over at .
'hello 'bar rot set-at
20 'baz rot set-at . |
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
| #langur | langur | var .hash = h{1: "abc", "1": 789}
# may assign with existing or non-existing hash key (if hash is mutable)
.hash[7] = 49
writeln .hash[1]
writeln .hash[7]
writeln .hash["1"]
# using an alternate value in case of invalid index; prevents exception
writeln .hash[1; 42]
writeln .hash[2; 42] |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #PowerShell | PowerShell | 1..5 | ForEach-Object { $_ * $_ } |
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.
| #Prolog | Prolog | ?- assert((fun(X, Y) :- Y is 2 * X)).
true.
?- maplist(fun, [1,2,3,4,5], L).
L = [2,4,6,8,10].
|
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #VBA | VBA | Option Explicit
Sub Test()
Dim h As Object, i As Long, u, v, s
Set h = CreateObject("Scripting.Dictionary")
h.Add "A", 1
h.Add "B", 2
h.Add "C", 3
'Iterate on keys
For Each s In h.Keys
Debug.Print s
Next
'Iterate on values
For Each s In h.Items
Debug.Print s
Next
'Iterate on both keys and values by creating two arrays
u = h.Keys
v = h.Items
For i = 0 To h.Count - 1
Debug.Print u(i), v(i)
Next
End Sub |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #VBScript | VBScript |
'instantiate the dictionary object
Set dict = CreateObject("Scripting.Dictionary")
'populate the dictionary or hash table
dict.Add 1,"larry"
dict.Add 2,"curly"
dict.Add 3,"moe"
'iterate key and value pairs
For Each key In dict.Keys
WScript.StdOut.WriteLine key & " - " & dict.Item(key)
Next
|
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
| #Raku | Raku | multi mean([]){ Failure.new('mean on empty list is not defined') }; # Failure-objects are lazy exceptions
multi mean (@a) { ([+] @a) / @a } |
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
| #REBOL | REBOL | rebol [
Title: "Arithmetic Mean (Average)"
URL: http://rosettacode.org/wiki/Average/Arithmetic_mean
]
average: func [v /local sum][
if empty? v [return 0]
sum: 0
forall v [sum: sum + v/1]
sum / length? v
]
; Note precision loss as spread increased.
print [mold x: [] "->" average x]
print [mold x: [3 1 4 1 5 9] "->" average x]
print [mold x: [1000 3 1 4 1 5 9 -1000] "->" average x]
print [mold x: [1e20 3 1 4 1 5 9 -1e20] "->" average x] |
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
| #XPL0 | XPL0 | include c:\cxpl\codes;
func real Power(X, Y); \X raised to the Y power
real X, Y; \ (from StdLib.xpl)
return Exp(Y * Ln(X));
int N, Order;
real R, A, A1, G, G1, H, H1;
[A1:= 0.0; G1:= 1.0; H1:= 0.0;
Order:= true;
for N:= 1 to 10 do
[R:= float(N); \convert integer N to real R
A1:= A1 + R;
A:= A1/R; \arithmetic mean
G1:= G1 * R;
G:= Power(G1, 1.0/R); \geometric mean (Nth root of G1)
if G>A then Order:= false;
H1:= H1 + 1.0/R;
H:= R/H1; \harmonic mean
if H>G then Order:= false;
];
RlOut(0, A); CrLf(0);
RlOut(0, G); CrLf(0);
RlOut(0, H); CrLf(0);
if not Order then Text(0, "NOT ");
Text(0, "ALWAYS DECREASING ORDER
");
] |
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
| #PL.2FI | PL/I | *process m or(!) s attributes source;
cb: Proc Options(main);
/* PL/I program to check for balanced brackets [] ********************
* 07.12.2013 Walter Pachl translated from REXX Version 2
*********************************************************************/
Dcl v Char(20) Var;
Dcl (i,j) Bin Fixed(31);
Dcl r Bin Float(53);
Call testbal(''); /* first some user written tests */
Call testbal('[][][][[]]');
Call testbal('[][][][[]]][');
Call testbal('[');
Call testbal(']');
Call testbal('[]');
Call testbal('][');
Call testbal('][][');
Call testbal('[[]]');
Call testbal('[[[[[[[]]]]]]]');
Call testbal('[[[[[]]]][]');
Call testbal('[][]');
Call testbal('[]][[]');
Call testbal(']]][[[[]');
Call testbal('[[a]][b]');
Put Edit(' ')(Skip,a);
r=random(12345); /* then some generated ones */
Do i=1 To 10;
v='';
Do j=1 To 10;
r=random();
If r>0.5 Then v=v!!']';
Else v=v!!'[';
End;
Call testbal(v);
End;
Return;
testbal: Proc(s); /* test the given string and show result */
Dcl s Char(*);
Dcl yesno(0:1) Char(20) Var Init('unbalanced',' balanced');
Put Edit(yesno(checkbal(s)),''''!!s!!'''')(Skip,a,x(1),a);
End;
checkBal: proc(s) Returns(Bin Fixed(31));
/*check for balanced brackets [] */
Dcl s Char(*);
Dcl nest Bin Fixed(31) Init(0);
Dcl i Bin Fixed(31);
Do i=1 To length(s);
Select(substr(s,i,1));
When('[') nest+=1;
When(']') Do;
If nest=0 Then return(0);
nest-=1;
End;
Otherwise;
End;
End;
Return(nest=0);
End;
End; |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Lasso | Lasso | // In Lasso associative arrays are called maps
// Define an empty map
local(mymap = map)
// Define a map with content
local(mymap = map(
'one' = 'Monday',
'2' = 'Tuesday',
3 = 'Wednesday'
))
// add elements to an existing map
#mymap -> insert('fourth' = 'Thursday')
// retrieve a value from a map
#mymap -> find('2') // Tuesday
'<br />'
#mymap -> find(3) // Wednesday, found by the key not the position
'<br />'
// Get all keys from a map
#mymap -> keys // staticarray(2, fourth, one, 3)
'<br />'
// Iterate thru a map and get values
with v in #mymap do {^
#v
'<br />'
^}
// Tuesday<br />Thursday<br />Monday<br />Wednesday<br />
// Perform actions on each value of a map
#mymap -> foreach => {
#1 -> uppercase
#1 -> reverse
}
#mymap // map(2 = YADSEUT, fourth = YADSRUHT, one = YADNOM, 3 = YADSENDEW) |
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.
| #PureBasic | PureBasic | Procedure Cube(Array param.i(1))
Protected n.i
For n = 0 To ArraySize(param())
Debug Str(param(n)) + "^3 = " + Str(param(n) * param(n) * param(n))
Next
EndProcedure
Dim AnArray.i(4)
For n = 0 To ArraySize(AnArray())
AnArray(n) = Random(99)
Next
Cube(AnArray()) |
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.
| #Python | Python | def square(n):
return n * n
numbers = [1, 3, 5, 7]
squares1 = [square(n) for n in numbers] # list comprehension
squares2a = map(square, numbers) # functional form
squares2b = map(lambda x: x*x, numbers) # functional form with `lambda`
squares3 = [n * n for n in numbers] # no need for a function,
# anonymous or otherwise
isquares1 = (n * n for n in numbers) # iterator, lazy
import itertools
isquares2 = itertools.imap(square, numbers) # iterator, lazy |
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
| #Vim_Script | Vim Script | let dict = {"apples": 11, "oranges": 25, "pears": 4}
echo "Iterating over key-value pairs"
for [key, value] in items(dict)
echo key " => " value
endfor
echo "\n"
echo "Iterating over keys"
for key in keys(dict)
echo key
endfor
echo "\n"
echo "Iterating over values"
for value in values(dict)
echo value
endfor |
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
| #Vlang | Vlang | fn main() {
my_map := {
"hello": 13,
"world": 31,
"!" : 71 }
// iterating over key-value pairs:
for key, value in my_map {
println("key = $key, value = $value")
}
// iterating over keys:
for key,_ in my_map {
println("key = $key")
}
// iterating over values:
for _, value in my_map {
println("value = $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
| #Red | Red | Red ["Arithmetic mean"]
print average []
print average [2 3 5] |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #ReScript | ReScript | let arr = [3, 8, 4, 1, 5, 12]
let num = Js.Array.length(arr)
let tot = Js.Array.reduce(\"+", 0, arr)
let mean = float_of_int(tot) /. float_of_int(num)
Js.log(Js.Float.toString(mean)) |
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
| #zkl | zkl | ns:=T(1,2,3,4,5,6,7,8,9,10);
ns.sum(0.0)/ns.len(); // Arithmetic mean
ns.reduce('*,1.0).pow(1.0/ns.len()); // Geometric mean
ns.len().toFloat() / ns.reduce(fcn(p,n){ p + 1.0/n },0.0); // Harmonic mean |
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
| #PowerShell | PowerShell |
function Get-BalanceStatus ( $String )
{
$Open = 0
ForEach ( $Character in [char[]]$String )
{
switch ( $Character )
{
"[" { $Open++ }
"]" { $Open-- }
default { $Open = -1 }
}
# If Open drops below zero (close before open or non-allowed character)
# Exit loop
If ( $Open -lt 0 ) { Break }
}
$Status = ( "NOT OK", "OK" )[( $Open -eq 0 )]
return $Status
}
|
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
| #LFE | LFE |
(let* ((my-dict (: dict new))
(my-dict (: dict store 'key-1 '"value 1" my-dict))
(my-dict (: dict store 'key-2 '"value 2" my-dict)))
(: io format '"size: ~p~n" (list (: dict size my-dict)))
(: io format '"some data: ~p~n" (list (: dict fetch 'key-1 my-dict))))
|
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.
| #QB64 | QB64 |
'Task
'Take a combined set of elements and apply a function to each element.
'UDT
Type Friend
Names As String * 8
Surnames As String * 8
Age As Integer
End Type
Dim Friends(1 To 6) As Friend
Restore
FillArray
SearchForAdult Friends(), LBound(friends), UBound(friends)
End
Data "John","Beoz",13,"Will","Strange",22
Data "Arthur","Boile",16,"Peter","Smith",21
Data "Tom","Parker",14,"Tim","Wesson",24
Sub FillArray
Shared Friends() As Friend
Dim indeX As Integer
For indeX = LBound(friends) To UBound(friends) Step 1
Read Friends(indeX).Names, Friends(indeX).Surnames, Friends(indeX).Age
Next
End Sub
Sub SearchForAdult (F() As Friend, Min As Integer, Max As Integer)
Dim Index As Integer
Print "Friends with more than 18 years old"
For Index = Min To Max Step 1
If F(Index).Age > 18 Then Print F(Index).Names; " "; F(Index).Surnames; " "; F(Index).Age
Next Index
End Sub
|
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.
| #Quackery | Quackery | /O> [ 3 ** ] is cubed ( n --> n )
...
Stack empty.
/O> ' [ 1 2 3 4 5 6 7 8 9 10 ]
... [] swap witheach
... [ cubed join ]
...
Stack: [ 1 8 27 64 125 216 343 512 729 1000 ]
/O> drop
...
Stack empty.
/O> ' [ 1 2 3 4 5 6 7 8 9 10 ]
... dup witheach
... [ cubed swap i^ poke ]
...
Stack: [ 1 8 27 64 125 216 343 512 729 1000 ] |
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
| #Wart | Wart | h <- (table 'a 1 'b 2)
each (key val) table
prn key " " val |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Wren | Wren | // create a new map with four entries
var capitals = {
"France": "Paris",
"Germany": "Berlin",
"Russia": "Moscow",
"Spain": "Madrid"
}
// iterate through the map and print out the key/value pairs
for (c in capitals) System.print([c.key, c.value])
System.print()
// iterate though the map and print out just the keys
for (k in capitals.keys) System.print(k)
System.print()
// iterate though the map and print out just the values
for (v in capitals.values) System.print(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
| #REXX | REXX | /*REXX program finds the averages/arithmetic mean of several lists (vectors) or CL input*/
parse arg @.1; if @.1='' then do; #=6 /*vector from the C.L.?*/
@.1 = 10 9 8 7 6 5 4 3 2 1
@.2 = 10 9 8 7 6 5 4 3 2 1 0 0 0 0 .11
@.3 = '10 20 30 40 50 -100 4.7 -11e2'
@.4 = '1 2 3 4 five 6 7 8 9 10.1. ±2'
@.5 = 'World War I & World War II'
@.6 = /* ◄─── a null value. */
end
else #=1 /*number of CL vectors.*/
do j=1 for #
say ' numbers = ' @.j
say ' average = ' avg(@.j)
say copies('═', 79)
end /*t*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
avg: procedure; parse arg x; #=words(x) /*#: number of items.*/
if #==0 then return 'N/A: ───[null vector.]' /*No words? Return N/A*/
$=0
do k=1 for #; _=word(x,k) /*obtain a number. */
if datatype(_,'N') then do; $=$+_; iterate; end /*if numeric, then add*/
say left('',40) "***error*** non-numeric: " _; #=#-1 /*error; adjust number*/
end /*k*/
if #==0 then return 'N/A: ───[no numeric values.]' /*No nums? Return N/A*/
return $ / # /*return the average. */ |
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
| #Prolog | Prolog | rosetta_brackets :-
test_brackets([]),
test_brackets(['[',']']),
test_brackets(['[',']','[',']']),
test_brackets(['[','[',']','[',']',']']),
test_brackets([']','[']),
test_brackets([']','[',']','[']),
test_brackets(['[',']',']','[','[',']']).
balanced_brackets :-
gen_bracket(2, B1, []), test_brackets(B1),
gen_bracket(4, B2, []), test_brackets(B2),
gen_bracket(4, B3, []), test_brackets(B3),
gen_bracket(6, B4, []), test_brackets(B4),
gen_bracket(6, B5, []), test_brackets(B5),
gen_bracket(8, B6, []), test_brackets(B6),
gen_bracket(8, B7, []), test_brackets(B7),
gen_bracket(10, B8, []), test_brackets(B8),
gen_bracket(10, B9, []), test_brackets(B9).
test_brackets(Goal) :-
( Goal = [] -> write('(empty)'); maplist(write, Goal)),
( balanced_brackets(Goal, []) ->
writeln(' succeed')
;
writeln(' failed')
).
% grammar of balanced brackets
balanced_brackets --> [].
balanced_brackets -->
['['],
balanced_brackets,
[']'].
balanced_brackets -->
['[',']'],
balanced_brackets.
% generator of random brackets
gen_bracket(0) --> [].
gen_bracket(N) -->
{N1 is N - 1,
R is random(2)},
bracket(R),
gen_bracket(N1).
bracket(0) --> ['['].
bracket(1) --> [']'].
|
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Liberty_BASIC | Liberty BASIC |
data "red", "255 50 50", "green", "50 255 50", "blue", "50 50 255"
data "my fave", "220 120 120", "black", "0 0 0"
myAssocList$ =""
for i =1 to 5
read k$
read dat$
call sl.Set myAssocList$, k$, dat$
next i
print " Key 'green' is associated with data item "; sl.Get$( myAssocList$, "green")
|
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.
| #R | R | cube <- function(x) x*x*x
elements <- 1:5
cubes <- cube(elements) |
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.
| #Racket | Racket |
#lang racket
;; using the `for/vector' comprehension form
(for/vector ([i #(1 2 3 4 5)]) (sqr i))
;; the usual functional `map'
(vector-map sqr #(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
| #XPL0 | XPL0 | include c:\cxpl\stdlib;
char Dict(10,10);
int Entries;
proc AddEntry(Letter, Greek); \Insert entry into associative array
char Letter, Greek;
[Dict(Entries,0):= Letter;
StrCopy(Greek, @Dict(Entries,1));
Entries:= Entries+1; \(limit checks ignored for simplicity)
];
int I;
[Entries:= 0;
AddEntry(^A, "alpha");
AddEntry(^D, "delta");
AddEntry(^B, "beta");
AddEntry(^C, "gamma");
for I:= 0 to Entries-1 do
[ChOut(0, Dict(I,0)); ChOut(0, ^ ); Text(0, @Dict(I,1)); CrLf(0)];
] |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #zkl | zkl | var d=Dictionary("A","alpha","D","delta", "B","beta", "C", "gamma");
d.keys.pump(Console.print,fcn(k){String(k,",")})
d.values.apply("toUpper").println();
d.makeReadOnly(); // can only iterate over k,v pairs if read only
foreach k,v in (d){print(k,":",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
| #Ring | Ring |
nums = [1,2,3,4,5,6,7,8,9,10]
sum = 0
see "Average = " + average(nums) + nl
func average numbers
for i = 1 to len(numbers)
sum = sum + nums[i]
next
return sum/len(numbers)
|
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
| #RPL.2F2 | RPL/2 | 1 2 3 5 7
AMEAN
<< DEPTH DUP 'N' STO ->LIST ΣLIST N / >>
3.6 |
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
| #PureBasic | PureBasic | Procedure.s Generate(N)
For i=1 To N
sample$+"[]"
Next
For i=Len(sample$)-1 To 2 Step -1
r=Random(i-1)+1
If r<>i
a.c=PeekC(@sample$+r*SizeOf(Character))
b.c=PeekC(@sample$+i*SizeOf(Character))
PokeC(@sample$+r*SizeOf(Character), b)
PokeC(@sample$+i*SizeOf(Character), a)
EndIf
Next
ProcedureReturn sample$
EndProcedure
Procedure Balanced(String$)
Protected *p.Character, cnt
*p=@String$
While *p\c
If *p\c='['
cnt+1
ElseIf *p\c=']'
cnt-1
If cnt<0: Break: EndIf
EndIf
*p+SizeOf(Character)
Wend
If cnt=0
ProcedureReturn #True
EndIf
EndProcedure
;- Test code
OpenConsole()
For i=1 To 5
TestString$ = Generate(i)
Print(TestString$)
If Balanced(TestString$)
PrintN(" is balanced.")
Else
PrintN(" is not balanced")
EndIf
Next |
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
| #Lingo | Lingo | props = [#key1: "value1", #key2: "value2"]
put props[#key2]
-- "value2"
put props["key2"]
-- "value2"
put props.key2
-- "value2"
put props.getProp(#key2)
-- "value2" |
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
| #LiveCode | LiveCode | command assocArray
local tArray
put "value 1" into tArray["key 1"]
put 123 into tArray["key numbers"]
put "a,b,c" into tArray["abc"]
put "number of elements:" && the number of elements of tArray & return & \
"length of item 3:" && the length of tArray["abc"] & return & \
"keys:" && the keys of tArray
end assocArray |
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.
| #Raku | Raku | sub function { 2 * $^x + 3 };
my @array = 1 .. 5;
# via map function
.say for map &function, @array;
# via map method
.say for @array.map(&function);
# via for loop
for @array {
say function($_);
}
# via the "hyper" metaoperator and method indirection
say @array».&function;
# we neither need a variable for the array nor for the function
say [1,2,3]>>.&({ $^x + 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.
| #Raven | Raven | # To print the squared elements
[1 2 3 4 5] each dup * 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
| #Ruby | Ruby | def mean(nums)
nums.sum(0.0) / nums.size
end
nums = [3, 1, 4, 1, 5, 9]
nums.size.downto(0) do |i|
ary = nums[0,i]
puts "array size #{ary.size} : #{mean(ary)}"
end |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Run_BASIC | Run BASIC | print "Gimme the number in the array:";input numArray
dim value(numArray)
for i = 1 to numArray
value(i) = i * 1.5
next
for i = 1 to total
totValue = totValue +value(numArray)
next
if totValue <> 0 then mean = totValue/numArray
print "The mean is: ";mean |
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
| #Python | Python | >>> def gen(N):
... txt = ['[', ']'] * N
... random.shuffle( txt )
... return ''.join(txt)
...
>>> def balanced(txt):
... braced = 0
... for ch in txt:
... if ch == '[': braced += 1
... if ch == ']':
... braced -= 1
... if braced < 0: return False
... return braced == 0
...
>>> for txt in (gen(N) for N in range(10)):
... print ("%-22r is%s balanced" % (txt, '' if balanced(txt) else ' not'))
...
'' is balanced
'[]' is balanced
'[][]' is balanced
'][[[]]' is not balanced
'[]][[][]' is not balanced
'[][[][]]][' is not balanced
'][]][][[]][[' is not balanced
'[[]]]]][]][[[[' is not balanced
'[[[[]][]]][[][]]' is balanced
'][[][[]]][]]][[[[]' is not balanced |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.