task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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]
square: func [x][x * x]
; Tests:
assert: func [code][print [either do code [" ok"]["FAIL"] mold code]]
print "Simple loop, modify in place:"
assert [[1 100 81] = (a: [1 10 9] forall a [a/1: square a/1] a)]
print [crlf "Functional style with 'map':"]
assert [[4 16 36] = map :square [2 4 6]]
print [crlf "Applying native function with 'map':"]
assert [[2 4 6] = map :square-root [4 16 36]] |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #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 "")
(balanced-brackets "[]")
(balanced-brackets "[][]")
(balanced-brackets "[[][]]")
(balanced-brackets "][")
(balanced-brackets "][][")
(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 insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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.= /*initialize the array A to all nulls*/
if #=='' | #=="," then #= 12 /*Not assigned? Then use default value*/
do j=0 to #; a.j= j /*assign the integer J ───► A.j */
end /*j*/ /*array A will have N values: 0 ──► #*/
call listA 'before callback' /*display A array before the callback*/
say /*display a blank line for readability.*/
say ' ··· applying callback to array A ···' /*display what is about to happen to B.*/
say /*display a blank line for readability.*/
call bangit 'a' /*factorialize (the values) of A array.*/
/* store the results ───► array B.*/
call listA ' after callback' /*display A array after the callback.*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
bangit: do v=0; $= value(arg(1)'.'v); if $=='' then return /*No value? Then return*/
call value arg(1)'.'v, fact($) /*assign a value (a factorial) to array*/
end /*i*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
fact: procedure; arg x; != 1; do f=2 to x; != !*f; end; /*f*/; return !
listA: do k=0 while a.k\==''; say arg(1) 'a.'k"=" a.k; end /*k*/; return |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #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$
say " is "
balanced not if
[ say "un" ]
say "balanced."
cr ] |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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
for num range numbers do
total +:= num;
end for;
result := total / flt(length(numbers));
end if;
end func;
const proc: main is func
begin
writeln(mean(numVector));
end func; |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #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 insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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(A)
While N {
Print Eval$(A, N^), A$(N^!)
}
Print Len(A)=5
Delete A, "100", 10, 20
Print Len(A)=2
If Exist(A, "End") Then Print Eval(A)=5000
|
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #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)
(define s (generate n))
(printf "~a => ~a\n" s (if (balanced? s) "OK" "NOT OK")))
(for ([n 10]) (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 insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #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" !! "is not"} well-balanced" |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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) ;* Null vector
* # Test and display
output = '[' str '] -> ' avg(arr)
output = '[ ] -> ' avg(empty)
end |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #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 balanced? str [print [mold str "failed!"]]
]
foreach str tests/bad [
if balanced? str [print [mold str "failed!"]]
]
repeat i 10 [
str: random copy/part "[][][][][][][][][][]" i * 2
print [mold str "is" either balanced? str ["balanced"]["unbalanced"]]
] |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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 insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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
--------------------------------------------------------------
| Mean Std. Err. [95% Conf. Interval]
-------------+------------------------------------------------
population | 16715.75 9431.077 -5585.203 39016.7
--------------------------------------------------------------
. tabstat population, statistic(mean)
variable | mean
-------------+----------
population | 16715.75
------------------------
. quietly summarize population
. display r(mean)
16715.75 |
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #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) /*for bad expressions, indent 50 spaces*/
yesNo.1= 'OK' /* [↓] the 14 "fixed" ][ expressions*/
q= ; call checkBal q; say yesNo.result '«null»'
q= '[][][][[]]' ; call checkBal q; say yesNo.result q
q= '[][][][[]]][' ; call checkBal q; say yesNo.result q
q= '[' ; call checkBal q; say yesNo.result q
q= ']' ; call checkBal q; say yesNo.result q
q= '[]' ; call checkBal q; say yesNo.result q
q= '][' ; call checkBal q; say yesNo.result q
q= '][][' ; call checkBal q; say yesNo.result q
q= '[[]]' ; call checkBal q; say yesNo.result q
q= '[[[[[[[]]]]]]]' ; call checkBal q; say yesNo.result q
q= '[[[[[]]]][]' ; call checkBal q; say yesNo.result q
q= '[][]' ; call checkBal q; say yesNo.result q
q= '[]][[]' ; call checkBal q; say yesNo.result q
q= ']]][[[[]' ; call checkBal q; say yesNo.result q
#=0 /*# additional random expressions*/
do j=1 until #==26 /*gen 26 unique bracket strings. */
q=translate( rand( random(1,10) ), '][', 10) /*generate random bracket string.*/
call checkBal q; if result==-1 then iterate /*skip if duplicated expression. */
say yesNo.result q /*display the result to console. */
#=#+1 /*bump the expression counter. */
end /*j*/ /* [↑] generate 26 random "Q" strings.*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
?: ?=random(0,1); return ? || \? /*REXX BIF*/
rand: $=copies(?()?(),arg(1)); _=random(2,length($)); return left($,_-1)substr($,_)
/*──────────────────────────────────────────────────────────────────────────────────────*/
checkBal: procedure expose @.; parse arg y /*obtain the "bracket" expression. */
if @.y then return -1 /*Done this expression before? Skip it*/
@.y=1 /*indicate expression was processed. */
!=0; do j=1 for length(y); _=substr(y,j,1) /*get a character.*/
if _=='[' then !=!+1 /*bump the nest #.*/
else do; !=!-1; if !<0 then return 0; end
end /*j*/
return !==0 /* [↑] "!" is the nested ][ counter.*/ |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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;
! CALLBACK ;
REAL PROCEDURE SQUARE(X); REAL X; SQUARE := X * X;
REAL ARRAY A(1:5);
INTEGER I;
FOR I := 1 STEP 1 UNTIL 5 DO A(I) := I;
APPLY(A, SQUARE);
FOR I := 1 STEP 1 UNTIL 5 DO OUTFIX(A(I), 2, 8); OUTIMAGE;
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.
| #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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #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) else output+=copy("]",n-l) ok
return output
func valid q
count = 0
if len(q)=0 return "ok." ok
for x=1 to len(q)
if substr(q,x,1)="[" count+=1 else count-=1 ok
if count<0 return "not ok." ok
next
return "ok."
|
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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:");
def entry = int.Parse(ReadLine());
WriteLine(hash1[entry]);
}
} |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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 set
say '<hash key="'key1'" value="'hash[key1]'" />' -- Display a value for a key that was set |
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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #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: " : "bad: ") + s
end
["[[]", "[]]", "a[ letters[-1] ].xyz[0]"].each do |s|
t = s.gsub(/[^\[\]]/, "")
puts (t =~ re ? " OK: " : "bad: ") + s
end |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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), ("key2", 2)].toTable # hash table from tuple seq
value = hash2["key1"]
hash["spam"] = 1
hash["eggs"] = 2
hash["foo"] = 3
echo "hash has ", hash.len, " elements"
echo "hash has key foo? ", hash.hasKey("foo")
echo "hash has key bar? ", hash.hasKey("bar")
echo "iterate pairs:" # iterating over (key, value) pairs
for key, value in hash:
echo key, ": ", value
echo "iterate keys:" # iterating over keys
for key in hash.keys:
echo key
echo "iterate values:" # iterating over values
for key in hash.values:
echo key |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #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_OUTPUT.PUT(VALUE * VALUE || ' ');
END;
SET I = 1;
WHILE (I <= 5) DO
CALL PRINT_SQUARE(NUMBERS[I]);
SET I = I + 1;
END WHILE;
CALL DBMS_OUTPUT.PUT_LINE('');
END;
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.
| #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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #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) = "[]][][][[]"
for i = 0 to 10
b$ = brk$(i)
while instr(b$,"[]") <> 0
x = instr(b$,"[]")
if x > 0 then b$ = left$(b$,x - 1) + mid$(b$,x + 2)
wend
if trim$(b$) = "" then print " OK "; else print "Not OK ";
print brk$(i)
next i |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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(Dictionary.Dictionary(Key,Value));
assocArray.Set("ten",NEW(Value,10));
assocArray.Set("eleven",NEW(Value,11));
aux := assocArray.Get("ten");
Out.LongInt(aux.value,0);Out.Ln;
aux := assocArray.Get("eleven");
Out.LongInt(aux.value,0);Out.Ln;Out.Ln;
(* Iterate keys *)
iterK := assocArray.IterKeys();
WHILE (iterK.Next(k)) DO
Out.Object(k);Out.Ln
END;
Out.Ln;
(* Iterate values *)
iterV := assocArray.IterValues();
WHILE (iterV.Next(aux)) DO
Out.LongInt(aux.value,0);Out.Ln
END
END AssociativeArray.
|
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) {
return(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.
| #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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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
}
(echo 3; echo 1; echo 4) | mean |
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #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 {
'[' => 1,
']' => -1,
_ => panic!("Strings should only contain brackets")
};
count += change;
if count < 0 { return false; }
}
count == 0
}
}
/// Generates random brackets
fn generate_brackets(num: usize) -> String {
use rand::random;
(0..num).map(|_| if random() { '[' } else { ']' }).collect()
}
fn main() {
for i in (0..10) {
let brackets = generate_brackets(i);
println!("{} {}", brackets, brackets.is_balanced())
}
} |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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();
map->Find("seven")->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 anonymous function and unnamed parameters
let isquares1 = numbers.lazy.map(square) // lazy sequence |
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
[ $numbers... -> $ * $ ] -> !OUT::write
[ $numbers... -> cube ] -> !OUT::write
|
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #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=>(random.nextDouble*100).toInt).filter(_>2).map(shuffleIt(_)).toList
}
def generate(n: Int): List[String] = {
val base = "["*n+"]"*n
var lb = ListBuffer[String]()
base.permutations.foreach(s=>lb+=s)
lb.toList.sorted
}
def checkBalance(brackets: String):Boolean = {
def balI(brackets: String, depth: Int):Boolean = {
if (brackets == "") depth == 0
else brackets(0) match {
case '[' => ((brackets.size > 1) && balI(brackets.substring(1), depth + 1))
case ']' => (depth > 0) && ((brackets.size == 1) || balI(brackets.substring(1), depth -1))
case _ => false
}
}
balI(brackets, 0)
}
println("arbitrary random order:")
generateRandom.map(s=>Pair(s,checkBalance(s))).foreach(p=>println((if(p._2) "balanced: " else "unbalanced: ")+p._1))
println("\n"+"check all permutations of given length:")
(1 to 5).map(generate(_)).flatten.map(s=>Pair(s,checkBalance(s))).foreach(p=>println((if(p._2) "balanced: " else "unbalanced: ")+p._1))
} |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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("callback", {1,2,3,4,5})
Disp map("√", {1,2,3,4,5}) |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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};
double[] zero_len = {};
double mean = arithmetic(test);
double mean_zero = arithmetic(zero_len);
stdout.printf("%s\n", mean.to_string());
stdout.printf("%s\n", mean_zero.to_string());
}
|
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #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 chars) (- sum 1)))
(else
(#f)))
(b (string->list string) 0))
(balanced-brackets "")
(balanced-brackets "[]")
(balanced-brackets "[][]")
(balanced-brackets "[[][]]")
(balanced-brackets "][")
(balanced-brackets "][][")
(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 insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #OCaml | OCaml | 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 item in the array )
a 5 [ 1 + ] map-array |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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()
Dim v(4) As Double
Dim i As Integer, leng As Integer
v(0) = 1#
v(1) = 2#
v(2) = 2.178
v(3) = 3#
v(4) = 3.142
For leng = 5 To 0 Step -1
Debug.Print "mean[";
For i = 0 To leng - 1
Debug.Print IIf(i, "; " & v(i), "" & v(i));
Next i
Debug.Print "] = "; mean(v, leng)
Next leng
End Sub |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #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 insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Ol | Ol |
;;; 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 100
2 200
7 777})
;;; add new key-value pair to the existing associative array
(define my-new-map (put my-map 'the-key 'the-value))
;;; print our arrays
(print empty-map)
; ==> #()
(print my-map)
; ==> #((1 . 100) (2 . 200) (7 . 777))
(print my-new-map)
; ==> #((1 . 100) (2 . 200) (7 . 777) (the-key . the-value))
|
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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #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
pos := rand(1, length(stri));
ch := stri[index];
stri @:= [index] stri[pos];
stri @:= [pos] ch;
end for;
end func;
const func boolean: checkBrackets (in string: test) is func
result
var boolean: okay is TRUE;
local
var char: ch is ' ';
var integer: open is 0;
begin
for ch range test do
if ch = '[' then
incr(open);
elsif ch = ']' then
if open = 0 then
okay := FALSE;
else
decr(open);
end if;
end if;
end for;
okay := open = 0;
end func;
const proc: main is func
local
var integer: n is 0;
var integer: count is 0;
var string: stri is "";
begin
for n range 0 to 4 do
for count range 1 to 3 do
stri := generateBrackets(n);
writeln(stri <& ": " <& checkBrackets(stri));
end for;
end for;
end func; |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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 x = 0 To S - 1 ' Reinitialize array
@(x) = x + 1
Next
Proc _MapArray (_Cosine, S) ' Call mapping procedure
Print : For x = 0 To S - 1 ' Print results
Print "COS(";x+1;") = ";Using "#.####";@(x)
Next
End
_MapArray Param(2) ' Param(1) = function
Local (1) ' Param(2) = array size
For c@ = 0 To b@ - 1
@(c@) = FUNC(a@(@(c@)))
Next
Return
_SquareRoot Param (1) ' This is an integer SQR subroutine
Local (2)
b@ = (10^(4*2)) * a@ ' Output is scaled by 10^4
a@ = b@
Do
c@ = (a@ + (b@ / a@))/2
Until (Abs(a@ - c@) < 2)
a@ = c@
Loop
Return (c@)
_Cosine Param(1) ' This is an integer COS subroutine
Push Abs((a@*10000)%62832) ' Output is scaled by 10^4
If Tos()>31416 Then Push 62832-Pop()
Let a@=Tos()>15708
If a@ Then Push 31416-Pop()
Push Tos()
Push (Pop()*Pop())/10000
Push 10000+((10000*-(Tos()/56))/10000)
Push 10000+((Pop()*-(Tos()/30))/10000)
Push 10000+((Pop()*-(Tos()/12))/10000)
Push 10000+((Pop()*-(Pop()/2))/10000)
If a@ Then Push -Pop() ' Result is directly transferred
Return ' through the stack |
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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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)],
[f64(3), 1, 4, 1, 5, 9],
[f64(10), 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11],
[f64(10), 20, 30, 40, 50, -100, 4.7, -11e2],
] {
println("Vector: $v")
m := arrays.fold(v, 0.0, fn(r f64, v f64) f64 { return r+v })/v.len
println("Mean of $v.len numbers is $m\n")
}
} |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #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 ", str)
} |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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
method dat(string k, d) as sys
sys i=find(k)
if i=0 then
if max>=n
print "Array overflow" : return 0
end if
max+=1
i=max*2-1
s[i]=k
end if
s[i+1]=d
return i
end method
end class
'====
'TEST
'====
AssociativeArray A
'fill
A.s<={"shoes","LC1", "ships","LC2", "sealingwax","LC3", "cabbages","LC4", "kings","LC5"}
A.max=5
'access
print A.dat("ships") 'result LC2
A.dat("computers")="LC99" '
print A.dat("computers") 'result LC99
|
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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 saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.