task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Averages/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
#Prolog
Prolog
median(L, Z) :- length(L, Length), I is Length div 2, Rem is Length rem 2, msort(L, S), maplist(sumlist, [[I, Rem], [I, 1]], Mid), maplist(nth1, Mid, [S, S], X), sumlist(X, Y), Z is Y/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
#Processing
Processing
void setup() { float[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; println("Arithmetic mean: " + arithmeticMean(numbers)); println("Geometric mean: " + geometricMean(numbers)); println("Harmonic mean: " + harmonicMean(numbers)); }   float arithmeticMean(float[] nums) { float mean = 0; for (float n : nums) { mean += n; } mean = mean / nums.length; return mean; }   float geometricMean(float[] nums) { float mean = 1; for (float n : nums) { mean *= n; } mean = pow(mean, 1.0 / nums.length); return mean; }   float harmonicMean(float[] nums) { float mean = 0; for (float n : nums) { mean += 1 / n; } mean = nums.length / mean; return 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
#Lua
Lua
  function isBalanced(s) --Lua pattern matching has a 'balanced' pattern that matches sets of balanced characters. --Any two characters can be used. return s:gsub('%b[]','')=='' and true or false end   function randomString() math.randomseed(os.time()) math.random()math.random()math.random()math.random() local tokens={'[',']'} local result={} for i=1,8 do table.insert(result,tokens[math.random(1,2)]) end return table.concat(result) end   local RS=randomString() print(RS) print(isBalanced(RS))  
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
#Erlang
Erlang
  -module(assoc). -compile([export_all]).   test_create() -> D = dict:new(), D1 = dict:store(foo,1,D), D2 = dict:store(bar,2,D1), print_vals(D2), print_vals(dict:store(foo,3,D2)).   print_vals(D) -> lists:foreach(fun (K) -> io:format("~p: ~b~n",[K,dict:fetch(K,D)]) end, dict:fetch_keys(D)).  
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Rust
Rust
fn count_divisors(n: u64) -> usize { if n < 2 { return 1; } 2 + (2..=(n / 2)).filter(|i| n % i == 0).count() }   fn main() { println!("The first 20 anti-primes are:"); (1..) .scan(0, |max, n| { let d = count_divisors(n); Some(if d > *max { *max = d; Some(n) } else { None }) }) .flatten() .take(20) .for_each(|n| print!("{} ", n)); println!(); }
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Scala
Scala
def factorCount(num: Int): Int = Iterator.range(1, num/2 + 1).count(num%_ == 0) + 1 def antiPrimes: LazyList[Int] = LazyList.iterate((1: Int, 1: Int)){case (n, facs) => Iterator.from(n + 1).map(i => (i, factorCount(i))).dropWhile(_._2 <= facs).next}.map(_._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.
#Lasso
Lasso
define cube(n::integer) => #n*#n*#n   local( mynumbers = array(1, 2, 3, 4, 5), mycube = array )   #mynumbers -> foreach => { #mycube -> insert(cube(#1)) }   #mycube
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.
#Lisaac
Lisaac
+ a : ARRAY(INTEGER); + b : {INTEGER;};   a := ARRAY(INTEGER).create 1 to 3; 1.to 3 do { i : INTEGER; a.put i to i; };   b := { arg : INTEGER; (arg * arg).print; '\n'.print; };   a.foreach b;
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
#Objeck
Objeck
  class Iteration { function : Main(args : String[]) ~ Nil { assoc_array := Collection.StringMap->New(); assoc_array->Insert("Hello", IntHolder->New(1)); assoc_array->Insert("World", IntHolder->New(2)); assoc_array->Insert("!", IntHolder->New(3));   keys := assoc_array->GetKeys(); values := assoc_array->GetValues();   each(i : keys) { key := keys->Get(i)->As(String); value := assoc_array->Find(key)->As(IntHolder)->Get(); "key={$key}, value={$value}"->PrintLine(); };   "-------------"->PrintLine();   each(i : keys) { key := keys->Get(i)->As(String); value := values->Get(i)->As(IntHolder)->Get(); "key={$key}, value={$value}"->PrintLine(); }; } }  
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#Mathprog
Mathprog
  /*Arithmetic Mean of a large number of Integers - or - solve a very large constraint matrix over 1 million rows and columns Nigel_Galloway March 18th., 2008. */   param e := 20; set Sample := {1..2**e-1};   var Mean; var E{z in Sample};   /* sum of variances is zero */ zumVariance: sum{z in Sample} E[z] = 0;   /* Mean + variance[n] = Sample[n] */ variances{z in Sample}: Mean + E[z] = z;   solve;   printf "The arithmetic mean of the integers from 1 to %d is %f\n", 2**e-1, Mean;   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
#MATLAB
MATLAB
function meanValue = findmean(setOfValues) meanValue = mean(setOfValues); end
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches to this.   One is to sort the elements, and then pick the element(s) in the middle. Sorting would take at least   O(n logn).   Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s).   This would also take   O(n logn).   The best solution is to use the   selection algorithm   to find the median in   O(n)   time. See also Quickselect_algorithm Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#Pure
Pure
median x = (/(2-rem)) $ foldl1 (+) $ take (2-rem) $ drop (mid-(1-rem)) $ sort (<=) x when len = # x; mid = len div 2; rem = len mod 2; end;
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches to this.   One is to sort the elements, and then pick the element(s) in the middle. Sorting would take at least   O(n logn).   Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s).   This would also take   O(n logn).   The best solution is to use the   selection algorithm   to find the median in   O(n)   time. See also Quickselect_algorithm Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#PureBasic
PureBasic
Procedure.d median(Array values.d(1), length.i) If length = 0 : ProcedureReturn 0.0 : EndIf SortArray(values(), #PB_Sort_Ascending) If length % 2 ProcedureReturn values(length / 2) EndIf ProcedureReturn 0.5 * (values(length / 2 - 1) + values(length / 2)) EndProcedure   Procedure.i readArray(Array values.d(1)) Protected length.i, i.i Read.i length ReDim values(length - 1) For i = 0 To length - 1 Read.d values(i) Next ProcedureReturn i EndProcedure   Dim floats.d(0) Restore array1 length.i = readArray(floats()) Debug median(floats(), length) Restore array2 length.i = readArray(floats()) Debug median(floats(), length)   DataSection array1: Data.i 7 Data.d 4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2 array2: Data.i 6 Data.d 4.1, 7.2, 1.7, 9.3, 4.4, 3.2 EndDataSection
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
#PureBasic
PureBasic
Procedure.d ArithmeticMean() For a = 1 To 10 mean + a Next ProcedureReturn mean / 10 EndProcedure Procedure.d GeometricMean() mean = 1 For a = 1 To 10 mean * a Next ProcedureReturn Pow(mean, 1 / 10) EndProcedure Procedure.d HarmonicMean() For a = 1 To 10 mean.d + 1 / a Next ProcedureReturn 10 / mean EndProcedure   If HarmonicMean() <= GeometricMean() And GeometricMean() <= ArithmeticMean() Debug "true" EndIf Debug ArithmeticMean() Debug GeometricMean() Debug HarmonicMean()
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
#Maple
Maple
  > use StringTools in > IsBalanced( "", "[", "]" ); > IsBalanced( "[", "[", "]" ); > IsBalanced( "]", "[", "]" ); > IsBalanced( "[]", "[", "]" ); > IsBalanced( "][", "[", "]" ); > IsBalanced( "[][]", "[", "]" ); > IsBalanced( "[[][]]", "[", "]" ); > IsBalanced( "[[[]][]]]", "[", "]" ); > s := Random( 20, "[]" ); > IsBalanced( s, "[", "]" ) > end use; true   false   false   true   false   true   true   false   s := "[[]][[[[[[[[[]][][]]"   false  
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#F.23
F#
  let dic = System.Collections.Generic.Dictionary<string,string>() ;; dic.Add("key","val") ; dic.["key"] <- "new val" ;  
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Seed7
Seed7
$ include "seed7_05.s7i";   const func integer: countDivisors (in integer: number) is func result var integer: count is 1; local var integer: num is 0; begin for num range 1 to number div 2 do if number rem num = 0 then incr(count); end if; end for; end func;   const proc: main is func local var integer: maxDiv is 0; var integer: count is 0; var integer: number is 1; var integer: divisors is 1; begin writeln("The first 20 anti-primes are:"); while count < 20 do divisors := countDivisors(number); if divisors > maxDiv then write(number <& " "); maxDiv := divisors; incr(count); end if; incr(number); end while; writeln; end func;
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Sidef
Sidef
say with (0) {|max| 1..Inf -> lazy.grep { (.sigma0 > max) && (max = .sigma0) }.first(20) }
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.
#Logo
Logo
to square :x output :x * :x end show map "square [1 2 3 4 5]  ; [1 4 9 16 25] show map [? * ?] [1 2 3 4 5]  ; [1 4 9 16 25] foreach [1 2 3 4 5] [print square ?]  ; 1 4 9 16 25, one per line
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.
#Lua
Lua
myArray = {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
#Objective-C
Objective-C
NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:13], @"hello", [NSNumber numberWithInt:31], @"world", [NSNumber numberWithInt:71], @"!", nil];   // iterating over keys: for (id key in myDict) { NSLog(@"key = %@", key); }   // iterating over values: for (id value in [myDict objectEnumerator]) { NSLog(@"value = %@", value); }
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#OCaml
OCaml
#!/usr/bin/env ocaml   let map = [| ('A', 1); ('B', 2); ('C', 3) |] ;;   (* iterate over pairs *) Array.iter (fun (k,v) -> Printf.printf "key: %c - value: %d\n" k v) map ;;   (* iterate over keys *) Array.iter (fun (k,_) -> Printf.printf "key: %c\n" k) map ;;   (* iterate over values *) Array.iter (fun (_,v) -> Printf.printf "value: %d\n" v) map ;;   (* in functional programming it is often more useful to fold over the elements *) Array.fold_left (fun acc (k,v) -> acc ^ Printf.sprintf "key: %c - value: %d\n" k v) "Elements:\n" map ;;
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
#Maxima
Maxima
load("descriptive"); mean([2, 7, 11, 17]);
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
#MAXScript
MAXScript
fn mean data = ( total = 0 for i in data do ( total += i ) if data.count == 0 then 0 else total as float/data.count )   print (mean #(3, 1, 4, 1, 5, 9))
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches to this.   One is to sort the elements, and then pick the element(s) in the middle. Sorting would take at least   O(n logn).   Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s).   This would also take   O(n logn).   The best solution is to use the   selection algorithm   to find the median in   O(n)   time. See also Quickselect_algorithm Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#Python
Python
def median(aray): srtd = sorted(aray) alen = len(srtd) return 0.5*( srtd[(alen-1)//2] + srtd[alen//2])   a = (4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2) print a, median(a) a = (4.1, 7.2, 1.7, 9.3, 4.4, 3.2) print a, median(a)
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
#R
R
omedian <- function(v) { if ( length(v) < 1 ) NA else { sv <- sort(v) l <- length(sv) if ( l %% 2 == 0 ) (sv[floor(l/2)+1] + sv[floor(l/2)])/2 else sv[floor(l/2)+1] } }   a <- c(4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2) b <- c(4.1, 7.2, 1.7, 9.3, 4.4, 3.2)   print(median(a)) # 4.4 print(omedian(a)) print(median(b)) # 4.25 print(omedian(b))
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
#Python
Python
from operator import mul from functools import reduce     def amean(num): return sum(num) / len(num)     def gmean(num): return reduce(mul, num, 1)**(1 / len(num))     def hmean(num): return len(num) / sum(1 / n for n in num)     numbers = range(1, 11) # 1..10 a, g, h = amean(numbers), gmean(numbers), hmean(numbers) print(a, g, h) assert a >= g >= h
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
(* Generate open/close events. *) gen[n_] := RandomSample[Table[{1, -1}, {n}] // Flatten]   (* Check balance. *) check[lst_] := And @@ (# >= 0 & /@ Accumulate[lst])   (* Do task for string with n opening and n closing brackets. *) doString[n_] := ( lst = gen[n]; str = StringJoin[lst /. {1 -> "[", -1 -> "]"}]; Print[str <> If[match[lst, 0], " is balanced.", " is not balanced."]])
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Factor
Factor
H{ { "one" 1 } { "two" 2 } } { [ "one" swap at . ] [ 2 swap value-at . ] [ "three" swap at . ] [ [ 3 "three" ] dip set-at ] [ "three" swap at . ] } cleave
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Swift
Swift
extension BinaryInteger { @inlinable public func countDivisors() -> Int { var workingN = self var count = 1   while workingN & 1 == 0 { workingN >>= 1   count += 1 }   var d = Self(3)   while d * d <= workingN { var (quo, rem) = workingN.quotientAndRemainder(dividingBy: d)   if rem == 0 { var dc = 0   while rem == 0 { dc += count workingN = quo   (quo, rem) = workingN.quotientAndRemainder(dividingBy: d) }   count += dc }   d += 2 }   return workingN != 1 ? count * 2 : count } }   var antiPrimes = [Int]() var maxDivs = 0   for n in 1... { guard antiPrimes.count < 20 else { break }   let divs = n.countDivisors()   if maxDivs < divs { maxDivs = divs antiPrimes.append(n) } }   print("First 20 anti-primes are \(Array(antiPrimes))")
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Tcl
Tcl
  proc countDivisors {n} { if {$n < 2} {return 1} set count 2 set n2 [expr $n / 2] for {set i 2} {$i <= $n2} {incr i} { if {[expr $n % $i] == 0} {incr count} } return $count }   # main set maxDiv 0 set count 0   puts "The first 20 anti-primes are:" for {set n 1} {$count < 20} {incr n} { set d [countDivisors $n] if {$d > $maxDiv} { puts $n set maxDiv $d incr count } }  
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.
#M2000_Interpreter
M2000 Interpreter
  a=(1,2,3,4,5) b=lambda->{ push number**2 } Print a#map(b) ' 1 4 9 16 25 Print a#map(b, b) ' 1 16 81 256 625 b=lambda (z) ->{ =lambda z ->{ push number**z } } Print a#map(b(2)) ' 1 4 9 16 25 Print a#map(b(3)) ' 1 8 27 64 125   \\ second example a=(1,2,3,4,5) class s {sum=0} \\ s is a pointer to an instance of s() s->s() c=lambda s -> { push number+number s=>sum=stackitem() ' peek the value from stack } \\ c passed by value to fold(), but has a pointer to s Print a#fold(c, 100)=115 Print s=>sum=115    
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.
#M4
M4
define(`foreach', `pushdef(`$1')_foreach($@)popdef(`$1')')dnl define(`_arg1', `$1')dnl define(`_foreach', `ifelse(`$2', `()', `', `define(`$1', _arg1$2)$3`'$0(`$1', (shift$2), `$3')')')dnl dnl define(`apply',`foreach(`x',$1,`$2(x)')')dnl dnl define(`z',`eval(`$1*2') ')dnl apply(`(1,2,3)',`z')
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
#Ol
Ol
  ;;; create sample associative array (define aa (list->ff '( (hello . 1) (world . 2) (! . 3))))   (print aa) ; ==> #((! . 3) (hello . 1) (world . 2))   ;;; simplest iteration over all associative array (using ff-iter, lazy iterator) (let loop ((kv (ff-iter aa))) (cond ((null? kv) #true) ((pair? kv) (print (car kv)) (loop (cdr kv))) (else (loop (force kv))))) ; ==> (! . 3) ; ==> (hello . 1) ; ==> (world . 2)   ;;; iteration with returning value (using ff-fold) (print "folding result: " (ff-fold (lambda (result key value) (print "key: " key ", value: " value) (+ result 1)) 0 aa))   ; ==> key: !, value: 3 ; ==> key: hello, value: 1 ; ==> key: world, value: 2 ; ==> folding result: 3   ;;; same but right fold (using ff-foldr) (print "rfolding result: " (ff-foldr (lambda (result key value) (print "key: " key ", value: " value) (+ result 1)) 0 aa))   ; ==> key: world, value: 2 ; ==> key: hello, value: 1 ; ==> key: !, value: 3 ; ==> rfolding result: 3   ;;; at least create new array from existing (let's multiply every value by value) (define bb (ff-map aa (lambda (key value) (* value value)))) (print bb)   ; ==> #((! . 9) (hello . 1) (world . 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
#ooRexx
ooRexx
d = .directory~new d["hello"] = 1 d["world"] = 2 d["!"] = 3   -- iterating over keys: loop key over d say "key =" key end   -- iterating over values: loop value over d~allitems say "value =" value end   -- iterating over key-value pairs: s = d~supplier loop while s~available say "key =" s~index", value =" s~item s~next end
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#Mercury
Mercury
:- module arithmetic_mean. :- interface.   :- import_module io.   :- pred main(io::di, io::uo) is det.   :- implementation.   :- import_module float, list, require.   main(!IO) :- io.print_line(mean([1.0, 2.0, 3.0, 4.0, 5.0]), !IO).   :- func mean(list(float)) = float.   mean([]) = func_error("mean: emtpy list"). mean(Ns @ [_ | _]) = foldl((+), Ns, 0.0) / float(length(Ns)).   :- end_module arithmetic_mean.
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#min
min
(((0 (+) reduce) (size /)) cleave) :mean (2 3 5) mean print
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches to this.   One is to sort the elements, and then pick the element(s) in the middle. Sorting would take at least   O(n logn).   Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s).   This would also take   O(n logn).   The best solution is to use the   selection algorithm   to find the median in   O(n)   time. See also Quickselect_algorithm Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#Racket
Racket
#lang racket (define (median numbers) (define sorted (list->vector (sort (vector->list numbers) <))) (define count (vector-length numbers)) (if (zero? count) #f (/ (+ (vector-ref sorted (floor (/ (sub1 count) 2))) (vector-ref sorted (floor (/ count 2)))) 2)))   (median '#(5 3 4)) ;; 4 (median '#()) ;; #f (median '#(5 4 2 3)) ;; 7/2 (median '#(3 4 1 -8.4 7.2 4 1 1.2)) ;; 2.1
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches to this.   One is to sort the elements, and then pick the element(s) in the middle. Sorting would take at least   O(n logn).   Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s).   This would also take   O(n logn).   The best solution is to use the   selection algorithm   to find the median in   O(n)   time. See also Quickselect_algorithm Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#Raku
Raku
sub median { my @a = sort @_; return (@a[(*-1) div 2] + @a[* div 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
#Quackery
Quackery
[] 10 times [ i^ 1+ join ]   say "Arithmetic mean:" sp 0 over witheach + over size 8 point$ echo$ cr say " Geometric mean:" sp 1 over witheach * over size 80 ** * 10 root 10 8 ** 8 point$ echo$ cr say " Harmonic mean:" sp dup size dip [ 0 n->v rot witheach [ n->v 1/v v+ ] ] n->v 2swap v/ 8 point$ echo$
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
#R
R
  x <- 1: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
#MATLAB_.2F_Octave
MATLAB / Octave
function x = isbb(s) t = cumsum((s=='[') - (s==']')); x = all(t>=0) && (t(end)==0); 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
#Fantom
Fantom
  class Main { public static Void main () { // create a map which maps Ints to Strs, with given key-value pairs Int:Str map := [1:"alpha", 2:"beta", 3:"gamma"]   // create an empty map Map map2 := [:] // now add some numbers mapped to their doubles 10.times |Int i| { map2[i] = 2*i }   } }  
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Tiny_BASIC
Tiny BASIC
100 LET A=0 101 LET N=1 102 LET H=0 103 PRINT "The first 20 anti-primes are:" 105 GOSUB 150 106 LET H=F 107 LET A=A+1 108 PRINT N 109 LET N=N+1 110 IF A<20 THEN GOTO 105 111 END 150 GOSUB 200 151 IF F>H THEN RETURN 152 LET N=N+1 153 GOTO 150 200 LET F=0 201 LET C=1 205 IF N/C*C=N THEN LET F=F+1 206 LET C=C+1 207 IF C<=N THEN GOTO 205 208 RETURN  
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Transd
Transd
  #lang transd   MainModule: { countDivs: (λ n Int() ret_ Int() (= ret_ 2) (for i in Range(2 (to-Int (/ (to-Double n) 2) 1)) do (if (not (mod n i)) (+= ret_ 1))) (ret ret_) ),   _start: (λ max 0 tmp 0 N 1 i 2 (textout 1 " ") (while (< N 20) (= tmp (countDivs i)) (if (> tmp max) (textout i " ") (= max tmp) (+= N 1)) (+= i 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.
#Maple
Maple
  > map( sqrt, [ 1.1, 3.2, 5.7 ] ); [1.048808848, 1.788854382, 2.387467277]   > map( x -> x + 1, { 1, 3, 5 } ); {2, 4, 6}   > sqrt~( [ 1.1, 3.2, 5.7 ] ); [1.048808848, 1.788854382, 2.387467277]   > (x -> x + 1)~( { 1, 3, 5 } ); {2, 4, 6}  
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Mathematica.2F.2FWolfram_Language
Mathematica//Wolfram Language
(#*#)& /@ {1, 2, 3, 4} Map[Function[#*#], {1, 2, 3, 4}] Map[((#*#)&,{1,2,3,4}] Map[Function[w,w*w],{1,2,3,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
#Oz
Oz
declare MyMap = unit('hello':13 'world':31 '!':71) in {ForAll {Record.toListInd MyMap} Show} %% pairs {ForAll {Record.arity MyMap} Show} %% keys {ForAll {Record.toList MyMap} Show} %% values
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#MiniScript
MiniScript
arr = [ 1, 3, 7, 8, 9, 1 ]   avg = function(arr) avgNum = 0 for num in arr avgNum = avgNum + num end for return avgNum / arr.len end function   print avg(arr)
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
#.D0.9C.D0.9A-61.2F52
МК-61/52
0 П0 П1 С/П ИП0 ИП1 * + ИП1 1 + П1 / П0 БП 03
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
#REBOL
REBOL
  median: func [ "Returns the midpoint value in a series of numbers; half the values are above, half are below." block [any-block!] /local len mid ][ if empty? block [return none] block: sort copy block len: length? block mid: to integer! len / 2 either odd? len [ pick block add 1 mid ][ (block/:mid) + (pick block add 1 mid) / 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
#Racket
Racket
  #lang racket   (define (arithmetic xs) (/ (for/sum ([x xs]) x) (length xs)))   (define (geometric xs) (expt (for/product ([x xs]) x) (/ (length xs))))   (define (harmonic xs) (/ (length xs) (for/sum ([x xs]) (/ x))))   (define xs (range 1 11)) (arithmetic xs) (geometric xs) (harmonic xs) (>= (arithmetic xs) (geometric xs) (harmonic xs))  
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
#Maxima
Maxima
brack(s) := block( [n: slength(s), r: 0, c], catch( for i thru n do ( if cequal(c: charat(s, i), "]") then (if (r: r - 1) < 0 then throw(false)) elseif cequal(c, "[") then r: r + 1 ), is(r = 0) ) )$   brack(""); true   brack("["); false   brack("]"); false   brack("[]"); true   brack("]["); false   brack("[[][]]"); true   brack("[[[]][]]]"); false
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Forth
Forth
: get ( key len table -- data ) \ 0 if not present search-wordlist if >body @ else 0 then ;   : put ( data key len table -- ) >r 2dup r@ search-wordlist if r> drop nip nip >body ! else r> get-current >r set-current \ switch definition word lists nextname create , r> set-current then ; wordlist constant bar 5 s" alpha" bar put 9 s" beta" bar put 2 s" gamma" bar put s" alpha" bar get . \ 5 8 s" Alpha" bar put \ Forth dictionaries are normally case-insensitive s" alpha" bar get . \ 8
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Vala
Vala
int count_divisors(int n) { if (n < 2) return 1; var count = 2; for (int i = 2; i <= n/2; ++i) if (n%i == 0) ++count; return count; } void main() { var max_div = 0; var count = 0; stdout.printf("The first 20 anti-primes are:\n"); for (int n = 1; count < 20; ++n) { var d = count_divisors(n); if (d > max_div) { stdout.printf("%d ", n); max_div = d; count++; } } stdout.printf("\n"); }
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#MATLAB
MATLAB
>> array = [1 2 3 4 5]   array =   1 2 3 4 5   >> arrayfun(@sin,array)   ans =   Columns 1 through 4   0.841470984807897 0.909297426825682 0.141120008059867 -0.756802495307928   Column 5   -0.958924274663138   >> cellarray = {1,2,3,4,5}   cellarray =   [1] [2] [3] [4] [5]   >> cellfun(@tan,cellarray)   ans =   Columns 1 through 4   1.557407724654902 -2.185039863261519 -0.142546543074278 1.157821282349578   Column 5   -3.380515006246586
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
#PARI.2FGP
PARI/GP
keys = Vec(M);
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
#Perl
Perl
#! /usr/bin/perl use strict;   my %pairs = ( "hello" => 13, "world" => 31, "!" => 71 );   # iterate over pairs   # Be careful when using each(), however, because it uses a global iterator # associated with the hash. If you call keys() or values() on the hash in the # middle of the loop, the each() iterator will be reset to the beginning. If # you call each() on the hash somewhere in the middle of the loop, it will # skip over elements for the "outer" each(). Only use each() if you are sure # that the code inside the loop will not call keys(), values(), or each(). while ( my ($k, $v) = each %pairs) { print "(k,v) = ($k, $v)\n"; }   # iterate over keys foreach my $key ( keys %pairs ) { print "key = $key, value = $pairs{$key}\n"; } # or (see note about each() above) while ( my $key = each %pairs) { print "key = $key, value = $pairs{$key}\n"; }   # iterate over values foreach my $val ( values %pairs ) { print "value = $val\n"; }
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#Modula-2
Modula-2
PROCEDURE Avg;   VAR avg : REAL;   BEGIN avg := sx / n; InOut.WriteString ("Average = "); InOut.WriteReal (avg, 8, 2); InOut.WriteLn END Avg;
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
#MUMPS
MUMPS
MEAN(X)  ;X is assumed to be a list of numbers separated by "^" QUIT:'$DATA(X) "No data" QUIT:X="" "Empty Set" NEW S,I SET S=0,I=1 FOR QUIT:I>$L(X,"^") SET S=S+$P(X,"^",I),I=I+1 QUIT (S/$L(X,"^"))
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
#ReScript
ReScript
let median = (arr) => { let float_compare = (a, b) => { let diff = a -. b if diff == 0.0 { 0 } else if diff > 0.0 { 1 } else { -1 } } let _ = Js.Array2.sortInPlaceWith(arr, float_compare) let count = Js.Array.length(arr) // find the middle value, or the lowest middle value let middleval = ((count - 1) / 2) let median = if (mod(count, 2) != 0) { // odd number, middle is the median arr[middleval] } else { // even number, calculate avg of 2 medians let low = arr[middleval] let high = arr[middleval+1] ((low +. high) /. 2.0) } median }   Js.log(median([4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2])) Js.log(median([4.1, 7.2, 1.7, 9.3, 4.4, 3.2]))
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches to this.   One is to sort the elements, and then pick the element(s) in the middle. Sorting would take at least   O(n logn).   Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s).   This would also take   O(n logn).   The best solution is to use the   selection algorithm   to find the median in   O(n)   time. See also Quickselect_algorithm Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#REXX
REXX
/*REXX program finds the median of a vector (and displays the vector and median).*/ /* ══════════vector════════════ ══show vector═══ ════════show result═══════════ */ v= 1 9 2 4  ; say "vector" v; say 'median──────►' median(v); say v= 3 1 4 1 5 9 7 6  ; say "vector" v; say 'median──────►' median(v); say v= '3 4 1 -8.4 7.2 4 1 1.2'; say "vector" v; say 'median──────►' median(v); say v= -1.2345678e99 2.3e700 ; say "vector" v; say 'median──────►' median(v); say exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ eSORT: procedure expose @. #; parse arg $; #= words($) /*$: is the vector. */ do g=1 for #; @.g= word($, g); end /*g*/ /*convert list──►array*/ h=# /*#: number elements.*/ do while h>1; h= h % 2 /*cut entries by half.*/ do i=1 for #-h; j= i; k= h + i /*sort lower section. */ do while @.k<@.j; parse value @.j @.k with @.k @.j /*swap.*/ if h>=j then leave; j= j - h; k= k - h /*diminish J and K.*/ end /*while @.k<@.j*/ end /*i*/ end /*while h>1*/ /*end of exchange sort*/ return /*──────────────────────────────────────────────────────────────────────────────────────*/ median: procedure; call eSORT arg(1); m= # % 2 /*  % is REXX's integer division.*/ n= m + 1 /*N: the next element after M. */ if # // 2 then return @.n /*[odd?] // ◄───REXX's ÷ remainder*/ return (@.m + @.n) / 2 /*process an even─element vector. */
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
#Raku
Raku
sub A { ([+] @_) / @_ } sub G { ([*] @_) ** (1 / @_) } sub H { @_ / [+] 1 X/ @_ }   say "A(1,...,10) = ", A(1..10); say "G(1,...,10) = ", G(1..10); say "H(1,...,10) = ", H(1..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
#Mercury
Mercury
  :- module balancedbrackets. :- interface.   :- import_module io.   :- pred main(io::di, io::uo) is det.     :- import_module list, random, char.   :- pred brackets(int::in,list(char)::out,supply::mdi,supply::muo) is det.   :- pred imbalance(list(char)::in,int::out) is semidet. :- pred balanced(list(char)::in) is semidet.   :- implementation.   :- import_module int.   imbalance([],0). imbalance(['['|T],N) :- imbalance(T,N+1). imbalance([']'|T],N) :- N > 0, imbalance(T,N-1).   balanced(S) :- imbalance(S,0).   brackets(N,S,!RS) :- ( N < 1 -> S is []  ; random(0,2,R,!RS), ( R is 0 -> S is ['['|T], brackets(N-1,T,!RS) ; S is [']'|T], brackets(N-1,T,!RS))).   main(!IO) :- random.init(0,RS), brackets(4,S,RS,_), print(S,!IO), ( balanced(S) -> print(" is balanced\n",!IO)  ; print(" is unbalanced\n", !IO) ).  
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
#FreeBASIC
FreeBASIC
#define max(a, b) Iif(a>b,a,b)   enum datatype 'for this demonstration we'll allow these five data types BOOL STRNG BYYTE INTEG FLOAT end enum   union value bool as boolean strng as string*32 byyte as byte integ as integer float as double end union   type dicitem 'one part of the dictionary entry, either the key or the value datatype as datatype 'need to keep track of what kind of data it is value as value end type   type dicentry 'a dic entry has two things, a key and a value key as dicitem value as dicitem end type   sub add_dicentry( Dic() as dicentry, entry as dicentry ) redim preserve Dic(0 to max(ubound(Dic)+1,0)) Dic(ubound(Dic)) = entry return end sub   redim as dicentry Dictionary(-1) 'initialise a dictionary with no entries as yet   dim as dicentry thing1, thing2   'generate some test dictionary entries with thing1 with .key .datatype = STRNG .value.strng = "Cat" end with with .value .datatype = STRNG .value.strng = "Mittens" end with end with   with thing2 with .key .datatype = integ .value.integ = 32767 end with with .value .datatype = float .value.float = 2.718281828 end with end with   add_dicentry( Dictionary(), thing1 ) add_dicentry( Dictionary(), thing2 )   print Dictionary(0).value.value.strng print Dictionary(1).key.value.integ
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#VBA
VBA
Private Function factors(n As Integer) As Collection Dim f As New Collection For i = 1 To Sqr(n) If n Mod i = 0 Then f.Add i If n / i <> i Then f.Add n / i End If Next i f.Add n Set factors = f End Function Public Sub anti_primes() Dim n As Integer, maxd As Integer Dim res As New Collection, lenght As Integer Dim lf As Integer n = 1: maxd = -1 Length = 0 Do While res.count < 20 lf = factors(n).count If lf > maxd Then res.Add n maxd = lf End If n = n + IIf(n > 1, 2, 1) Loop Debug.Print "The first 20 anti-primes are:"; For Each x In res Debug.Print x; Next x End Sub
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Function CountDivisors(n As Integer) As Integer If n < 2 Then Return 1 End If Dim count = 2 '1 and n For i = 2 To n \ 2 If n Mod i = 0 Then count += 1 End If Next Return count End Function   Sub Main() Dim maxDiv, count As Integer Console.WriteLine("The first 20 anti-primes are:")   Dim n = 1 While count < 20 Dim d = CountDivisors(n)   If d > maxDiv Then Console.Write("{0} ", n) maxDiv = d count += 1 End If n += 1 End While   Console.WriteLine() End Sub   End Module
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.
#Maxima
Maxima
/* for lists or sets */   map(sin, [1, 2, 3, 4]); map(sin, {1, 2, 3, 4});   /* for matrices */   matrixmap(sin, matrix([1, 2], [2, 4]));
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.
#min
min
(1 2 3 4 5) (sqrt puts) foreach  ; print each square root (1 2 3 4 5) 'sqrt map  ; collect return values
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
#Phix
Phix
with javascript_semantics setd("one",1) setd(2,"duo") setd({3,4},{5,"six"}) function visitor(object key, object data, object /*userdata*/) ?{key,data} return 1 -- (continue traversal) end function traverse_dict(routine_id("visitor"))
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
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   def getd /# dict key -- dict data #/ swap 1 get rot find nip dup if swap 2 get rot get nip else drop "Unfound" endif enddef     def setd /# dict ( key data ) -- dict #/ 1 get var ikey 2 get var idata drop 1 get ikey find var p drop p if 2 get idata p set 2 set else 2 get idata 0 put 2 set 1 get ikey 0 put 1 set endif enddef     def pair /# dict n -- dict ( k d ) #/ 1 over 2 tolist var ikey 2 swap 2 tolist var idata ikey sget swap idata sget rot swap 2 tolist enddef   def scandict /# dict n -- dict ( ) #/ var n 1 get len nip for pair n if n get nip endif print nl endfor enddef   def pairs /# dict -- dict ( ) #/ 0 scandict enddef   def keys 1 scandict enddef   def values 2 scandict enddef   /# ---------- MAIN ---------- #/   ( ( ) ( ) )   ( "one" 1 ) setd ( 2 "duo" ) setd ( ( 3 4 ) ( 5 "six" ) ) setd   pairs nl keys nl values  
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#Nanoquery
Nanoquery
def sum(lst) sum = 0 for n in lst sum += n end return sum end   def average(x) return sum(x) / len(x) 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
#Nemerle
Nemerle
using System; using System.Console; using Nemerle.Collections;   module Mean { ArithmeticMean(x : list[int]) : double { |[] => 0.0 |_ =>(x.FoldLeft(0, _+_) :> double) / x.Length }   Main() : void { WriteLine("Mean of [1 .. 10]: {0}", ArithmeticMean($[1 .. 10])); } }
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
#Ring
Ring
  aList = [5,4,2,3] see "medium : " + median(aList) + nl   func median aray srtd = sort(aray) alen = len(srtd) if alen % 2 = 0 return (srtd[alen/2] + srtd[alen/2 + 1]) / 2.0 else return srtd[ceil(alen/2)] ok  
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
#Ruby
Ruby
def median(ary) return nil if ary.empty? mid, rem = ary.length.divmod(2) if rem == 0 ary.sort[mid-1,2].inject(:+) / 2.0 else ary.sort[mid] end end   p median([]) # => nil p median([5,3,4]) # => 4 p median([5,4,2,3]) # => 3.5 p median([3,4,1,-8.4,7.2,4,1,1.2]) # => 2.1
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of positive integers. The most common of the three means, the arithmetic mean, is the sum of the list divided by its length: A ( x 1 , … , x n ) = x 1 + ⋯ + x n n {\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}} The geometric mean is the n {\displaystyle n} th root of the product of the list: G ( x 1 , … , x n ) = x 1 ⋯ x n n {\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}} The harmonic mean is n {\displaystyle n} divided by the sum of the reciprocal of each item in the list: H ( x 1 , … , x n ) = n 1 x 1 + ⋯ + 1 x n {\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}} See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#REXX
REXX
/*REXX program computes and displays the Pythagorean means [Amean, Gmean, Hmean]. */ numeric digits 20 /*use a little extra for the precision.*/ parse arg n . /*obtain the optional argument from CL.*/ if n=='' | n=="," then n= 10 /*None specified? Then use the default*/ sum= 0; prod= 1; rSum= 0 /*initialize sum/product/reciprocal sum*/ $=; do #=1 for n; $= $ # /*generate list by appending # to list.*/ sum = sum + # /*compute the sum of all the elements. */ prod= prod * # /*compute the product of all elements. */ rSum= rSum + 1/# /*compute the sum of the reciprocals. */ end /*#*/ say ' list ='$ /*display the list of numbers used. */ say 'Amean =' sum / n /*calculate & display arithmetic mean.*/ say 'Gmean =' Iroot(prod, n) /* " " " geometric " */ if result=="[n/a]" then say '***error***: root' y "can't be even if 1st argument is < 0." say 'Hmean =' n / rSum /* " " " harmonic " */ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ Iroot: procedure; parse arg x 1 ox, y 1 oy /*get both args, and also a copy of X&Y*/ if x=0 | x=1 | y=1 then return x /*handle special case of zero and unity*/ if y=0 then return 1 /* " " " " a zero root.*/ if x<0 & y//2==0 then return '[n/a]' /*indicate result is "not applicable". */ x= abs(x); y= abs(y); m= y - 1 /*use the absolute value for X and Y. */ oDigs= digits(); a= oDigs + 5 /*save original digits; add five digs.*/ g= (x+1) / y*2 /*use this as the first guesstimate. */ d= 5 /*start with 5 dec digs, saves CPU time*/ do until d==a; d= min(d + d, a) /*keep going as digits are increased. */ numeric digits d; f= d - 2 /*limit digits to original digits + 5.*/ og= /*use a non─guess for the old G (guess)*/ do forever; gm= g**m /*keep computing at the Yth root. */ _= format( (m*g*gm + x)/(y*gm),,f) /*this is the nitty─gritty calculation.*/ if _=g | _=og then leave /*are we close enough yet? */ og= g; g= _ /*save guess ──► OG; set the new guess.*/ end /*forever*/ end /*until */   g= g * sign(ox); if oy<0 then g= 1 / g /*adjust for original X sign; neg. root*/ numeric digits oDigs; return g / 1 /*normalize to original decimal digits.*/
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
#MiniScript
MiniScript
isBalanced = function(str) level = 0 for c in str if c == "[" then level = level + 1 if c == "]" then level = level - 1 if level < 0 then return false end for return level == 0 end function
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
#Free_Pascal
Free Pascal
program AssociativeArrayCreation; {$IFDEF FPC}{$MODE DELPHI}{$ENDIF} {$IFDEF WINDOWS}{$APPTYPE CONSOLE}{$ENDIF} uses Generics.Collections; var lDictionary: TDictionary<string, Integer>; begin lDictionary := TDictionary<string, Integer>.Create; try lDictionary.Add('foo', 5); lDictionary.Add('bar', 10); lDictionary.Add('baz', 15); lDictionary.AddOrSetValue('foo', 6); // replaces value if it exists finally lDictionary.Free; end; end.
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Vlang
Vlang
fn count_divisors(n int) int { if n < 2 { return 1 } mut count := 2 // 1 and n for i := 2; i <= n/2; i++ { if n%i == 0 { count++ } } return count }   fn main() { println("The first 20 anti-primes are:") mut max_div := 0 mut count := 0 for n := 1; count < 20; n++ { d := count_divisors(n) if d > max_div { print("$n ") max_div = d count++ } } println('') }
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Wren
Wren
import "/math" for Int   System.print("The first 20 anti-primes are:") var maxDiv = 0 var count = 0 var n = 1 while (count < 20) { var d = Int.divisors(n).count if (d > maxDiv) { System.write("%(n) ") maxDiv = d count = count + 1 } n = n + 1 } System.print()
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.
#Modula-3
Modula-3
MODULE Callback EXPORTS Main;   IMPORT IO, Fmt;   TYPE CallBack = PROCEDURE (a: CARDINAL; b: INTEGER); Values = REF ARRAY OF INTEGER;   VAR sample := ARRAY [1..5] OF INTEGER {5, 4, 3, 2, 1}; callback := Display;   PROCEDURE Display(loc: CARDINAL; val: INTEGER) = BEGIN IO.Put("array[" & Fmt.Int(loc) & "] = " & Fmt.Int(val * val) & "\n"); END Display;   PROCEDURE Map(VAR values: ARRAY OF INTEGER; size: CARDINAL; worker: CallBack) = VAR lvalues := NEW(Values, size); BEGIN FOR i := FIRST(lvalues^) TO LAST(lvalues^) DO worker(i, values[i]); END; END Map;   BEGIN Map(sample, NUMBER(sample), callback); END Callback.
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
#PHP
PHP
<?php $pairs = array( "hello" => 1, "world" => 2, "!" => 3 );   // iterate over key-value pairs foreach($pairs as $k => $v) { echo "(k,v) = ($k, $v)\n"; }   // iterate over keys foreach(array_keys($pairs) as $key) { echo "key = $key, value = $pairs[$key]\n"; }   // iterate over values foreach($pairs as $value) { echo "values = $value\n"; } ?>
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
#Picat
Picat
go => Map = new_map([1=one,2=two,3=three,4=four]), foreach(K=V in Map) println(K=V) end, nl,   println(keys=Map.keys), foreach(K in Map.keys.sort) println(K=Map.get(K)) end, nl,   println(values=Map.values), foreach(V in Map.values.sort)  % This works but gets a warning: nonlocal_var_in_iterator_pattern  % println(V=[K : K=V in Map])    % No warning: println(V=[K : K=V1 in Map,V1 == V]) end, nl.
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
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   launchSample() return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method arithmeticMean(vv = Vector) public static signals DivideException returns Rexx sum = 0 n_ = Rexx loop n_ over vv sum = sum + n_ end n_ mean = sum / vv.size()   return mean   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method launchSample() public static TRUE_ = 1 == 1 FALSE_ = \TRUE_ tracing = FALSE_ vectors = getSampleData() loop v_ = 0 to vectors.length - 1 say 'Average of:' vectors[v_].toString() do say ' =' arithmeticMean(vectors[v_]) catch dex = DivideException say 'Caught "Divide By Zero"; bypassing...' if tracing then dex.printStackTrace() catch xex = RuntimeException say 'Caught unspecified run-time exception; bypassing...' if tracing then xex.printStackTrace() end say end v_ return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method getSampleData() private static returns Vector[] seed = 1066 rng = Random(seed) vectors =[ - Vector(Arrays.asList([Rexx 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])), - Vector(), - Vector(Arrays.asList([Rexx rng.nextInt(seed), rng.nextInt(seed), rng.nextInt(seed), rng.nextInt(seed), rng.nextInt(seed), rng.nextInt(seed)])), - Vector(Arrays.asList([Rexx rng.nextDouble(), rng.nextDouble(), rng.nextDouble(), rng.nextDouble(), rng.nextDouble(), rng.nextDouble(), rng.nextDouble()])), - Vector(Arrays.asList([Rexx '1.0', '2.0', 3.0])), - Vector(Arrays.asList([Rexx '1.0', 'not a number', 3.0])) - ] return vectors  
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
#Run_BASIC
Run BASIC
sqliteconnect #mem, ":memory:" mem$ = "CREATE TABLE med (x float)" #mem execute(mem$)   a$ ="4.1,5.6,7.2,1.7,9.3,4.4,3.2" :gosub [median] a$ ="4.1,7.2,1.7,9.3,4.4,3.2" :gosub [median] a$ ="4.1,4,1.2,6.235,7868.33" :gosub [median] a$ ="1,5,3,2,4" :gosub [median] a$ ="1,5,3,6,4,2" :gosub [median] a$ ="4.4,2.3,-1.7,7.5,6.6,0.0,1.9,8.2,9.3,4.5"  :gosub [median]' end [median] #mem execute("DELETE FROM med") for i = 1 to 100 v$ = word$( a$, i, ",") if v$ = "" then exit for mem$ = "INSERT INTO med values(";v$;")" #mem execute(mem$) next i mem$ = "SELECT AVG(x) as median FROM (SELECT x FROM med ORDER BY x LIMIT 2 - (SELECT COUNT(*) FROM med) % 2 OFFSET (SELECT (COUNT(*) - 1) / 2 FROM med))"   #mem execute(mem$) #row = #mem #nextrow() median = #row median() print " Median :";median;chr$(9);" Values:";a$   RETURN
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
#Rust
Rust
fn median(mut xs: Vec<f64>) -> f64 { // sort in ascending order, panic on f64::NaN xs.sort_by(|x,y| x.partial_cmp(y).unwrap() ); let n = xs.len(); if n % 2 == 0 { (xs[n/2] + xs[n/2 - 1]) / 2.0 } else { xs[n/2] } }   fn main() { let nums = vec![2.,3.,5.,0.,9.,82.,353.,32.,12.]; println!("{:?}", median(nums)) }
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
#Ring
Ring
  decimals(8) array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] see "arithmetic mean = " + arithmeticMean(array) + nl see "geometric mean = " + geometricMean(array) + nl see "harmonic mean = " + harmonicMean(array) + nl   func arithmeticMean a return summary(a) / len(a)   func geometricMean a b = 1 for i = 1 to len(a) b *= a[i] next return pow(b, (1/len(a)))   func harmonicMean a b = list(len(a)) for nr = 1 to len(a) b[nr] = 1/a[nr] next return len(a) / summary(b)   func summary s sum = 0 for n = 1 to len(s) sum += s[n] next return sum  
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#Modula-2
Modula-2
  MODULE Brackets; IMPORT IO, Lib;   CONST MaxN = 4;   PROCEDURE DoTest( N : CARDINAL); VAR brStr : ARRAY [0..2*MaxN] OF CHAR; (* string of brackets *) verdict : ARRAY [0..2] OF CHAR; br : CHAR; k, nL, nR, randNum : CARDINAL; count : INTEGER; BEGIN k := 0; (* index into brStr *) nL := N; nR := N; (* number of left/right brackets remaining *) WHILE (nL > 0) AND (nR > 0) DO randNum := Lib.RANDOM( nL + nR); IF (randNum < nL) THEN brStr[k] := '['; DEC(nL); ELSE brStr[k] := ']'; DEC(nR); END; INC(k); END; (* Here when only one kind of bracket is possible *) IF (nL = 0) THEN br := ']' ELSE br := '['; END; WHILE (k < 2*N) DO brStr[k] := br; INC(k); END; brStr[k] := 0C; (* null to mark end of string *)   (* Test for balance *) count := 0; k := 0; REPEAT IF brStr[k] = '[' THEN INC( count) ELSE DEC( count) END; INC( k); UNTIL (count < 0) OR (k = 2*N); IF (count < 0) THEN verdict := 'no' ELSE verdict := 'yes' END; IO.WrStr( brStr); IO.WrStr(' '); IO.WrStr( verdict); IO.WrLn; END DoTest;   (* Main routine *) VAR j : CARDINAL; BEGIN Lib.RANDOMIZE; FOR j := 1 TO 10 DO DoTest( Lib.RANDOM(MaxN) + 1); END; END Brackets.  
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
#Futhark
Futhark
let associative_array = {key1=1,key2=2}
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#XPL0
XPL0
int Counter, Num, Cnt, Div, Max; [Counter:= 0; Max:= 0; Num:= 1; loop [Cnt:= 0; Div:= 1; repeat if rem(Num/Div) = 0 then Cnt:= Cnt+1; Div:= Div+1; until Div > Num; if Cnt > Max then [IntOut(0, Num); ChOut(0, ^ ); Max:= Cnt; Counter:= Counter+1; if Counter >= 20 then quit; ]; Num:= Num+1; ]; ]
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Yabasic
Yabasic
print "The first 20 anti-primes are:"   while (count < 20) n = n + 1 d = count_divisors(n) if d > max_divisors then print n; max_divisors = d count = count + 1 end if wend print   sub count_divisors(n) local count, i   if n < 2 return 1   count = 2 for i = 2 to n/2 if not(mod(n, i)) count = count + 1 next return count 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.
#Nanoquery
Nanoquery
// create a list of numbers 1-10 numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}   // display the list as it is println numbers   // square each element in the list for i in range(1, len(numbers) - 1) numbers[i] = numbers[i] * numbers[i] end   // display the squared list println numbers
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.
#Nemerle
Nemerle
def seg = array[1, 2, 3, 5, 8, 13]; def squares = seq.Map(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
#PicoLisp
PicoLisp
(put 'A 'foo 5) (put 'A 'bar 10) (put 'A 'baz 15)   : (getl 'A) # Get the whole property list -> ((15 . baz) (10 . bar) (5 . foo))   : (mapcar cdr (getl 'A)) # Get all keys -> (baz bar foo)   : (mapcar car (getl 'A)) # Get all values -> (15 10 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
#Pike
Pike
  mapping(string:string) m = ([ "A":"a", "B":"b", "C":"c" ]); foreach(m; string key; string value) { write(key+value); } Result: BbAaCc   // only keys foreach(m; string key;) { write(key); } Result: BAC   // only values foreach(m;; string value) { write(value); } Result: bac    
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
#NewLISP
NewLISP
(define (Mean Lst) (if (empty? Lst) 0 (/ (apply + Lst) (length Lst))))   (Mean (sequence 1 1000))-> 500 (Mean '()) -> 0
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
#Nial
Nial
mean is / [sum, tally]   mean 6 2 4 = 4
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
#Scala
Scala
def median[T](s: Seq[T])(implicit n: Fractional[T]) = { import n._ val (lower, upper) = s.sortWith(_<_).splitAt(s.size / 2) if (s.size % 2 == 0) (lower.last + upper.head) / fromInt(2) else upper.head }
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
#Ruby
Ruby
class Array def arithmetic_mean inject(0.0, :+) / length end   def geometric_mean inject(:*) ** (1.0 / length) end   def harmonic_mean length / inject(0.0) {|s, m| s + 1.0/m} end end   class Range def method_missing(m, *args) case m when /_mean$/ then to_a.send(m) else super end end end   p a = (1..10).arithmetic_mean p g = (1..10).geometric_mean p h = (1..10).harmonic_mean # is h < g < a ?? p g.between?(h, a)
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
#Nanoquery
Nanoquery
import Nanoquery.Util   def gen(N) txt = {"[", "]"} * N txt = new(Random).shuffle(txt) return "".join("", txt) end   def balanced(txt) braced = 0 for ch in txt if ch = "[" braced += 1 else if ch = "]" braced -= 1 end   if braced < 0 return false end end return braced = 0 end   // unlike Python, the range function is inclusive in Nanoquery for N in range(1, 10) txt = gen(N) if balanced(txt) println format("%-22s is balanced", txt) else println format("%-22s is not balanced", txt) end end