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... | #Logo | Logo | pprop "animals "cat 5
pprop "animals "dog 4
pprop "animals "mouse 11
print gprop "animals "cat ; 5
remprop "animals "dog
show plist "animals ; [mouse 11 cat 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.
| #REBOL | REBOL | rebol [
Title: "Array Callback"
URL: http://rosettacode.org/wiki/Apply_a_callback_to_an_Array
]
map: func [
"Apply a function across an array."
f [native! function!] "Function to apply to each element of array."
a [block!] "Array to process."
/local x
][x: copy [] forall a [append x do [f a/1]] x]
squ... |
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... | #Rust | Rust | fn sum(arr: &[f64]) -> f64 {
arr.iter().fold(0.0, |p,&q| p + q)
}
fn mean(arr: &[f64]) -> f64 {
sum(arr) / arr.len() as f64
}
fn main() {
let v = &[2.0, 3.0, 5.0, 7.0, 13.0, 21.0, 33.0, 54.0];
println!("mean of {:?}: {:?}", v, mean(v));
let w = &[];
println!("mean of {:?}: {:?}", w, mean(w... |
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... | #Sather | Sather | class VECOPS is
mean(v:VEC):FLT is
m ::= 0.0;
loop m := m + v.aelt!; end;
return m / v.dim.flt;
end;
end;
class MAIN is
main is
v ::= #VEC(|1.0, 5.0, 7.0|);
#OUT + VECOPS::mean(v) + "\n";
end;
end; |
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) ... | #Qi | Qi | (define balanced-brackets-0
[] 0 -> true
[] _ -> false
[#\[|R] Sum -> (balanced-brackets-0 R (+ Sum 1))
_ 0 -> false
[_ |R] Sum -> (balanced-brackets-0 R (- Sum 1)))
(define balanced-brackets
"" -> true
S -> (balanced-brackets-0 (explode (INTERN S)) 0))
(balanced-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 ins... | #LOLCODE | LOLCODE | HAI 1.2
I HAS A Hash ITZ A BUKKIT
Hash HAS A key1 ITZ "val1" BTW This works for identifier-like keys, like obj.key in JavaScript
Hash HAS A SRS "key-2" ITZ 1 BTW Non-identifier keys need the SRS
VISIBLE Hash'Z SRS "key-2"
KTHXBYE
|
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.
| #Retro | Retro | { #1 #2 #3 #4 #5 } [ #10 * ] a:map [ n:put sp ] a:for-each |
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.
| #REXX | REXX | /*REXX program applies a callback to an array (using factorials for a demonstration).*/
numeric digits 100 /*be able to display some huge numbers.*/
parse arg # . /*obtain an optional value from the CL.*/
a.= ... |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin... | #Scala | Scala | def mean(s: Seq[Int]) = s.foldLeft(0)(_+_) / s.size |
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... | #Scheme | Scheme | (define (mean l)
(if (null? l)
0
(/ (apply + l) (length l)))) |
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) ... | #Quackery | Quackery | [ char [ over of
swap
char ] swap of
join shuffle ] is bracket$ ( n --> $ )
[ 0 swap witheach
[ char [ =
iff 1 else -1 +
dup 0 < if
conclude ]
0 = ] is balanced ( $ --> b )
10 times
[ 20 i 2 * - times sp
i bracket$ dup echo$
... |
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... | #Lua | Lua | hash = {}
hash[ "key-1" ] = "val1"
hash[ "key-2" ] = 1
hash[ "key-3" ] = {} |
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.
| #Ring | Ring |
for x in [1,2,3,4,5]
x = x*x
next
|
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.
| #RLaB | RLaB |
>> x = rand(2,4)
0.707213207 0.275298961 0.396757763 0.232312312
0.215619868 0.207078017 0.565700032 0.666090571
>> sin(x)
0.649717845 0.271834652 0.386430003 0.230228332
0.213952984 0.205601224 0.536006923 0.617916954
|
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
const array float: numVector is [] (1.0, 2.0, 3.0, 4.0, 5.0);
const func float: mean (in array float: numbers) is func
result
var float: result is 0.0;
local
var float: total is 0.0;
var float: num is 0.0;
begin
if length(numbers) <> 0 then
... |
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... | #SenseTalk | SenseTalk | put the average of [12,92,-17,66,128]
put average(empty)
|
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) ... | #R | R | balanced <- function(str){
str <- strsplit(str, "")[[1]]
str <- ifelse(str=='[', 1, -1)
all(cumsum(str) >= 0) && sum(str) == 0
} |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element ins... | #M2000_Interpreter | M2000 Interpreter |
Inventory A="100":=1, "200":=5, 10:=500, 20:="Hello There"
Print len(A)
Print A(100)=1, A(200)=5, A$(20)="Hello There"
Return A, 100:=3, 200:=7
\\ print all elements
Print A
For i=0 to Len(A)-1 {
\\ Key, Value by current order (using !)
Print Eval$(A, i), A$(i!)
}
\\ Iterator
Append A, "End":=5000
N=Each... |
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... | #Maple | Maple | > T := table( [ (2,3) = 4, "foo" = 1, sin(x) = cos(x) ] );
T := table(["foo" = 1, sin(x) = cos(x), (2, 3) = 4])
> T[2,3];
4
> T[sin(x)];
cos(x)
> T["foo"];
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.
| #Ruby | Ruby | for i in [1,2,3,4,5] do
puts i**2
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.
| #Rust | Rust | fn echo(n: &i32) {
println!("{}", n);
}
fn main() {
let a: [i32; 5];
a = [1, 2, 3, 4, 5];
let _: Vec<_> = a.into_iter().map(echo).collect();
} |
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... | #Sidef | Sidef | func avg(Array list) {
list.len > 0 || return 0;
list.sum / list.len;
}
say avg([Math.inf, Math.inf]);
say avg([3,1,4,1,5,9]);
say avg([1e+20, 3, 1, 4, 1, 5, 9, -1e+20]);
say avg([10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0.11]);
say avg([10, 20, 30, 40, 50, -100, 4.7, -1100]); |
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) ... | #Racket | Racket |
#lang racket
(define (generate n)
(list->string (shuffle (append* (make-list n '(#\[ #\]))))))
(define (balanced? str)
(let loop ([l (string->list str)] [n 0])
(or (null? l)
(if (eq? #\[ (car l))
(loop (cdr l) (add1 n))
(and (> n 0) (loop (cdr l) (sub1 n)))))))
(define (try 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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | a[2] = "string"; a["sometext"] = 23; |
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.
| #Salmon | Salmon | function apply(list, ageless to_apply)
(comprehend(x; list) (to_apply(x)));
function square(x) (x*x);
iterate(x; apply([0...9], square))
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.
| #Sather | Sather | class MAIN is
do_something(i:INT):INT is
return i * i;
end;
main is
a:ARRAY{INT} := |1, 2, 3, 4, 5|;
-- we use an anonymous closure to apply our do_something "callback"
a.map(bind(do_something(_)));
loop #OUT + a.elt! + "\n"; end;
end;
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 conveyin... | #Slate | Slate | [|:list| (list reduce: #+ `er ifEmpty: [0]) / (list isEmpty ifTrue: [1] ifFalse: [list size])] applyWith: #(3 1 4 1 5 9).
[|:list| (list reduce: #+ `er ifEmpty: [0]) / (list isEmpty ifTrue: [1] ifFalse: [list size])] applyWith: {}. |
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... | #Smalltalk | Smalltalk |
| numbers |
numbers := #(1 2 3 4 5 6 7 8).
(numbers isEmpty
ifTrue:[0]
ifFalse: [
(numbers inject: 0 into: [:sumSoFar :eachElement | sumSoFar + eachElement]) / numbers size ]
) displayNl.
|
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) ... | #Raku | Raku | sub balanced($s) {
my $l = 0;
for $s.comb {
when "]" {
--$l;
return False if $l < 0;
}
when "[" {
++$l;
}
}
return $l == 0;
}
my $n = prompt "Number of brackets";
my $s = (<[ ]> xx $n).flat.pick(*).join;
say "$s {balanced($s) ?? "is" ... |
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... | #MATLAB_.2F_Octave | MATLAB / Octave | hash.a = 1;
hash.b = 2;
hash.C = [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.
| #Scala | Scala | val l = List(1,2,3,4)
l.foreach {i => println(i)} |
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.
| #Scheme | Scheme | (define (square n) (* n n))
(define x #(1 2 3 4 5))
(map square (vector->list 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... | #SNOBOL4 | SNOBOL4 | define('avg(a)i,sum') :(avg_end)
avg i = i + 1; sum = sum + a<i> :s(avg)
avg = 1.0 * sum / prototype(a) :(return)
avg_end
* # Fill arrays
str = '1 2 3 4 5 6 7 8 9 10'; arr = array(10)
loop i = i + 1; str len(p) span('0123456789') . arr<i> @p :s(loop)
empty = array(1) ;* Nu... |
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... | #SQL | SQL |
CREATE TABLE "numbers" ("datapoint" INTEGER);
INSERT INTO "numbers" SELECT rownum FROM tab;
SELECT SUM("datapoint")/COUNT(*) FROM "numbers";
|
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) ... | #Red | Red | ; Functional code
balanced-brackets: [#"[" any balanced-brackets #"]"]
rule: [any balanced-brackets end]
balanced?: func [str][parse str rule]
; Tests
tests: [
good: ["" "[]" "[][]" "[[]]" "[[][]]" "[[[[[]]][][[]]]]"]
bad: ["[" "]" "][" "[[]" "[]]" "[]][[]" "[[[[[[]]]]]]]"]
]
foreach str tests/good [
if not bal... |
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... | #Maxima | Maxima | /* No need to declare anything, undeclared arrays are hashed */
h[1]: 6;
h[9]: 2;
arrayinfo(h);
[hashed, 1, [1], [9]] |
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... | #min | min | {1 :one 2 :two 3 :three} |
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.
| #SenseTalk | SenseTalk |
put each item in [1,2,3,5,9,14,24] squared
put myFunc of each for each item of [1,2,3,5,9,14,24]
to handle myFunc of num
return 2*num + 1
end myFunc |
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.
| #Sidef | Sidef | func callback(i) { say i**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... | #Standard_ML | Standard ML | fun mean_reals [] = 0.0
| mean_reals xs = foldl op+ 0.0 xs / real (length xs);
val mean_ints = mean_reals o (map real); |
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... | #Stata | Stata | clear all
input str20 country population
Belgium 11311.1
Bulgaria 7153.8
"Czech Republic" 10553.8
Denmark 5707.3
Germany 82175.7
Estonia 1315.9
Ireland 4724.7
Greece 10783.7
end
. mean population
Mean estimation Number of obs = 8
-------------------------------------------------------... |
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) ... | #REXX | REXX | /*REXX program checks for balanced brackets [ ] ─── some fixed, others random.*/
parse arg seed . /*obtain optional argument from the CL.*/
if datatype(seed,'W') then call random ,,seed /*if specified, then use as RANDOM seed*/
@.=0; yesNo.0= right('not OK', 50) ... |
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... | #MiniScript | MiniScript | map = { 3: "test", "foo": 42 }
print map[3]
map[3] = "more tests"
print map[3]
print map["foo"]
print map.foo // same as map["foo"] (only for string keys that are valid identifiers)
|
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.
| #Simula | Simula | BEGIN
! APPLIES A CALLBACK FUNCTION TO AN ARRAY ;
PROCEDURE APPLY(ARR, FUN);
REAL ARRAY ARR;
PROCEDURE FUN IS REAL PROCEDURE FUN(X); REAL X;;
BEGIN
INTEGER I;
FOR I := LOWERBOUND(ARR, 1) STEP 1 UNTIL UPPERBOUND(ARR, 1) DO
ARR(I) := FUN(ARR(I));
END 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.
| #Slate | Slate | #( 1 2 3 4 5 ) collect: [| :n | n * 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... | #Swift | Swift | func meanDoubles(s: [Double]) -> Double {
return s.reduce(0, +) / Double(s.count)
}
func meanInts(s: [Int]) -> Double {
return meanDoubles(s.map{Double($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 conveyin... | #Tcl | Tcl | package require Tcl 8.5
proc mean args {
if {[set num [llength $args]] == 0} {return 0}
expr {[tcl::mathop::+ {*}$args] / double($num)}
}
mean 3 1 4 1 5 9 ;# ==> 3.8333333333333335 |
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) ... | #Ring | Ring |
nr = 0
while nr < 10
nr += 1
test=generate(random(9)+1)
see "bracket string " + test + " is " + valid(test) + nl
end
func generate n
l = 0 r = 0 output = ""
while l<n and r<n
switch random(2)
on 1 l+=1 output+="["
on 2 r+=1 output+="]"
off
end
if l=n output+=copy("]",n-r) ... |
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... | #Nemerle | Nemerle | using System;
using System.Console;
using Nemerle.Collections;
module AssocArray
{
Main() : void
{
def hash1 = Hashtable([(1, "one"), (2, "two"), (3, "three")]);
def hash2 = Hashtable(3);
foreach (e in hash1)
hash2[e.Value] = e.Key;
WriteLine("Enter 1, 2, or 3:");
... |
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... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols
key0 = '0'
key1 = 'key0'
hash = '.' -- Initialize the associative array 'hash' to '.'
hash[key1] = 'value0' -- Set a specific key/value pair
say '<hash key="'key0'" value="'hash[key0]'" />' -- Display a value for a key that wasn't se... |
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.
| #Smalltalk | Smalltalk | #( 1 2.0 'three') do: [:each | each displayNl]. |
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.
| #Sparkling | Sparkling | let numbers = { 1, 2, 3, 4 };
foreach(numbers, function(idx, num) {
print(num);
}); |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin... | #TI-83_BASIC | TI-83 BASIC | Mean(Ans |
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... | #TI-89_BASIC | TI-89 BASIC | Define rcmean(nums) = when(dim(nums) = 0, 0, mean(nums)) |
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) ... | #Ruby | Ruby | re = /\A # beginning of string
(?<bb> # begin capture group <bb>
\[ # literal [
\g<bb>* # zero or more <bb>
\] # literal ]
)* # end group, zero or more such groups
\z/x # end of string
10.times do |i|
s = (%w{[ ]} * i).shuffle.join
puts (s =~ re ? " OK: "... |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element ins... | #Nim | Nim | import tables
var
hash = initTable[string, int]() # empty hash table
hash1: Table[string, int] # empty hash table (implicit initialization).
hash2 = {"key1": 1, "key2": 2}.toTable # hash table with two keys
hash3 = [("key1", 1), ("key2", 2)].toTable # hash table from tuple array
hash4 = @[("key1", 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.
| #SQL_PL | SQL PL |
--#SET TERMINATOR @
SET SERVEROUTPUT ON @
BEGIN
DECLARE TYPE NUMBERS AS SMALLINT ARRAY[5];
DECLARE NUMBERS NUMBERS;
DECLARE I SMALLINT;
SET I = 1;
WHILE (I <= 5) DO
SET NUMBERS[I] = I;
SET I = I + 1;
END WHILE;
BEGIN
DECLARE PROCEDURE PRINT_SQUARE (
IN VALUE SMALLINT
)
BEGIN
CALL DBMS... |
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.
| #Standard_ML | Standard ML |
map f l
|
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... | #Trith | Trith | : mean dup empty? [drop 0] [dup [+] foldl1 swap length /] branch ;
[3 1 4 1 5 9] 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 conveyin... | #TypeScript | TypeScript |
function mean(numbersArr)
{
let arrLen = numbersArr.length;
if (arrLen > 0) {
let sum: number = 0;
for (let i of numbersArr) {
sum += i;
}
return sum/arrLen;
}
else return "Not defined";
}
alert( mean( [1,2,3,4,5] ) );
alert( 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) ... | #Run_BASIC | Run BASIC | dim brk$(10)
brk$(1) = "[[[][]]]"
brk$(2) = "[[[]][[[][[][]]]]]"
brk$(3) = "][][]][["
brk$(4) = "[][][]"
brk$(5) = "[][]][]][[]]][[["
brk$(6) = "]][[[[]]]][]]][[[["
brk$(7) = "[[][[[]]][]]"
brk$(8) = "[]][][][[[]]"
brk$(9) = "][]][["
brk$(10) =... |
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... | #Oberon-2 | Oberon-2 |
MODULE AssociativeArray;
IMPORT
ADT:Dictionary,
Object:Boxed,
Out;
TYPE
Key = STRING;
Value = Boxed.LongInt;
VAR
assocArray: Dictionary.Dictionary(Key,Value);
iterK: Dictionary.IterKeys(Key,Value);
iterV: Dictionary.IterValues(Key,Value);
aux: Value;
k: Key;
BEGIN
assocArray := NEW(Dictionar... |
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.
| #Stata | Stata | function map(f,a) {
nr = rows(a)
nc = cols(a)
b = J(nr,nc,.)
for (i=1;i<=nr;i++) {
for (j=1;j<=nc;j++) b[i,j] = (*f)(a[i,j])
}
return(b)
}
function maps(f,a) {
nr = rows(a)
nc = cols(a)
b = J(nr,nc,"")
for (i=1;i<=nr;i++) {
for (j=1;j<=nc;j++) b[i,j] = (*f)(a[i,j])
}
return(b)
}
function square(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.
| #SuperCollider | SuperCollider | [1, 2, 3].squared // returns [1, 4, 9] |
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... | #UNIX_Shell | UNIX Shell | echo "`cat f | paste -sd+ | bc -l` / `cat f | wc -l`" | bc -l
|
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... | #UnixPipes | UnixPipes | term() {
b=$1;res=$2
echo "scale=5;$res+$b" | bc
}
sum() {
(read B; res=$1;
test -n "$B" && (term $B $res) || (term 0 $res))
}
fold() {
func=$1
(while read a ; do
fold $func | $func $a
done)
}
mean() {
tee >(wc -l > count) | fold sum | xargs echo "scale=5;(1/" $(cat count) ") * " | bc
}
... |
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) ... | #Rust | Rust | extern crate rand;
trait Balanced {
/// Returns true if the brackets are balanced
fn is_balanced(&self) -> bool;
}
impl<'a> Balanced for str {
fn is_balanced(&self) -> bool {
let mut count = 0;
for bracket in self.chars() {
let change = match bracket {
'[' =... |
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... | #Objeck | Objeck |
# create map
map := StringMap->New();
# insert
map->Insert("two", IntHolder->New(2)->As(Base));
map->Insert("thirteen", IntHolder->New(13)->As(Base));
map->Insert("five", IntHolder->New(5)->As(Base));
map->Insert("seven", IntHolder->New(7)->As(Base));
# find
map->Find("thirteen")->As(IntHolder)->GetValue()->PrintLine... |
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.
| #Swift | Swift | func square(n: Int) -> Int {
return n * n
}
let numbers = [1, 3, 5, 7]
let squares1a = numbers.map(square) // map method on array
let squares1b = numbers.map {x in x*x} // map method on array with anonymous function
let squares1b = numbers.map { $0 * $0 } // map method on array with anonym... |
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.
| #Tailspin | Tailspin |
def numbers: [1,3,7,10];
templates cube
$ * $ * $ !
end cube
// Using inline array templates (which also allows access to index by $i)
$numbers -> \[i]($ * $i !\) -> !OUT::write
$numbers -> \[i]($ * $ !\) -> !OUT::write
$numbers -> \[i]($ -> cube !\) -> !OUT::write
// Using array literal and deconstructor
[ $... |
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... | #Ursa | Ursa | #
# arithmetic mean
#
decl int<> input
decl int i
for (set i 1) (< i (size args)) (inc i)
append (int args<i>) input
end for
out (/ (+ input) (size input)) endl console |
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... | #Ursala | Ursala | #import nat
#import flo
mean = ~&?\0.! div^/plus:-0. float+ length
#cast %e
example = mean <5.,3.,-2.,6.,-4.> |
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) ... | #Scala | Scala | import scala.collection.mutable.ListBuffer
import scala.util.Random
object BalancedBrackets extends App {
val random = new Random()
def generateRandom: List[String] = {
import scala.util.Random._
val shuffleIt: Int => String = i => shuffle(("["*i+"]"*i).toList).foldLeft("")(_+_)
(1 to 20).map(i=>(ra... |
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... | #Objective-C | Objective-C | NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"Joe Doe", @"name",
[NSNumber numberWithUnsignedInt:42], @"age",
[NSNull null], @"extra",
nil]; |
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.
| #Tcl | Tcl | foreach var $dat {
myfunc $var
} |
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.
| #TI-89_BASIC | TI-89 BASIC | © For no return value
Define foreach(fe_cname,fe_list) = Prgm
Local fe_i
For fe_i,1,dim(fe_list)
#fe_cname(fe_list[fe_i])
EndFor
EndPrgm
© For a list of results
Define map(map_cnam,map_list) = seq(#map_cnam(map_list[map_i]),map_i,1,dim(map_list))
Define callback(elem) = Prgm
Disp elem
EndPrgm
foreach(... |
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... | #V | V | [mean
[sum 0 [+] fold].
dup sum
swap size [[1 <] [1]] when /
]. |
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... | #Vala | Vala |
double arithmetic(double[] list){
double mean;
double sum = 0;
if (list.length == 0)
return 0.0;
foreach(double number in list){
sum += number;
} // foreach
mean = sum / list.length;
return mean;
} // end arithmetic mean
public static void main(){
double[] test = {1.0, 2.0, 5.0, -5.0, 9.5, 3.14159... |
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) ... | #Scheme | Scheme | (define (balanced-brackets string)
(define (b chars sum)
(cond ((< sum 0)
#f)
((and (null? chars) (= 0 sum))
#t)
((null? chars)
#f)
((char=? #\[ (car chars))
(b (cdr chars) (+ sum 1)))
((char=? #\] (car chars))
(b (cdr ... |
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... | #OCaml | OCaml | let hash = Hashtbl.create 0;;
List.iter (fun (key, value) -> Hashtbl.add hash key value)
["foo", 5; "bar", 10; "baz", 15];; |
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.
| #TIScript | TIScript | var a = [1, 2, 3, 4, 5];
a.map(function(v) { return v * v; })
|
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Toka | Toka | ( array count function -- )
{
value| array fn |
[ i array ] is I
[ to fn swap to array 0 swap [ I array.get :stack fn invoke I array.put ] countedLoop ]
} is map-array
( Build an array )
5 cells is-array a
10 0 a array.put
11 1 a array.put
12 2 a array.put
13 3 a array.put
14 4 a array.put
( Add 1 to each ite... |
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... | #VBA | VBA | Private Function mean(v() As Double, ByVal leng As Integer) As Variant
Dim sum As Double, i As Integer
sum = 0: i = 0
For i = 0 To leng - 1
sum = sum + vv
Next i
If leng = 0 Then
mean = CVErr(xlErrDiv0)
Else
mean = sum / leng
End If
End Function
Public Sub main()
... |
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... | #VBScript | VBScript |
Function mean(arr)
size = UBound(arr) + 1
mean = 0
For i = 0 To UBound(arr)
mean = mean + arr(i)
Next
mean = mean/size
End Function
'Example
WScript.Echo mean(Array(3,1,4,1,5,9))
|
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) ... | #Scilab | Scilab | function varargout=isbb(s)
st=strsplit(s);
t=cumsum((st=='[')-(st==']'));
balanced=and(t>=0) & t(length(t))==0;
varargout=list(balanced)
endfunction |
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... | #Ol | Ol |
;;; empty associative array
#empty
; or short form
#e
;;; creating the new empty associative array
(define empty-map #empty)
;;; creating associative array with values
(define my-map (pairs->ff '(
(1 . 100)
(2 . 200)
(7 . 777))))
;;; or in short form (available from Ol version 2.1)
(define my-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.
| #TorqueScript | TorqueScript |
function map(%array,%arrayCount,%function)
{
for(%i=0;%i<%arrayCount;%i++)
{
eval("%a = "@%array@"["@%i@"];");
eval(""@%function@"("@%a@");");
}
}
|
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.
| #TXR | TXR | $ txr -e '[mapdo prinl #(1 2 3 4 5 6 7 8 9 10)]'
1
2
3
4
5
6
7
8
9
10 |
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... | #Vedit_macro_language | Vedit macro language | #1 = 0 // Sum
#2 = 0 // Count
BOF
While(!At_EOF) {
#1 += Num_Eval(SIMPLE)
#2++
Line(1, ERRBREAK)
}
if (#2) { #1 /= #2 }
Num_Type(#1) |
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... | #Vim_Script | Vim Script | function Mean(lst)
if empty(a:lst)
throw "Empty"
endif
let sum = 0.0
for i in a:lst
let sum += i
endfor
return sum / len(a:lst)
endfunction |
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) ... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func string: generateBrackets (in integer: count) is func
result
var string: stri is "";
local
var integer: index is 0;
var integer: pos is 0;
var char: ch is ' ';
begin
stri := "[" mult count & "]" mult count;
for index range 1 to length(stri) do
po... |
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... | #ooRexx | ooRexx | map = .directory~new
map["foo"] = 5
map["bar"] = 10
map["baz"] = 15
map["foo"] = 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.
| #uBasic.2F4tH | uBasic/4tH | S = 5 ' Size of the array
For x = 0 To S - 1 ' Initialize array
@(x) = x + 1
Next
Proc _MapArray (_SquareRoot, S) ' Call mapping procedure
For x = 0 To S - 1 ' Print results
Print "SQRT(";x+1;") = ";Using "#.####";@(x)
Next
For ... |
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.
| #UNIX_Shell | UNIX Shell | map() {
map_command=$1
shift
for i do "$map_command" "$i"; done
}
list=1:2:3
(IFS=:; map echo $list) |
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... | #Vlang | Vlang | import math
import arrays
fn main() {
for v in [
[]f64{}, // mean returns ok = false
[math.inf(1), math.inf(1)], // answer is +Inf
// answer is NaN, and mean returns ok = true, indicating NaN
// is the correct result
[math.inf(1), math.inf(-1)],
... |
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... | #Wart | Wart | def (mean l)
sum.l / len.l |
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) ... | #Sidef | Sidef | func balanced (str) {
var depth = 0
str.each { |c|
if(c=='['){ ++depth }
elsif(c==']'){ --depth < 0 && return false }
}
return !depth
}
for str [']','[','[[]','][]','[[]]','[[]]]][][]]','x[ y [ [] z ]][ 1 ][]abcd'] {
printf("%sbalanced\t: %s\n", balanced(str) ? "" : "NOT ", ... |
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... | #OxygenBasic | OxygenBasic |
def n 200
Class AssociativeArray
'=====================
indexbase 1
string s[n]
sys max
method find(string k) as sys
sys i,e
e=max*2
for i=1 to e step 2
if k=s[i] then return i
next
end method
method dat(string k) as string
sys i=find(k)
if i then return s[i+1]
end method
... |
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... | #Oz | Oz | declare
Dict = {Dictionary.new}
in
Dict.foo := 5
Dict.bar := 10
Dict.baz := 15
Dict.foo := 20
{Inspect Dict} |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Ursala | Ursala | #import nat
#cast %nL
demo = successor* <325,32,67,1,3,7,315> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.