task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element ins...
#Gambas
Gambas
// declare a nil map variable, for maps from string to int var x map[string]int   // make an empty map x = make(map[string]int)   // make an empty map with an initial capacity x = make(map[string]int, 42)   // set a value x["foo"] = 3   // getting values y1 := x["bar"] // zero value returned if no map entry exists ...
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#zkl
zkl
fcn properDivsN(n) //--> count of proper divisors. 1-->1, wrong but OK here { [1.. (n + 1)/2 + 1].reduce('wrap(p,i){ p + (n%i==0 and n!=i) }) } fcn antiPrimes{ // -->iterator Walker.chain([2..59],[60..*,30]).tweak(fcn(c,rlast){ last,mx := rlast.value, properDivsN(c); if(mx<=last) return(Void.Skip); ...
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#NetLogo
NetLogo
  ;; NetLogo “anonymous procedures” ;; stored in a variable, just to show it can be done. let callback [ [ x ] x * x ] show (map callback [ 1 2 3 4 5 ])  
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#NewLISP
NewLISP
> (map (fn (x) (* x x)) '(1 2 3 4)) (1 4 9 16)  
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#PostScript
PostScript
  % over keys and values <</a 1 /b 2 /c 3>> {= =} forall % just keys <</a 1 /b 2 /c 3>> {= } forall % just values <</a 1 /b 2 /c 3>> {pop =} forall  
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Potion
Potion
mydictionary = (red=0xff0000, green=0x00ff00, blue=0x0000ff)   mydictionary each (key, val): (key, ":", val, "\n") join print. mydictionary each (key): (key, "\n") join print.
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#Nim
Nim
import strutils   proc mean(xs: openArray[float]): float = for x in xs: result += x result = result / float(xs.len)   var v = @[1.0, 2.0, 2.718, 3.0, 3.142] for i in 0..5: echo "mean of first ", v.len, " = ", formatFloat(mean(v), precision = 0) if v.len > 0: v.setLen(v.high)
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#Niue
Niue
  [ [ , len 1 - at ! ] len 3 - times swap , ] 'map ; ( a Lisp like map, to sum the stack ) [ len 'n ; [ + ] 0 n swap-at map n / ] 'avg ;   1 2 3 4 5 avg . => 3 3.4 2.3 .01 2.0 2.1 avg . => 1.9619999999999997  
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#Scheme
Scheme
(define (median l) (* (+ (list-ref (bubble-sort l >) (round (/ (- (length l) 1) 2))) (list-ref (bubble-sort l >) (round (/ (length l) 2)))) 0.5))
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i";   const type: floatList is array float;   const func float: median (in floatList: floats) is func result var float: median is 0.0; local var floatList: sortedFloats is 0 times 0.0; begin sortedFloats := sort(floats); if odd(length(sortedFloats)) the...
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 p...
#Run_BASIC
Run BASIC
bXsum = 1 for i = 1 to 10 sum = sum + i ' sum of 1 -> 10 bXsum = bXsum * i ' sum i * i sum1i = sum1i + (1/i) ' sum 1/i next   average = sum / 10 geometric = bXsum ^ (1/10) harmonic = 10/sum1i   print "ArithmeticMean:";average print "Geometric Mean:";geometric print...
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) ...
#Nim
Nim
  from random import random, randomize, shuffle from strutils import repeat   randomize()   proc gen(n: int): string = result = "[]".repeat(n) shuffle(result)   proc balanced(txt: string): bool = var b = 0 for c in txt: case c of '[': inc(b) of ']': dec(b) if b < 0: return false ...
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 ins...
#Go
Go
// declare a nil map variable, for maps from string to int var x map[string]int   // make an empty map x = make(map[string]int)   // make an empty map with an initial capacity x = make(map[string]int, 42)   // set a value x["foo"] = 3   // getting values y1 := x["bar"] // zero value returned if no map entry exists ...
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#NGS
NGS
{ [1, 2, 3, 4, 5].map(F(x) x*x) }
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Nial
Nial
each (* [first, first] ) 1 2 3 4 =1 4 9 16
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#PowerShell
PowerShell
$h = @{ 'a' = 1; 'b' = 2; 'c' = 3 }
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Prolog
Prolog
  assert( mymap(key1,value1) ). assert( mymap(key2,value1) ).  
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#Oberon-2
Oberon-2
  MODULE AvgMean; IMPORT Out; CONST MAXSIZE = 10; PROCEDURE Avg(a: ARRAY OF REAL; items: INTEGER): REAL; VAR i: INTEGER; total: REAL; BEGIN total := 0.0; FOR i := 0 TO LEN(a) - 1 DO total := total + a[i] END; RETURN total/LEN(a) END Avg; VAR ary: ARRAY MAXSIZE OF REAL; BEGIN ary[0] := 10.0; ary[1] := 11.01;...
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 ...
#SenseTalk
SenseTalk
put the median of [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2] put the median of [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2, 6.6]   put customMedian of [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2] put customMedian of [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2, 6.6]   to handle customMedian of list sort list if the number of items in list is an even n...
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#Sidef
Sidef
func median(arry) { var srtd = arry.sort; var alen = srtd.length; srtd[(alen-1)/2]+srtd[alen/2] / 2; }
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#Rust
Rust
fn main() { let mut sum = 0.0; let mut prod = 1; let mut recsum = 0.0; for i in 1..11{ sum += i as f32; prod *= i; recsum += 1.0/(i as f32); } let avg = sum/10.0; let gmean = (prod as f32).powf(0.1); let hmean = 10.0/recsum; println!("Average: {}, Geometric m...
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 p...
#Scala
Scala
def arithmeticMean(n: Seq[Int]) = n.sum / n.size.toDouble def geometricMean(n: Seq[Int]) = math.pow(n.foldLeft(1.0)(_*_), 1.0 / n.size.toDouble) def harmonicMean(n: Seq[Int]) = n.size / n.map(1.0 / _).sum   var nums = 1 to 10 var a = arithmeticMean(nums) var g = geometricMean(nums) var h = harmonicMean(nums)   print...
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) ...
#Oberon-2
Oberon-2
  MODULE BalancedBrackets; IMPORT Object, Object:Boxed, ADT:LinkedList, ADT:Storable, IO, Out := NPCT:Console;   TYPE (* CHAR is not boxed in the standard lib *) (* so make a boxed char *) Character* = POINTER TO CharacterDesc; CharacterDesc* = RECORD (Boxed.ObjectDesc) c: CHAR; END;   (*...
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 ins...
#Gosu
Gosu
// empty map var emptyMap = new HashMap<String, Integer>()   // map initialization var map = {"Scott"->50, "Carson"->40, "Luca"->30, "Kyle"->38}   // map key/value assignment map["Scott"] = 51   // get a value var x = map["Scott"]   // remove an entry map.remove("Scott")   // loop and maps for(entry in map.entrySet()) ...
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Nim
Nim
var arr = @[1,2,3,4] arr.apply proc(some: var int) = echo(some, " squared = ", some*some)
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Oberon-2
Oberon-2
  MODULE ApplyCallBack; IMPORT Out := NPCT:Console;   TYPE Fun = PROCEDURE (x: LONGINT): LONGINT; Ptr2Ary = POINTER TO ARRAY OF LONGINT;   VAR a: ARRAY 5 OF LONGINT; x: ARRAY 3 OF LONGINT; r: Ptr2Ary;   PROCEDURE Min(x,y: LONGINT): LONGINT; BEGIN IF x <= y THEN RETURN x ELSE RETURN y END; END Min;...
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 ...
#PureBasic
PureBasic
NewMap dict.s() dict("de") = "German" dict("en") = "English" dict("fr") = "French"   ForEach dict() Debug MapKey(dict()) + ":" + dict() Next
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Python
Python
myDict = { "hello": 13, "world": 31, "!"  : 71 }   # iterating over key-value pairs: for key, value in myDict.items(): print ("key = %s, value = %s" % (key, value))   # iterating over keys: for key in myDict: print ("key = %s" % key) # (is a shortcut for:) for key in myDict.keys(): print ("key = %...
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 conveyin...
#Objeck
Objeck
  function : native : PrintAverage(values : FloatVector) ~ Nil { values->Average()->PrintLine(); }  
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#OCaml
OCaml
let mean_floats = function | [] -> 0. | xs -> List.fold_left (+.) 0. xs /. float_of_int (List.length xs)   let mean_ints xs = mean_floats (List.map float_of_int xs)
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#Slate
Slate
s@(Sequence traits) median [ s isEmpty ifTrue: [Nil] ifFalse: [| sorted | sorted: s sort. sorted length `cache isEven ifTrue: [(sorted middle + (sorted at: sorted indexMiddle - 1)) / 2] ifFalse: [sorted middle]] ].
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#Smalltalk
Smalltalk
OrderedCollection extend [ median [ self size = 0 ifFalse: [ |s l| l := self size. s := self asSortedCollection. (l rem: 2) = 0 ifTrue: [ ^ ((s at: (l//2 + 1)) + (s at: (l//2))) / 2 ] ifFalse: [ ^ s at: (l//2 + 1) ] ] ifTrue: [ ^nil ] ] ].
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#Scheme
Scheme
(define (a-mean l) (/ (apply + l) (length l)))   (define (g-mean l) (expt (apply * l) (/ (length l))))   (define (h-mean l) (/ (length l) (apply + (map / l))))   (define (iota start stop) (if (> start stop) (list) (cons start (iota (+ start 1) stop))))   (let* ((l (iota 1 10)) (a (a-mean l)) (g (g-m...
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) ...
#Objeck
Objeck
  bundle Default { class Balanced { function : IsBalanced(text : String) ~ Bool { level := 0; each(i : text) { character := text->Get(i); if(character = ']') { if(level = 0) { return false; }; level -= 1; };   if(character = '['...
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 ins...
#Groovy
Groovy
map = [:] map[7] = 7 map['foo'] = 'foovalue' map.put('bar', 'barvalue') map.moo = 'moovalue'   assert 7 == map[7] assert 'foovalue' == map.foo assert 'barvalue' == map['bar'] assert 'moovalue' == map.get('moo')
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Objeck
Objeck
  use Structure;   bundle Default { class Test { function : Main(args : String[]) ~ Nil { Run(); }   function : native : Run() ~ Nil { values := IntVector->New([1, 2, 3, 4, 5]); squares := values->Apply(Square(Int) ~ Int); each(i : squares) { squares->Get(i)->PrintLine(); ...
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 ...
#QB64
QB64
  'dictionary is not native data type of QB64 ' here a dictionary engine using a string to store data Dim Shared Skey As String * 1, SValue As String * 1, EValue As String * 1 Skey = Chr$(0) SValue = Chr$(1) EValue = Chr$(255)   'Demo area----------------> Dim MyDictionary As String   If ChangeValue(MyDictionary, "a", ...
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 ...
#R
R
> env <- new.env() > env[["x"]] <- 123 > env[["x"]]
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#Octave
Octave
function m = omean(l) if ( numel(l) == 0 ) m = 0; else m = mean(l); endif endfunction   disp(omean([])); disp(omean([1,2,3]));
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#Oforth
Oforth
: avg ( x -- avg ) x sum x size dup ifZero: [ 2drop null ] else: [ >float / ] ;
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#Stata
Stata
set obs 100000 gen x=rbeta(0.2,1.3) quietly summarize x, detail display r(p50)
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#Tcl
Tcl
proc median args { set list [lsort -real $args] set len [llength $list] # Odd number of elements if {$len & 1} { return [lindex $list [expr {($len-1)/2}]] } # Even number of elements set idx2 [expr {$len/2}] set idx1 [expr {$idx2-1}] return [expr { ([lindex $list $idx...
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 p...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i";   const array float: numbers is [] (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0);   const func proc: main is func local var float: number is 0.0; var float: sum is 0.0; var float: product is 1.0; var float: reciprocalSum is 0.0; begin for nu...
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) ...
#OCaml
OCaml
let generate_brackets n = let rec aux i acc = if i <= 0 then acc else aux (pred i) ('['::']'::acc) in let brk = aux n [] in List.sort (fun _ _ -> (Random.int 3) - 1) brk   let is_balanced brk = let rec aux = function | [], 0 -> true | '['::brk, level -> aux (brk, succ level) | ']'::brk,...
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 ins...
#Harbour
Harbour
arr := { => } arr[ 10 ] := "Val_10" arr[ "foo" ] := "foovalue"
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#OCaml
OCaml
Array.map
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Octave
Octave
function e = f(x, y) e = x^2 + exp(-1/(y+1)); endfunction   % f([2,3], [1,4]) gives and error, but arrayfun(@f, [2, 3], [1,4]) % works
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Racket
Racket
  #lang racket   (define dict1 #hash((apple . 5) (orange . 10))) ; hash table (define dict2 '((apple . 5) (orange . 10)))  ; a-list (define dict3 (vector "a" "b" "c"))  ; vector (integer keys)   (dict-keys dict1)  ; => '(orange apple) (dict-values dict2)  ; => '(5 10) (for/...
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 ...
#Raku
Raku
my %pairs = hello => 13, world => 31, '!' => 71;   for %pairs.kv -> $k, $v { say "(k,v) = ($k, $v)"; }   # Stable order for %pairs.sort(*.value)>>.kv -> ($k, $v) { say "(k,v) = ($k, $v)"; }   { say "$^a => $^b" } for %pairs.kv;   say "key = $_" for %pairs.keys;   say "value = $_" for %pairs.values;
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#ooRexx
ooRexx
  call testAverage .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1) call testAverage .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11) call testAverage .array~of(10, 20, 30, 40, 50, -100, 4.7, -11e2) call testAverage .array~new   ::routine testAverage use arg numbers say "numbers =" numbers~toString("l", ", ") sa...
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 conveyin...
#Oz
Oz
declare fun {Mean Xs} {FoldL Xs Number.'+' 0.0} / {Int.toFloat {Length Xs}} end in {Show {Mean [3. 1. 4. 1. 5. 9.]}}
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#TI-83_BASIC
TI-83 BASIC
median({1.1, 2.5, 0.3241})
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#TI-89_BASIC
TI-89 BASIC
median({3, 4, 1, -8.4, 7.2, 4, 1, 1})
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#Sidef
Sidef
func A(a) { a.sum / a.len } func G(a) { a.prod.root(a.len) } func H(a) { a.len / a.map{1/_}.sum }
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) ...
#Oforth
Oforth
String method: isBalanced | c | 0 self forEach: c [ c '[' == ifTrue: [ 1+ continue ] c ']' <> ifTrue: [ continue ] 1- dup 0 < ifTrue: [ drop false return ] ] 0 == ;   : genBrackets(n) "" #[ "[" "]" 2 rand 2 == ifTrue: [ swap ] rot + swap + ] times(n) ;
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element ins...
#Haskell
Haskell
import Data.Map   dict = fromList [("key1","val1"), ("key2","val2")]   ans = Data.Map.lookup "key2" dict -- evaluates to Just "val2"  
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Oforth
Oforth
0 #+ [ 1, 2, 3, 4, 5 ] apply
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Ol
Ol
  (for-each (lambda (element) (display element)) '(1 2 3 4 5)) ; ==> 12345  
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#REXX
REXX
/*REXX program demonstrates how to set and display values for an associative array. */ /*╔════════════════════════════════════════════════════════════════════════════════════╗ ║ The (below) two REXX statements aren't really necessary, but it shows how to ║ ║ define any and all entries in a associative 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 conveyin...
#PARI.2FGP
PARI/GP
avg(v)={ if(#v,vecsum(v)/#v) };
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#Pascal
Pascal
Program Mean;   function DoMean(vector: array of double): double; var sum: double; i, len: integer; begin sum := 0; len := length(vector); if len > 0 then begin for i := low(vector) to high(vector) do sum := sum + vector[i]; sum := sum / len; end; DoMean := sum; ...
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 ...
#Ursala
Ursala
#import std #import flo   median = fleq-<; @K30K31X eql?\~&rh div\2.+ plus@lzPrhPX
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#Vala
Vala
int compare_numbers(void* a_ref, void* b_ref) { double a = *(double*) a_ref; double b = *(double*) b_ref; return a > b ? 1 : a < b ? -1 : 0; }   double median(double[] elements) { double[] clone = elements; Posix.qsort(clone, clone.length, sizeof(double), compare_numbers); double middle = clone....
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 p...
#Smalltalk
Smalltalk
Collection extend [ arithmeticMean [ ^ (self fold: [:a :b| a + b ]) / (self size) ]   geometricMean [ ^ (self fold: [:a :b| a * b]) raisedTo: (self size reciprocal) ]   harmonicMean [ ^ (self size) / ((self collect: [:x|x reciprocal]) fold: [:a :b| a + b ] ) ] ]   |a| a := #(1 2 3...
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) ...
#ooRexx
ooRexx
  tests = .array~of("", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]")   -- add some randomly generated tests loop i = 1 to 8 tests~append(generateBrackets(i)) end   loop test over tests say test":" checkbrackets(test) end   ::routine checkBrackets use arg input -- counter of bracket groups. Must be 0 at ...
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 ins...
#hexiscript
hexiscript
let d dict 2 # Initial estimated size let d["test"] "test" # Strings can be used as index let d[123] 123 # Integers can also be used as index   println d["test"] println d[123]
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element ins...
#Icon_and_Unicon
Icon and Unicon
procedure main() local t t := table() t["foo"] := "bar" write(t["foo"]) end
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#ooRexx
ooRexx
start = .array~of("Rick", "Mike", "David", "Mark") new = map(start, .routines~reversit) call map new, .routines~sayit     -- a function to perform an iterated callback over an array -- using the provided function. Returns an array containing -- each function result ::routine map use strict arg array, function resu...
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Order
Order
#include <order/interpreter.h>   ORDER_PP( 8tuple_map(8fn(8X, 8times(8X, 8X)), 8tuple(1, 2, 3, 4, 5)) ) // -> (1,4,9,16,25)   ORDER_PP( 8seq_map(8fn(8X, 8times(8X, 8X)), 8seq(1, 2, 3, 4, 5)) ) // -> (1)(4)(9)(16)(25)   ORDER_PP( 8seq_for_each(8fn(8X, 8print(8X 8comma)), 8seq(1, 2, 3, 4, 5)) ) // prints 1,2,3,4,5, and r...
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 ...
#Ring
Ring
  # Project : Associative array/Iteration   lst = [["hello", 13], ["world", 31], ["!", 71]] for n = 1 to len(lst) see lst[n][1] + " : " + lst[n][2] + nl next  
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#RLaB
RLaB
  x = <<>>; // create an empty list x.hello = 1; x.world = 2; x.["!"] = 3;   // to iterate over identifiers of a list one needs to use the function ''members'' // the identifiers are returned as a lexicographically ordered string row-vector // here ["!", "hello", "world"] for(i in members(x)) { printf("%s %g\n", i...
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 conveyin...
#Perl
Perl
sub avg { @_ or return 0; my $sum = 0; $sum += $_ foreach @_; return $sum/@_; }   print avg(qw(3 1 4 1 5 9)), "\n";
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#Phix
Phix
with javascript_semantics function mean(sequence s) if length(s)=0 then return 0 end if return sum(s)/length(s) end function ? mean({1, 2, 5, -5, -9.5, 3.14159})
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#VBA
VBA
Private Function medianq(s As Variant) As Double Dim res As Double, tmp As Integer Dim l As Integer, k As Integer res = 0 l = UBound(s): k = WorksheetFunction.Floor_Precise((l + 1) / 2, 1) If l Then res = quick_select(s, k) If l Mod 2 = 0 Then tmp = quick_...
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 ...
#Vedit_macro_language
Vedit macro language
Sort(0, File_Size, NOCOLLATE+NORESTORE) EOF Goto_Line(Cur_Line/2) Reg_Copy(10, 1)
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#SQL
SQL
  --setup CREATE TABLE averages (val INTEGER); INSERT INTO averages VALUES (1); INSERT INTO averages VALUES (2); INSERT INTO averages VALUES (3); INSERT INTO averages VALUES (4); INSERT INTO averages VALUES (5); INSERT INTO averages VALUES (6); INSERT INTO averages VALUES (7); INSERT INTO averages VALUES (8); INSERT IN...
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) ...
#OxygenBasic
OxygenBasic
function CheckBrackets(string s) as bool '======================================= sys co, le=len s byte b at strptr s indexbase 0 for i=0 to <le select b(i) case "[" : co++ case "]" : co-- end select if co<0 then return 0 next if co=0 then return 1 end function     'TEST '====   print Ch...
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 ins...
#Inform_7
Inform 7
Hash Bar is a room.   Connection relates various texts to one number. The verb to be connected to implies the connection relation.   "foo" is connected to 12. "bar" is connected to 34. "baz" is connected to 56.   When play begins: [change values] now "bleck" is connected to 78; [check values] if "foo" is connected ...
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 ins...
#Ioke
Ioke
{a: "a", b: "b"}
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Oz
Oz
declare fun{Square A} A*A end   Lst = [1 2 3 4 5]   %% apply a PROCEDURE to every element {ForAll Lst Show}   %% apply a FUNCTION to every element Result = {Map Lst Square} {Show Result}
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#PARI.2FGP
PARI/GP
callback(n)=n+n; apply(callback, [1,2,3,4,5])
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Ruby
Ruby
my_dict = { "hello" => 13, "world" => 31, "!" => 71 }   # iterating over key-value pairs: my_dict.each {|key, value| puts "key = #{key}, value = #{value}"} # or my_dict.each_pair {|key, value| puts "key = #{key}, value = #{value}"}   # iterating over keys: my_dict.each_key {|key| puts "key = #{key}"}   # it...
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 ...
#Rust
Rust
use std::collections::HashMap; fn main() { let mut olympic_medals = HashMap::new(); olympic_medals.insert("United States", (1072, 859, 749)); olympic_medals.insert("Soviet Union", (473, 376, 355)); olympic_medals.insert("Great Britain", (246, 276, 284)); olympic_medals.insert("Germany", (252, 260, 2...
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#Phixmonti
Phixmonti
1 2 5 -5 -9.5 3.14159 stklen tolist len swap sum swap / print
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#PHP
PHP
$nums = array(3, 1, 4, 1, 5, 9); if ($nums) echo array_sum($nums) / count($nums), "\n"; else echo "0\n";
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#Vlang
Vlang
fn main() { println(median([3, 1, 4, 1])) // prints 2 println(median([3, 1, 4, 1, 5])) // prints 3 }   fn median(aa []int) int { mut a := aa.clone() a.sort() half := a.len / 2 mut m := a[half] if a.len%2 == 0 { m = (m + a[half-1]) / 2 } return m }
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#Wortel
Wortel
@let {  ; iterative med1 &l @let {a @sort l s #a i @/s 2 ?{%%s 2 ~/ 2 +`-i 1 a `i a `i a}}    ; tacit med2 ^(\~/2 @sum @(^(\&![#~f #~c] \~/2 \~-1 #) @` @id) @sort)   [[  !med1 [4 2 5 2 1]  !med1 [4 5 2 1]  !med2 [4 2 5 2 1]  !med2 [4 5 2 1] ]] }
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#Stata
Stata
clear all set obs 10 gen x=_n ameans x   Variable | Type Obs Mean [95% Conf. Interval] -------------+--------------------------------------------------------------- x | Arithmetic 10 5.5 3.334149 7.665851 | Geometric 10 4....
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 p...
#Tcl
Tcl
proc arithmeticMean list { set sum 0.0 foreach value $list { set sum [expr {$sum + $value}] } return [expr {$sum / [llength $list]}] } proc geometricMean list { set product 1.0 foreach value $list { set product [expr {$product * $value}] } return [expr {$product ** (1.0/[llength $list])}] } proc...
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) ...
#PARI.2FGP
PARI/GP
balanced(s)={ my(n=0,v=Vecsmall(s)); for(i=1,#v, if(v[i]==91, n++ , if(v[i]==93 && n, n--, return(0)) ) ); !n }; rnd(n)=Strchr(vectorsmall(n,i,if(random(2),91,93))) forstep(n=0,10,2,s=rnd(n);print(s"\t"if(balanced(s),"true","false")))
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element ins...
#J
J
coclass 'assocArray' encode=: 'z', (a.{~;48 65 97(+ i.)&.>10 26 26) {~ 62x #.inv 256x #. a.&i. get=: ".@encode has=: 0 <: nc@<@encode set=:4 :'(encode x)=:y'
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Pascal
Pascal
# create array my @a = (1, 2, 3, 4, 5);   # create callback function sub mycallback { return 2 * shift; }   # use array indexing for (my $i = 0; $i < scalar @a; $i++) { print "mycallback($a[$i]) = ", mycallback($a[$i]), "\n"; }   # using foreach foreach my $x (@a) { print "mycallback($x) = ", mycallback($x), "\n"...
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 ...
#Scala
Scala
val m = Map("Amsterdam" -> "Netherlands", "New York" -> "USA", "Heemstede" -> "Netherlands")   println(f"Key->Value: ${m.mkString(", ")}%s") println(f"Pairs: ${m.toList.mkString(", ")}%s") println(f"Keys: ${m.keys.mkString(", ")}%s") println(f"Values: ${m.values.mkString(", ")}%s") println(f"Unique values: ${m.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 ...
#Scheme
Scheme
  ;; Create an associative array (hash-table) whose keys are strings: (define table (hash-table 'string=? '("hello" . 0) '("world" . 22) '("!" . 999)))   ;; Iterate over the table, passing the key and the value of each entry ;; as arguments to a function: (hash-table-for-each table ;; Create by "partial applicati...
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 conveyin...
#PicoLisp
PicoLisp
(de mean (Lst) (if (atom Lst) 0 (/ (apply + Lst) (length Lst)) ) )
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#PL.2FI
PL/I
arithmetic_mean = sum(A)/dimension(A,1);
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#Wren
Wren
import "/sort" for Sort, Find import "/math" for Nums import "/queue" for PriorityQueue   var lists = [ [5, 3, 4], [3, 4, 1, -8.4, 7.2, 4, 1, 1.2] ]   for (l in lists) { // sort and then find median var l2 = Sort.merge(l) System.print(Nums.median(l2))   // using a priority queue var pq = Pri...
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 p...
#Ursala
Ursala
#import std #import flo   data = ari10(1.,10.) # arithmetic progression, length 10 with endpoints 1 and 10   a = mean data g = exp mean ln* data h = div/1. mean div/*1. data   #cast %eLbX   main = ^(~&,ordered not fleq) <a,g,h>
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) ...
#Pascal
Pascal
sub generate { my $n = shift; my $str = '[' x $n; substr($str, rand($n + $_), 0) = ']' for 1..$n; return $str; }   sub balanced { shift =~ /^ (\[ (?1)* \])* $/x; }   for (0..8) { my $input = generate($_); print balanced($input) ? " ok:" : "bad:", " '$input'\n"; }
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element ins...
#Java
Java
Map<String, Integer> map = new HashMap<String, Integer>(); map.put("foo", 5); map.put("bar", 10); map.put("baz", 15); map.put("foo", 6);