task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches ... | #Prolog | Prolog | median(L, Z) :-
length(L, Length),
I is Length div 2,
Rem is Length rem 2,
msort(L, S),
maplist(sumlist, [[I, Rem], [I, 1]], Mid),
maplist(nth1, Mid, [S, S], X),
sumlist(X, Y),
Z is Y/2. |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of p... | #Processing | Processing | void setup() {
float[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
println("Arithmetic mean: " + arithmeticMean(numbers));
println("Geometric mean: " + geometricMean(numbers));
println("Harmonic mean: " + harmonicMean(numbers));
}
float arithmeticMean(float[] nums) {
float mean = 0;
for (float n : nums) {
... |
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) ... | #Lua | Lua |
function isBalanced(s)
--Lua pattern matching has a 'balanced' pattern that matches sets of balanced characters.
--Any two characters can be used.
return s:gsub('%b[]','')=='' and true or false
end
function randomString()
math.randomseed(os.time())
math.random()math.random()math.random()math.random()
lo... |
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... | #Erlang | Erlang |
-module(assoc).
-compile([export_all]).
test_create() ->
D = dict:new(),
D1 = dict:store(foo,1,D),
D2 = dict:store(bar,2,D1),
print_vals(D2),
print_vals(dict:store(foo,3,D2)).
print_vals(D) ->
lists:foreach(fun (K) ->
io:format("~p: ~b~n",[K,dict:fetch(K,D)])
... |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #Rust | Rust | fn count_divisors(n: u64) -> usize {
if n < 2 {
return 1;
}
2 + (2..=(n / 2)).filter(|i| n % i == 0).count()
}
fn main() {
println!("The first 20 anti-primes are:");
(1..)
.scan(0, |max, n| {
let d = count_divisors(n);
Some(if d > *max {
*max... |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #Scala | Scala | def factorCount(num: Int): Int = Iterator.range(1, num/2 + 1).count(num%_ == 0) + 1
def antiPrimes: LazyList[Int] = LazyList.iterate((1: Int, 1: Int)){case (n, facs) => Iterator.from(n + 1).map(i => (i, factorCount(i))).dropWhile(_._2 <= facs).next}.map(_._1) |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Lasso | Lasso | define cube(n::integer) => #n*#n*#n
local(
mynumbers = array(1, 2, 3, 4, 5),
mycube = array
)
#mynumbers -> foreach => {
#mycube -> insert(cube(#1))
}
#mycube |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Lisaac | Lisaac | + a : ARRAY(INTEGER);
+ b : {INTEGER;};
a := ARRAY(INTEGER).create 1 to 3;
1.to 3 do { i : INTEGER;
a.put i to i;
};
b := { arg : INTEGER;
(arg * arg).print;
'\n'.print;
};
a.foreach b; |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked ... | #Objeck | Objeck |
class Iteration {
function : Main(args : String[]) ~ Nil {
assoc_array := Collection.StringMap->New();
assoc_array->Insert("Hello", IntHolder->New(1));
assoc_array->Insert("World", IntHolder->New(2));
assoc_array->Insert("!", IntHolder->New(3));
keys := assoc_array->GetKeys();
values := as... |
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... | #Mathprog | Mathprog |
/*Arithmetic Mean of a large number of Integers
- or - solve a very large constraint matrix
over 1 million rows and columns
Nigel_Galloway
March 18th., 2008.
*/
param e := 20;
set Sample := {1..2**e-1};
var Mean;
var E{z in Sample};
/* sum of variances is zero */
zumVariance: sum{z in Sample} E[z... |
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... | #MATLAB | MATLAB | function meanValue = findmean(setOfValues)
meanValue = mean(setOfValues);
end |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches ... | #Pure | Pure | median x = (/(2-rem)) $ foldl1 (+) $ take (2-rem) $ drop (mid-(1-rem)) $ sort (<=) x
when len = # x;
mid = len div 2;
rem = len mod 2;
end; |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches ... | #PureBasic | PureBasic | Procedure.d median(Array values.d(1), length.i)
If length = 0 : ProcedureReturn 0.0 : EndIf
SortArray(values(), #PB_Sort_Ascending)
If length % 2
ProcedureReturn values(length / 2)
EndIf
ProcedureReturn 0.5 * (values(length / 2 - 1) + values(length / 2))
EndProcedure
Procedure.i readArray(Array values.d... |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of p... | #PureBasic | PureBasic | Procedure.d ArithmeticMean()
For a = 1 To 10
mean + a
Next
ProcedureReturn mean / 10
EndProcedure
Procedure.d GeometricMean()
mean = 1
For a = 1 To 10
mean * a
Next
ProcedureReturn Pow(mean, 1 / 10)
EndProcedure
Procedure.d HarmonicMean()
For a = 1 To 10
mean.d + 1 / a
Next
ProcedureRetu... |
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) ... | #Maple | Maple |
> use StringTools in
> IsBalanced( "", "[", "]" );
> IsBalanced( "[", "[", "]" );
> IsBalanced( "]", "[", "]" );
> IsBalanced( "[]", "[", "]" );
> IsBalanced( "][", "[", "]" );
> IsBalanced( "[][]", "[", "]" );
> IsBalanced( "[[][]]", "[", "]" );
> IsBalanced( "[[[]][]]... |
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... | #F.23 | F# |
let dic = System.Collections.Generic.Dictionary<string,string>() ;;
dic.Add("key","val") ;
dic.["key"] <- "new val" ;
|
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func integer: countDivisors (in integer: number) is func
result
var integer: count is 1;
local
var integer: num is 0;
begin
for num range 1 to number div 2 do
if number rem num = 0 then
incr(count);
end if;
end for;
end func;
const proc: ma... |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #Sidef | Sidef | say with (0) {|max|
1..Inf -> lazy.grep { (.sigma0 > max) && (max = .sigma0) }.first(20)
} |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Logo | Logo | to square :x
output :x * :x
end
show map "square [1 2 3 4 5] ; [1 4 9 16 25]
show map [? * ?] [1 2 3 4 5] ; [1 4 9 16 25]
foreach [1 2 3 4 5] [print square ?] ; 1 4 9 16 25, one per line |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Lua | Lua | myArray = {1, 2, 3, 4, 5} |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked ... | #Objective-C | Objective-C | NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:13], @"hello",
[NSNumber numberWithInt:31], @"world",
[NSNumber numberWithInt:71], @"!", nil];
// iterating over keys:
for (id key in myDict) {
NSLog(@... |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked ... | #OCaml | OCaml | #!/usr/bin/env ocaml
let map = [| ('A', 1); ('B', 2); ('C', 3) |] ;;
(* iterate over pairs *)
Array.iter (fun (k,v) -> Printf.printf "key: %c - value: %d\n" k v) map ;;
(* iterate over keys *)
Array.iter (fun (k,_) -> Printf.printf "key: %c\n" k) map ;;
(* iterate over values *)
Array.iter (fun (_,v) -> Printf.... |
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... | #Maxima | Maxima | load("descriptive");
mean([2, 7, 11, 17]); |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin... | #MAXScript | MAXScript | fn mean data =
(
total = 0
for i in data do
(
total += i
)
if data.count == 0 then 0 else total as float/data.count
)
print (mean #(3, 1, 4, 1, 5, 9)) |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches ... | #Python | Python | def median(aray):
srtd = sorted(aray)
alen = len(srtd)
return 0.5*( srtd[(alen-1)//2] + srtd[alen//2])
a = (4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2)
print a, median(a)
a = (4.1, 7.2, 1.7, 9.3, 4.4, 3.2)
print a, median(a) |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches ... | #R | R | omedian <- function(v) {
if ( length(v) < 1 )
NA
else {
sv <- sort(v)
l <- length(sv)
if ( l %% 2 == 0 )
(sv[floor(l/2)+1] + sv[floor(l/2)])/2
else
sv[floor(l/2)+1]
}
}
a <- c(4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2)
b <- c(4.1, 7.2, 1.7, 9.3, 4.4, 3.2)
print(median(a)) # 4.4
print... |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of p... | #Python | Python | from operator import mul
from functools import reduce
def amean(num):
return sum(num) / len(num)
def gmean(num):
return reduce(mul, num, 1)**(1 / len(num))
def hmean(num):
return len(num) / sum(1 / n for n in num)
numbers = range(1, 11) # 1..10
a, g, h = amean(numbers), gmean(numbers), hmea... |
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) ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | (* Generate open/close events. *)
gen[n_] := RandomSample[Table[{1, -1}, {n}] // Flatten]
(* Check balance. *)
check[lst_] := And @@ (# >= 0 & /@ Accumulate[lst])
(* Do task for string with n opening and n closing brackets. *)
doString[n_] := (
lst = gen[n];
str = StringJoin[lst /. {1 -> "[", -1 -> "]"}];
Pri... |
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... | #Factor | Factor | H{ { "one" 1 } { "two" 2 } }
{ [ "one" swap at . ]
[ 2 swap value-at . ]
[ "three" swap at . ]
[ [ 3 "three" ] dip set-at ]
[ "three" swap at . ] } cleave |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #Swift | Swift | extension BinaryInteger {
@inlinable
public func countDivisors() -> Int {
var workingN = self
var count = 1
while workingN & 1 == 0 {
workingN >>= 1
count += 1
}
var d = Self(3)
while d * d <= workingN {
var (quo, rem) = workingN.quotientAndRemainder(dividingBy: d)
... |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #Tcl | Tcl |
proc countDivisors {n} {
if {$n < 2} {return 1}
set count 2
set n2 [expr $n / 2]
for {set i 2} {$i <= $n2} {incr i} {
if {[expr $n % $i] == 0} {incr count}
}
return $count
}
# main
set maxDiv 0
set count 0
puts "The first 20 anti-primes are:"
for {set n 1} {$count < 20} {incr n} {
set d [countDi... |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #M2000_Interpreter | M2000 Interpreter |
a=(1,2,3,4,5)
b=lambda->{
push number**2
}
Print a#map(b) ' 1 4 9 16 25
Print a#map(b, b) ' 1 16 81 256 625
b=lambda (z) ->{
=lambda z ->{
push number**z
}
}
Print a#map(b(2)) ' 1 4 9 16 25
Print a#map(b(3)) ' 1 8 27 64 125
\\ second example
a=(1,2,3,4,5)
class s {sum=0}
\\ s is a pointer to an instance of... |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #M4 | M4 | define(`foreach', `pushdef(`$1')_foreach($@)popdef(`$1')')dnl
define(`_arg1', `$1')dnl
define(`_foreach', `ifelse(`$2', `()', `',
`define(`$1', _arg1$2)$3`'$0(`$1', (shift$2), `$3')')')dnl
dnl
define(`apply',`foreach(`x',$1,`$2(x)')')dnl
dnl
define(`z',`eval(`$1*2') ')dnl
apply(`(1,2,3)',`z') |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked ... | #Ol | Ol |
;;; create sample associative array
(define aa (list->ff '(
(hello . 1)
(world . 2)
(! . 3))))
(print aa)
; ==> #((! . 3) (hello . 1) (world . 2))
;;; simplest iteration over all associative array (using ff-iter, lazy iterator)
(let loop ((kv (ff-iter aa)))
(cond
((null? kv) #true)
((pair?... |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked ... | #ooRexx | ooRexx | d = .directory~new
d["hello"] = 1
d["world"] = 2
d["!"] = 3
-- iterating over keys:
loop key over d
say "key =" key
end
-- iterating over values:
loop value over d~allitems
say "value =" value
end
-- iterating over key-value pairs:
s = d~supplier
loop while s~available
say "key =" s~index", value =" s... |
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... | #Mercury | Mercury | :- module arithmetic_mean.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module float, list, require.
main(!IO) :-
io.print_line(mean([1.0, 2.0, 3.0, 4.0, 5.0]), !IO).
:- func mean(list(float)) = float.
mean([]) = func_error("mean: emtpy list").
m... |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin... | #min | min | (((0 (+) reduce) (size /)) cleave) :mean
(2 3 5) mean print |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches ... | #Racket | Racket | #lang racket
(define (median numbers)
(define sorted (list->vector (sort (vector->list numbers) <)))
(define count (vector-length numbers))
(if (zero? count)
#f
(/ (+ (vector-ref sorted (floor (/ (sub1 count) 2)))
(vector-ref sorted (floor (/ count 2))))
2)))
(median '#(5 3 4)) ... |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches ... | #Raku | Raku | sub median {
my @a = sort @_;
return (@a[(*-1) div 2] + @a[* div 2]) / 2;
} |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of p... | #Quackery | Quackery | [] 10 times [ i^ 1+ join ]
say "Arithmetic mean:" sp
0 over witheach +
over size 8 point$ echo$
cr
say " Geometric mean:" sp
1 over witheach *
over size 80 ** * 10 root
10 8 ** 8 point$ echo$
cr
say " Harmonic mean:" sp
dup size dip
[ 0 n->v rot
witheach [ n->v 1/v v+ ] ]
n->v 2sw... |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of p... | #R | R |
x <- 1:10
|
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) ... | #MATLAB_.2F_Octave | MATLAB / Octave | function x = isbb(s)
t = cumsum((s=='[') - (s==']'));
x = all(t>=0) && (t(end)==0);
end;
|
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element ins... | #Fantom | Fantom |
class Main
{
public static Void main ()
{
// create a map which maps Ints to Strs, with given key-value pairs
Int:Str map := [1:"alpha", 2:"beta", 3:"gamma"]
// create an empty map
Map map2 := [:]
// now add some numbers mapped to their doubles
10.times |Int i|
{
map2[i] = 2*... |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #Tiny_BASIC | Tiny BASIC | 100 LET A=0
101 LET N=1
102 LET H=0
103 PRINT "The first 20 anti-primes are:"
105 GOSUB 150
106 LET H=F
107 LET A=A+1
108 PRINT N
109 LET N=N+1
110 IF A<20 THEN GOTO 105
111 END
150 GOSUB 200
151 IF F>H THEN RETURN
152 LET N=N+1
153 GOTO 150
200 LET F=0
201 LET C=1
205 IF N/C*C=N THEN LET F=F+1
206 LET C=C+1
207 IF C<=... |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #Transd | Transd |
#lang transd
MainModule: {
countDivs: (λ n Int() ret_ Int()
(= ret_ 2)
(for i in Range(2 (to-Int (/ (to-Double n) 2) 1)) do
(if (not (mod n i)) (+= ret_ 1)))
(ret ret_)
),
_start: (λ max 0 tmp 0 N 1 i 2
(textout 1 " ")
(while (< N 20)
(=... |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Maple | Maple |
> map( sqrt, [ 1.1, 3.2, 5.7 ] );
[1.048808848, 1.788854382, 2.387467277]
> map( x -> x + 1, { 1, 3, 5 } );
{2, 4, 6}
> sqrt~( [ 1.1, 3.2, 5.7 ] );
[1.048808848, 1.788854382, 2.387467277]
> (x -> x + 1)~( { 1, 3, 5 } );
... |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Mathematica.2F.2FWolfram_Language | Mathematica//Wolfram Language | (#*#)& /@ {1, 2, 3, 4}
Map[Function[#*#], {1, 2, 3, 4}]
Map[((#*#)&,{1,2,3,4}]
Map[Function[w,w*w],{1,2,3,4}] |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked ... | #Oz | Oz | declare
MyMap = unit('hello':13 'world':31 '!':71)
in
{ForAll {Record.toListInd MyMap} Show} %% pairs
{ForAll {Record.arity MyMap} Show} %% keys
{ForAll {Record.toList MyMap} Show} %% values |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin... | #MiniScript | MiniScript | arr = [ 1, 3, 7, 8, 9, 1 ]
avg = function(arr)
avgNum = 0
for num in arr
avgNum = avgNum + num
end for
return avgNum / arr.len
end function
print avg(arr) |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin... | #.D0.9C.D0.9A-61.2F52 | МК-61/52 | 0 П0 П1 С/П ИП0 ИП1 * + ИП1 1
+ П1 / П0 БП 03 |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches ... | #REBOL | REBOL |
median: func [
"Returns the midpoint value in a series of numbers; half the values are above, half are below."
block [any-block!]
/local len mid
][
if empty? block [return none]
block: sort copy block
len: length? block
mid: to integer! len / 2
either odd? len [
pick block add ... |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of p... | #Racket | Racket |
#lang racket
(define (arithmetic xs)
(/ (for/sum ([x xs]) x)
(length xs)))
(define (geometric xs)
(expt (for/product ([x xs]) x)
(/ (length xs))))
(define (harmonic xs)
(/ (length xs)
(for/sum ([x xs]) (/ x))))
(define xs (range 1 11))
(arithmetic xs)
(geometric xs)
(harmonic xs)
(>= (... |
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) ... | #Maxima | Maxima | brack(s) := block(
[n: slength(s), r: 0, c],
catch(
for i thru n do (
if cequal(c: charat(s, i), "]") then (if (r: r - 1) < 0 then throw(false))
elseif cequal(c, "[") then r: r + 1
),
is(r = 0)
)
)$
brack("");
true
brack("[");
false
brack("]");
false
brack("[]");
tru... |
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... | #Forth | Forth | : get ( key len table -- data ) \ 0 if not present
search-wordlist if
>body @
else 0 then ;
: put ( data key len table -- )
>r 2dup r@ search-wordlist if
r> drop nip nip
>body !
else
r> get-current >r set-current \ switch definition word lists
nextname create ,
r> set-current
... |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #Vala | Vala | int count_divisors(int n) {
if (n < 2) return 1;
var count = 2;
for (int i = 2; i <= n/2; ++i)
if (n%i == 0) ++count;
return count;
}
void main() {
var max_div = 0;
var count = 0;
stdout.printf("The first 20 anti-primes are:\n");
for (int n = 1; count < 20; ++n) {
var d = count_divisors(n);
... |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #MATLAB | MATLAB | >> array = [1 2 3 4 5]
array =
1 2 3 4 5
>> arrayfun(@sin,array)
ans =
Columns 1 through 4
0.841470984807897 0.909297426825682 0.141120008059867 -0.756802495307928
Column 5
-0.958924274663138
>> cellarray = {1,2,3,4,5}
cellarray =
[1] [2] [3] [4] ... |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked ... | #PARI.2FGP | PARI/GP | keys = Vec(M); |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked ... | #Perl | Perl | #! /usr/bin/perl
use strict;
my %pairs = ( "hello" => 13,
"world" => 31,
"!" => 71 );
# iterate over pairs
# Be careful when using each(), however, because it uses a global iterator
# associated with the hash. If you call keys() or values() on the hash in the
# middle of the loop, the each() iterato... |
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... | #Modula-2 | Modula-2 | PROCEDURE Avg;
VAR avg : REAL;
BEGIN
avg := sx / n;
InOut.WriteString ("Average = ");
InOut.WriteReal (avg, 8, 2);
InOut.WriteLn
END Avg; |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin... | #MUMPS | MUMPS | MEAN(X)
;X is assumed to be a list of numbers separated by "^"
QUIT:'$DATA(X) "No data"
QUIT:X="" "Empty Set"
NEW S,I
SET S=0,I=1
FOR QUIT:I>$L(X,"^") SET S=S+$P(X,"^",I),I=I+1
QUIT (S/$L(X,"^")) |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches ... | #ReScript | ReScript | let median = (arr) =>
{
let float_compare = (a, b) => {
let diff = a -. b
if diff == 0.0 { 0 } else
if diff > 0.0 { 1 } else { -1 }
}
let _ = Js.Array2.sortInPlaceWith(arr, float_compare)
let count = Js.Array.length(arr)
// find the middle value, or the lowest middle value
let ... |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches ... | #REXX | REXX | /*REXX program finds the median of a vector (and displays the vector and median).*/
/* ══════════vector════════════ ══show vector═══ ════════show result═══════════ */
v= 1 9 2 4 ; say "vector" v; say 'median──────►' median(v); say
v= 3 1 4 1 5 9 7 6 ; say "vector"... |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of p... | #Raku | Raku | sub A { ([+] @_) / @_ }
sub G { ([*] @_) ** (1 / @_) }
sub H { @_ / [+] 1 X/ @_ }
say "A(1,...,10) = ", A(1..10);
say "G(1,...,10) = ", G(1..10);
say "H(1,...,10) = ", H(1..10);
|
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) ... | #Mercury | Mercury |
:- module balancedbrackets.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- import_module list, random, char.
:- pred brackets(int::in,list(char)::out,supply::mdi,supply::muo) is det.
:- pred imbalance(list(char)::in,int::out) is semidet.
:- pred balanced(list(char)::in) is semi... |
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... | #FreeBASIC | FreeBASIC | #define max(a, b) Iif(a>b,a,b)
enum datatype
'for this demonstration we'll allow these five data types
BOOL
STRNG
BYYTE
INTEG
FLOAT
end enum
union value
bool as boolean
strng as string*32
byyte as byte
integ as integer
float as double
end union
type dicitem
'one par... |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #VBA | VBA | Private Function factors(n As Integer) As Collection
Dim f As New Collection
For i = 1 To Sqr(n)
If n Mod i = 0 Then
f.Add i
If n / i <> i Then f.Add n / i
End If
Next i
f.Add n
Set factors = f
End Function
Public Sub anti_primes()
Dim n As Integer, maxd A... |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function CountDivisors(n As Integer) As Integer
If n < 2 Then
Return 1
End If
Dim count = 2 '1 and n
For i = 2 To n \ 2
If n Mod i = 0 Then
count += 1
End If
Next
Return count
End Function
... |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Maxima | Maxima | /* for lists or sets */
map(sin, [1, 2, 3, 4]);
map(sin, {1, 2, 3, 4});
/* for matrices */
matrixmap(sin, matrix([1, 2], [2, 4])); |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #min | min | (1 2 3 4 5) (sqrt puts) foreach ; print each square root
(1 2 3 4 5) 'sqrt map ; collect return values |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked ... | #Phix | Phix | with javascript_semantics
setd("one",1)
setd(2,"duo")
setd({3,4},{5,"six"})
function visitor(object key, object data, object /*userdata*/)
?{key,data}
return 1 -- (continue traversal)
end function
traverse_dict(routine_id("visitor"))
|
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked ... | #Phixmonti | Phixmonti | include ..\Utilitys.pmt
def getd /# dict key -- dict data #/
swap 1 get rot find nip
dup if
swap 2 get rot get nip
else
drop "Unfound"
endif
enddef
def setd /# dict ( key data ) -- dict #/
1 get var ikey
2 get var idata
drop
1 get ikey find var p drop
p if... |
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... | #Nanoquery | Nanoquery | def sum(lst)
sum = 0
for n in lst
sum += n
end
return sum
end
def average(x)
return sum(x) / len(x)
end |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin... | #Nemerle | Nemerle | using System;
using System.Console;
using Nemerle.Collections;
module Mean
{
ArithmeticMean(x : list[int]) : double
{
|[] => 0.0
|_ =>(x.FoldLeft(0, _+_) :> double) / x.Length
}
Main() : void
{
WriteLine("Mean of [1 .. 10]: {0}", ArithmeticMean($[1 .. 10]));
}
} |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches ... | #Ring | Ring |
aList = [5,4,2,3]
see "medium : " + median(aList) + nl
func median aray
srtd = sort(aray)
alen = len(srtd)
if alen % 2 = 0
return (srtd[alen/2] + srtd[alen/2 + 1]) / 2.0
else return srtd[ceil(alen/2)] ok
|
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches ... | #Ruby | Ruby | def median(ary)
return nil if ary.empty?
mid, rem = ary.length.divmod(2)
if rem == 0
ary.sort[mid-1,2].inject(:+) / 2.0
else
ary.sort[mid]
end
end
p median([]) # => nil
p median([5,3,4]) # => 4
p median([5,4,2,3]) # => 3.5
p median([3,4,1,-8.4... |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of p... | #REXX | REXX | /*REXX program computes and displays the Pythagorean means [Amean, Gmean, Hmean]. */
numeric digits 20 /*use a little extra for the precision.*/
parse arg n . /*obtain the optional argument from CL.*/
if n=='' | n=="," then n= 10 ... |
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) ... | #MiniScript | MiniScript | isBalanced = function(str)
level = 0
for c in str
if c == "[" then level = level + 1
if c == "]" then level = level - 1
if level < 0 then return false
end for
return level == 0
end function |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element ins... | #Free_Pascal | Free Pascal | program AssociativeArrayCreation;
{$IFDEF FPC}{$MODE DELPHI}{$ENDIF}
{$IFDEF WINDOWS}{$APPTYPE CONSOLE}{$ENDIF}
uses Generics.Collections;
var
lDictionary: TDictionary<string, Integer>;
begin
lDictionary := TDictionary<string, Integer>.Create;
try
lDictionary.Add('foo', 5);
lDictionary.Add('bar', 10);
... |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #Vlang | Vlang | fn count_divisors(n int) int {
if n < 2 {
return 1
}
mut count := 2 // 1 and n
for i := 2; i <= n/2; i++ {
if n%i == 0 {
count++
}
}
return count
}
fn main() {
println("The first 20 anti-primes are:")
mut max_div := 0
mut count := 0
for n := ... |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #Wren | Wren | import "/math" for Int
System.print("The first 20 anti-primes are:")
var maxDiv = 0
var count = 0
var n = 1
while (count < 20) {
var d = Int.divisors(n).count
if (d > maxDiv) {
System.write("%(n) ")
maxDiv = d
count = count + 1
}
n = n + 1
}
System.print() |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Modula-3 | Modula-3 | MODULE Callback EXPORTS Main;
IMPORT IO, Fmt;
TYPE CallBack = PROCEDURE (a: CARDINAL; b: INTEGER);
Values = REF ARRAY OF INTEGER;
VAR sample := ARRAY [1..5] OF INTEGER {5, 4, 3, 2, 1};
callback := Display;
PROCEDURE Display(loc: CARDINAL; val: INTEGER) =
BEGIN
IO.Put("array[" & Fmt.Int(loc) & "] ... |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked ... | #PHP | PHP | <?php
$pairs = array( "hello" => 1,
"world" => 2,
"!" => 3 );
// iterate over key-value pairs
foreach($pairs as $k => $v) {
echo "(k,v) = ($k, $v)\n";
}
// iterate over keys
foreach(array_keys($pairs) as $key) {
echo "key = $key, value = $pairs[$key]\n";
}
// iterate over values
foreach($pairs as $val... |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked ... | #Picat | Picat | go =>
Map = new_map([1=one,2=two,3=three,4=four]),
foreach(K=V in Map)
println(K=V)
end,
nl,
println(keys=Map.keys),
foreach(K in Map.keys.sort)
println(K=Map.get(K))
end,
nl,
println(values=Map.values),
foreach(V in Map.values.sort)
% This works but gets a warning: nonlocal_var_in... |
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... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
launchSample()
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method arithmeticMean(vv = Vector) public static signals DivideException returns Rexx
sum = 0
n_ = Rexx
loop n_ over vv
sum = ... |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches ... | #Run_BASIC | Run BASIC | sqliteconnect #mem, ":memory:"
mem$ = "CREATE TABLE med (x float)"
#mem execute(mem$)
a$ ="4.1,5.6,7.2,1.7,9.3,4.4,3.2" :gosub [median]
a$ ="4.1,7.2,1.7,9.3,4.4,3.2" :gosub [median]
a$ ="4.1,4,1.2,6.235,7868.33" :gosub [median]
a$ ="1,5,3,2,4" :gosub [median]
a$ ="1,5,3,6,4,2" :gosub [median]
a$ ... |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches ... | #Rust | Rust | fn median(mut xs: Vec<f64>) -> f64 {
// sort in ascending order, panic on f64::NaN
xs.sort_by(|x,y| x.partial_cmp(y).unwrap() );
let n = xs.len();
if n % 2 == 0 {
(xs[n/2] + xs[n/2 - 1]) / 2.0
} else {
xs[n/2]
}
}
fn main() {
let nums = vec![2.,3.,5.,0.,9.,82.,353.,32.,12.]... |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of p... | #Ring | Ring |
decimals(8)
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
see "arithmetic mean = " + arithmeticMean(array) + nl
see "geometric mean = " + geometricMean(array) + nl
see "harmonic mean = " + harmonicMean(array) + nl
func arithmeticMean a
return summary(a) / len(a)
func geometricMean a
b = 1
for i = 1 ... |
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) ... | #Modula-2 | Modula-2 |
MODULE Brackets;
IMPORT IO, Lib;
CONST MaxN = 4;
PROCEDURE DoTest( N : CARDINAL);
VAR
brStr : ARRAY [0..2*MaxN] OF CHAR; (* string of brackets *)
verdict : ARRAY [0..2] OF CHAR;
br : CHAR;
k, nL, nR, randNum : CARDINAL;
count : INTEGER;
BEGIN
k := 0; (* index into brStr *)
nL := N; nR := N; (* numbe... |
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... | #Futhark | Futhark | let associative_array = {key1=1,key2=2} |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #XPL0 | XPL0 | int Counter, Num, Cnt, Div, Max;
[Counter:= 0;
Max:= 0;
Num:= 1;
loop [Cnt:= 0;
Div:= 1;
repeat if rem(Num/Div) = 0 then Cnt:= Cnt+1;
Div:= Div+1;
until Div > Num;
if Cnt > Max then
[IntOut(0, Num); ChOut(0, ^ );
Max:= Cnt;
... |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #Yabasic | Yabasic | print "The first 20 anti-primes are:"
while (count < 20)
n = n + 1
d = count_divisors(n)
if d > max_divisors then
print n;
max_divisors = d
count = count + 1
end if
wend
print
sub count_divisors(n)
local count, i
if n < 2 return 1
count = 2
for i = 2 to n/... |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Nanoquery | Nanoquery | // create a list of numbers 1-10
numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
// display the list as it is
println numbers
// square each element in the list
for i in range(1, len(numbers) - 1)
numbers[i] = numbers[i] * numbers[i]
end
// display the squared list
println numbers |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Nemerle | Nemerle | def seg = array[1, 2, 3, 5, 8, 13];
def squares = seq.Map(x => x*x); |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked ... | #PicoLisp | PicoLisp | (put 'A 'foo 5)
(put 'A 'bar 10)
(put 'A 'baz 15)
: (getl 'A) # Get the whole property list
-> ((15 . baz) (10 . bar) (5 . foo))
: (mapcar cdr (getl 'A)) # Get all keys
-> (baz bar foo)
: (mapcar car (getl 'A)) # Get all values
-> (15 10 5) |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked ... | #Pike | Pike |
mapping(string:string) m = ([ "A":"a", "B":"b", "C":"c" ]);
foreach(m; string key; string value)
{
write(key+value);
}
Result: BbAaCc
// only keys
foreach(m; string key;)
{
write(key);
}
Result: BAC
// only values
foreach(m;; string value)
{
write(value);
}
Result: bac
|
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin... | #NewLISP | NewLISP | (define (Mean Lst)
(if (empty? Lst)
0
(/ (apply + Lst) (length Lst))))
(Mean (sequence 1 1000))-> 500
(Mean '()) -> 0 |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin... | #Nial | Nial | mean is / [sum, tally]
mean 6 2 4
= 4 |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches ... | #Scala | Scala | def median[T](s: Seq[T])(implicit n: Fractional[T]) = {
import n._
val (lower, upper) = s.sortWith(_<_).splitAt(s.size / 2)
if (s.size % 2 == 0) (lower.last + upper.head) / fromInt(2) else upper.head
} |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of p... | #Ruby | Ruby | class Array
def arithmetic_mean
inject(0.0, :+) / length
end
def geometric_mean
inject(:*) ** (1.0 / length)
end
def harmonic_mean
length / inject(0.0) {|s, m| s + 1.0/m}
end
end
class Range
def method_missing(m, *args)
case m
when /_mean$/ then to_a.send(m)
else super
en... |
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) ... | #Nanoquery | Nanoquery | import Nanoquery.Util
def gen(N)
txt = {"[", "]"} * N
txt = new(Random).shuffle(txt)
return "".join("", txt)
end
def balanced(txt)
braced = 0
for ch in txt
if ch = "["
braced += 1
else if ch = "]"
braced -= 1
end
if braced < 0
return false
end
end
return braced = 0
end
// unlike Python... |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.