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/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... | #Lasso | Lasso | define average(a::array) => {
not #a->size ? return 0
local(x = 0.0)
with i in #a do => { #x += #i }
return #x / #a->size
}
average(array(1,2,5,17,7.4)) //6.48 |
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... | #LFE | LFE |
(defun mean (data)
(/ (lists:sum data)
(length data)))
|
http://rosettacode.org/wiki/Attractive_numbers | Attractive numbers | A number is an attractive number if the number of its prime factors (whether distinct or not) is also prime.
Example
The number 20, whose prime decomposition is 2 × 2 × 5, is an attractive number because the number of its prime factors (3) is also prime.
Task
Show sequence items up to 120.... | #Vlang | Vlang | fn is_prime(n int) bool {
if n < 2 {
return false
}
else if n%2 == 0 {
return n == 2
}
else if n%3 == 0 {
return n == 3
}
else {
mut d := 5
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
... |
http://rosettacode.org/wiki/Attractive_numbers | Attractive numbers | A number is an attractive number if the number of its prime factors (whether distinct or not) is also prime.
Example
The number 20, whose prime decomposition is 2 × 2 × 5, is an attractive number because the number of its prime factors (3) is also prime.
Task
Show sequence items up to 120.... | #Wren | Wren | import "/fmt" for Fmt
import "/math" for Int
var max = 120
System.print("The attractive numbers up to and including %(max) are:")
var count = 0
for (i in 1..max) {
var n = Int.primeFactors(i).count
if (Int.isPrime(n)) {
System.write(Fmt.d(4, i))
count = count + 1
if (count%20 == 0) Sy... |
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 ... | #Oz | Oz | declare
fun {Median Xs}
Len = {Length Xs}
Mid = Len div 2 + 1 %% 1-based index
Sorted = {Sort Xs Value.'<'}
in
if {IsOdd Len} then {Nth Sorted Mid}
else ({Nth Sorted Mid} + {Nth Sorted Mid-1}) / 2.0
end
end
in
{Show {Median [4.1 5.6 7.2 1.7 9.3 4.4 3.2]}}
{Show {Median [4.1 7.2 1... |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of p... | #Perl | Perl | sub A
{
my $a = 0;
$a += $_ for @_;
return $a / @_;
}
sub G
{
my $p = 1;
$p *= $_ for @_;
return $p**(1/@_); # power of 1/n == root of n
}
sub H
{
my $h = 0;
$h += 1/$_ for @_;
return @_/$h;
}
my @ints = (1..10);
my $a = A(@ints);
my $g = G(@int... |
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) ... | #K | K |
gen_brackets:{"[]"@x _draw 2}
check:{r:(-1;1)@"["=x; *(0=+/cs<'0)&(0=-1#cs:+\r)}
{(x;check x)}' gen_brackets' 2*1+!10
(("[[";0)
("[][]";1)
("][][]]";0)
("[[][[][]";0)
("][]][[[[[[";0)
("]]][[]][]]][";0)
("[[[]][[[][[[][";0)
("[[]][[[]][]][][]";1)
("][[][[]]][[]]]][][";0)
("]][[[[]]]][][][[]]]]";0))
|
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file | Append a record to the end of a text file | Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment.
This feature is most useful in the case of log files,... | #UNIX_Shell | UNIX Shell | rec1=(
jsmith
x
1001
1000
"Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org"
/home/jsmith
/bin/bash
)
rec2=(
jdoe
x
1002
1000
"Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org"
/home/jdoe
/bin/bash
)
rec3=(
xyz
... |
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file | Append a record to the end of a text file | Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment.
This feature is most useful in the case of log files,... | #Ursa | Ursa | # ursa appends to files by default when the out function is used
# create new passwd in working directory
decl file f
f.create "passwd"
f.open "passwd"
out "account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell" endl f
out "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-007... |
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... | #Delphi | Delphi | program AssociativeArrayCreation;
{$APPTYPE CONSOLE}
uses Generics.Collections;
var
lDictionary: TDictionary<string, Integer>;
begin
lDictionary := TDictionary<string, Integer>.Create;
try
lDictionary.Add('foo', 5);
lDictionary.Add('bar', 10);
lDictionary.Add('baz', 15);
lDictionary.AddOrSet... |
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
| #Processing | Processing | void setup() {
int most_factors = 0;
IntList anti_primes = new IntList();
int n = 1;
while (anti_primes.size() < 20) {
int counter = 1;
for (int i = 1; i <= n / 2; i++) {
if (n % i == 0) {
counter++;
}
}
if (counter > most_factors) {
anti_primes.append(n);
most_fa... |
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
| #Prolog | Prolog |
divcount(N, Count) :- divcount(N, 1, 0, Count).
divcount(N, D, C, C) :- D*D > N, !.
divcount(N, D, C, Count) :-
succ(D, D2),
divs(N, D, A), plus(A, C, C2),
divcount(N, D2, C2, Count).
divs(N, D, 0) :- N mod D =\= 0, !.
divs(N, D, 1) :- D*D =:= N, !.
divs(_, _, 2).
antiprimes(N, L) :- antiprimes(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.
| #Java | Java | public class ArrayCallback7 {
interface IntConsumer {
void run(int x);
}
interface IntToInt {
int run(int x);
}
static void forEach(int[] arr, IntConsumer consumer) {
for (int i : arr) {
consumer.run(i);
}
}
static void update(int[] arr, In... |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat... | #UNIX_Shell | UNIX Shell | #!/bin/bash
function mode {
declare -A map
max=0
for x in "$@"; do
tmp=$((${map[$x]} + 1))
map[$x]=$tmp
((tmp > max)) && max=$tmp
done
for x in "${!map[@]}"; do
[[ ${map[$x]} == $max ]] && echo -n "$x "
done
echo
} |
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 ... | #Lua | Lua | local t = {
["foo"] = "bar",
["baz"] = 6,
fortytwo = 7
}
for key,val in pairs(t) do
print(string.format("%s: %s", key, val))
end |
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 ... | #M2000_Interpreter | M2000 Interpreter |
Module checkit {
\\ Inventories are objects with keys and values, or keys (used as read only values)
\\ They use hash function.
\\ Function TwoKeys return Inventory object (as a pointer to object)
Function TwoKeys {
Inventory Alfa="key1":=100, "key2":=200
=Alfa
}
... |
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... | #Liberty_BASIC | Liberty BASIC | total=17
dim nums(total)
for i = 1 to total
nums(i)=i-1
next
for j = 1 to total
sum=sum+nums(j)
next
if total=0 then mean=0 else mean=sum/total
print "Arithmetic mean: ";mean
|
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin... | #Limbo | Limbo | implement Command;
include "sys.m";
sys: Sys;
include "draw.m";
include "sh.m";
init(nil: ref Draw->Context, nil: list of string)
{
sys = load Sys Sys->PATH;
a := array[] of {1.0, 2.0, 500.0, 257.0};
sys->print("mean of a: %f\n", getmean(a));
}
getmean(a: array of real): real
{
n: real = 0.0;
for (i :=... |
http://rosettacode.org/wiki/Attractive_numbers | Attractive numbers | A number is an attractive number if the number of its prime factors (whether distinct or not) is also prime.
Example
The number 20, whose prime decomposition is 2 × 2 × 5, is an attractive number because the number of its prime factors (3) is also prime.
Task
Show sequence items up to 120.... | #XPL0 | XPL0 | func IsPrime(N); \Return 'true' if N is prime
int N, I;
[if N <= 2 then return N = 2;
if (N&1) = 0 then \even >2\ return false;
for I:= 3 to sqrt(N) do
[if rem(N/I) = 0 then return false;
I:= I+1;
];
return true;
];
func Factors(N); \Return number of factors for N
int N, Cnt, F;
[Cnt:= 0;
... |
http://rosettacode.org/wiki/Attractive_numbers | Attractive numbers | A number is an attractive number if the number of its prime factors (whether distinct or not) is also prime.
Example
The number 20, whose prime decomposition is 2 × 2 × 5, is an attractive number because the number of its prime factors (3) is also prime.
Task
Show sequence items up to 120.... | #zkl | zkl | var [const] BI=Import("zklBigNum"); // libGMP
fcn attractiveNumber(n){ BI(primeFactors(n).len()).probablyPrime() }
println("The attractive numbers up to and including 120 are:");
[1..120].filter(attractiveNumber)
.apply("%4d".fmt).pump(Void,T(Void.Read,19,False),"println"); |
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 ... | #PARI.2FGP | PARI/GP | median(v)={
vecsort(v)[#v\2]
}; |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches ... | #Pascal | Pascal | Program AveragesMedian(output);
type
TDoubleArray = array of double;
procedure bubbleSort(var list: TDoubleArray);
var
i, j, n: integer;
t: double;
begin
n := length(list);
for i := n downto 2 do
for j := 0 to i - 1 do
if list[j] > list[j + 1] then
begin
t := list[j];
list[... |
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... | #Phix | Phix | with javascript_semantics
function arithmetic_mean(sequence s)
return sum(s)/length(s)
end function
function geometric_mean(sequence s)
return power(product(s),1/length(s))
end function
function harmonic_mean(sequence s)
return length(s)/sum(sq_div(1,s))
end function
constant s = {1,2,3,4,5,6,7,8,9,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) ... | #Klingphix | Klingphix | "[[]][]]"
%acc 0 !acc
%flag false !flag
len [
get tochar dup
"[" == [$acc 1 + !acc] if
"]" == [$acc 1 - !acc] if
$acc 0 < [true !flag] if
] for
print
$acc 0 # $flag or ( [" is NOT ok"] [" is OK"] ) if
print
" " input |
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file | Append a record to the end of a text file | Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment.
This feature is most useful in the case of log files,... | #Visual_Basic_.NET | Visual Basic .NET | Imports System.IO
Module Module1
Class PasswordRecord
Public account As String
Public password As String
Public fullname As String
Public office As String
Public extension As String
Public homephone As String
Public email As String
Public directory... |
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... | #Dyalect | Dyalect | var t = (x: 1, y: 2, z: 3)
print(t.Keys().ToArray()) |
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
| #PureBasic | PureBasic | Procedure.i cntDiv(n.i)
Define.i i, count
If n < 2 : ProcedureReturn 1 : EndIf
count = 2 : i = 2
While i <= n / 2
If n % i = 0 : count + 1 : EndIf
i + 1
Wend
ProcedureReturn count
EndProcedure
; - - - MAIN - - -
Define.i n = 1, d, maxDiv = 0, count = 0
If OpenConsole("")
PrintN("The... |
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
| #Python | Python | from itertools import chain, count, cycle, islice, accumulate
def factors(n):
def prime_powers(n):
for c in accumulate(chain([2, 1, 2], cycle([2,4]))):
if c*c > n: break
if n%c: continue
d,p = (), c
while not n%c:
n,p,d = n//c, p*c, d+(p,)
... |
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.
| #JavaScript | JavaScript | function map(a, func) {
var ret = [];
for (var i = 0; i < a.length; i++) {
ret[i] = func(a[i]);
}
return ret;
}
map([1, 2, 3, 4, 5], 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.
| #Joy | Joy | [1 2 3 4 5] [dup *] map. |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat... | #Ursala | Ursala | #import std
mode = ~&hS+ leql$^&h+ eql|=@K2
#cast %nLW
examples = mode~~ (<1,3,6,6,6,7,7,12,12,17>,<1,1,2,4,4>) |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat... | #VBA | VBA | Public Sub main()
s = [{1,2,3,3,3,4,4,4,5,5,6}]
t = WorksheetFunction.Mode_Mult(s)
For Each x In t
Debug.Print x;
Next x
End Sub |
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 ... | #M4 | M4 | divert(-1)
define(`for',
`ifelse($#,0,``$0'',
`ifelse(eval($2<=$3),1,
`pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')')
define(`new',`define(`$1[size]key',0)')
define(`asize',`defn(`$1[size]key')')
define(`aget',`defn(`$1[$2]')')
define(`akget',`defn(`$1[$2]key')')
define(`avget',`aget($1,akget(... |
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 ... | #Maple | Maple |
> T := table( [ "A" = 1, "B" = 2, "C" = 3, "D" = 4 ] );
> for i in indices( T, nolist ) do print(i ) end:
"A"
"B"
"C"
"D"
|
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... | #Lingo | Lingo | -- v can be (2D) point, (3D) vector or list of integers/floats
on mean (v)
case ilk(v) of
#point: cnt = 2
#vector: cnt = 3
#list: cnt = v.count
otherwise: return
end case
sum = 0
repeat with i = 1 to cnt
sum = sum + v[i]
end repeat
return float(sum)/cnt
en... |
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... | #LiveCode | LiveCode | average(1,2,3,4,5) -- 3
average(empty) -- 0 |
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 ... | #Perl | Perl | sub median {
my @a = sort {$a <=> $b} @_;
return ($a[$#a/2] + $a[@a/2]) / 2;
} |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches ... | #Phix | Phix | with javascript_semantics
function median(sequence s)
atom res=0
integer l = length(s), k = floor((l+1)/2)
if l then
s = sort(s)
res = s[k]
if remainder(l,2)=0 then
res = (res+s[k+1])/2
end if
end if
return res
end function
|
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... | #PHP | PHP | <?php
// Created with PHP 7.0
function ArithmeticMean(array $values)
{
return array_sum($values) / count($values);
}
function GeometricMean(array $values)
{
return array_product($values) ** (1 / count($values));
}
function HarmonicMean(array $values)
{
$sum = 0;
foreach ($values as $value) {
... |
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) ... | #Kotlin | Kotlin | import java.util.Random
fun isBalanced(s: String): Boolean {
if (s.isEmpty()) return true
var countLeft = 0 // number of left brackets so far unmatched
for (c in s) {
if (c == '[') countLeft++
else if (countLeft > 0) countLeft--
else return false
}
return countLeft == 0
}
... |
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file | Append a record to the end of a text file | Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment.
This feature is most useful in the case of log files,... | #Wren | Wren | import "io" for File, FileFlags
var records = [
"jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash",
"jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash"
]
// Write records to a new file called "pas... |
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... | #E | E | [].asMap() # immutable, empty
["one" => 1, "two" => 2] # immutable, 2 mappings
[].asMap().diverge() # mutable, empty
["one" => 2].diverge(String, float64) # mutable, initial contents,
# typed (coerces to float) |
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
| #Quackery | Quackery | 0 temp put
[] 0
[ 1+ dup factors size
dup temp share > iff
[ temp replace
dup dip join ]
else drop
over size 20 = until ]
temp release
drop echo |
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
| #R | R | # Antiprimes
max_divisors <- 0
findFactors <- function(x){
myseq <- seq(x)
myseq[(x %% myseq) == 0]
}
antiprimes <- vector()
x <- 1
n <- 1
while(length(antiprimes) < 20){
y <- findFactors(x)
if (length(y) > max_divisors){
antiprimes <- c(antiprimes, x)
max_divisors <- length(y)
n <- n + 1
}
... |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #Racket | Racket | #lang racket
(require racket/generator
math/number-theory)
(define (get-divisors n)
(apply * (map (λ (factor) (add1 (second factor))) (factorize n))))
(define antiprimes
(in-generator
(for/fold ([prev 0]) ([i (in-naturals 1)])
(define divisors (get-divisors i))
(when (> divisors prev) (y... |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #jq | jq | # Illustration of map/1 using the builtin filter: exp
map(exp) # exponentiate each item in the input list
# A compound expression can be specified as the argument to map, e.g.
map( (. * .) + sqrt ) # x*x + sqrt(x)
# The compound expression can also be a composition of filters, e.g.
map( sqrt|floor ) # the floo... |
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.
| #Jsish | Jsish | /* Apply callback, in Jsish using array.map() */
;[1, 2, 3, 4, 5].map(function(v,i,a) { return v * v; });
/*
=!EXPECTSTART!=
[1, 2, 3, 4, 5].map(function(v,i,a) { return v * v; }) ==> [ 1, 4, 9, 16, 25 ]
=!EXPECTEND!=
*/ |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat... | #Vedit_macro_language | Vedit macro language | BOF // Copy all data to a new buffer
Reg_Copy(10, ALL)
Buf_Switch(Buf_Free)
Reg_Ins(10)
Sort(0, File_Size) // Sort the data
BOF
repeat(ALL) { // Count & delete duplicate lines
#1 = 1
while(Match("^{.*}\N\1$", REGEXP)==0) {
Del_Line(1)
... |
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 ... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | keys=DownValues[#,Sort->False][[All,1,1,1]]&;
hashes=#/@keys[#]&;
a[2]="string";a["sometext"]=23;
keys[a]
->{2,sometext}
hashes[a]
->{string,23} |
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 ... | #MATLAB_.2F_Octave | MATLAB / Octave | keys = fieldnames(hash);
for k=1:length(keys),
key = keys{k};
value = getfield(hash,key); % get value of key
hash = setfield(hash,key,-value); % set value of key
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... | #Logo | Logo | to average :l
if empty? :l [output 0]
output quotient apply "sum :l count :l
end
print average [1 2 3 4] ; 2.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 conveyin... | #Logtalk | Logtalk |
:- object(averages).
:- public(arithmetic/2).
% fails for empty vectors
arithmetic([X| Xs], Mean) :-
sum_and_count([X| Xs], 0, Sum, 0, Count),
Mean is Sum / Count.
% use accumulators to make the predicate tail-recursive
sum_and_count([], Sum, Sum, Count, Count).
sum_and_c... |
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 ... | #Phixmonti | Phixmonti | include ..\Utilitys.pmt
def median /# l -- n #/
sort len 2 / >ps
tps .5 + int 2 slice nip
ps> dup int != if
1 get nip
else
sum 2 /
endif
enddef
( 4.1 5.6 7.2 1.7 9.3 4.4 3.2 ) median ?
( 4.1 7.2 1.7 9.3 4.4 3.2 ) median ? |
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 ... | #PHP | PHP |
function median($arr)
{
sort($arr);
$count = count($arr); //count the number of values in array
$middleval = floor(($count-1)/2); // find the middle value, or the lowest middle value
if ($count % 2) { // odd number, middle is the median
$median = $arr[$middleval];
} else { // even number, ... |
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... | #PicoLisp | PicoLisp | (load "@lib/math.l")
(let (Lst (1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0) Len (length Lst))
(prinl "Arithmetic mean: "
(format
(/ (apply + Lst) Len)
*Scl ) )
(prinl "Geometric mean: "
(format
(pow (*/ (apply * Lst) (** 1.0 (dec Len))) (/ 1.0 Len))
*Scl ) )
(pr... |
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) ... | #L.2B.2B | L++ | (include "string")
(defn bool balanced (std::string s)
(def bal 0)
(foreach c s
(if (== c #\[) (++ bal)
(if (== c #\]) (-- bal)))
(if (< bal 0) (return false)))
(return (== bal 0)))
(main
(decl std::string (at tests) |{"", "[]", "[][]", "[[][]]", "][", "][][", "[]][[]"}|)
(pr std::boolalpha)... |
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file | Append a record to the end of a text file | Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment.
This feature is most useful in the case of log files,... | #Yabasic | Yabasic | a = open("passwd", "a") // Open the file for appending, i.e. what you write to the file will be appended after its initial contents.
// If the file does not exist, it will be created.
print #a "account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell"
print #a "jsmith... |
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file | Append a record to the end of a text file | Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment.
This feature is most useful in the case of log files,... | #zkl | zkl | var [const]
gnames=T("fullname","office","extension","homephone","email"),
pnames=T("account","password","uid","gid","gecos","directory","shell");
class Gecos{
var fullname, office, extension, homephone, email;
fcn init(str){ gnames.zipWith(setVar,vm.arglist) }
fcn toString { gnames.apply(setVar).conc... |
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... | #EchoLisp | EchoLisp |
(lib 'hash) ;; needs hash.lib
(define H (make-hash)) ;; new hash table
;; keys may be symbols, numbers, strings ..
;; values may be any lisp object
(hash-set H 'simon 'antoniette)
→ antoniette
(hash-set H 'antoinette 'albert)
→ albert
(hash-set H "Elvis" 42)
→ 42
(hash-ref H 'Elvis)
→ #f ;; not found. E... |
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
| #Raku | Raku | sub propdiv (\x) {
my @l = 1 if x > 1;
(2 .. x.sqrt.floor).map: -> \d {
unless x % d { @l.push: d; my \y = x div d; @l.push: y if y != d }
}
@l
}
my $last = 0;
my @anti-primes = lazy 1, |(|(2..59), 60, *+60 … *).grep: -> $c {
my \mx = +propdiv($c);
next if mx <= $last;
$last = mx... |
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
| #Red | Red | Red []
inc: func ['v] [set v 1 + get v] ;; shortcut function for n: n + 1
n: 0 found: 0 max_div: 0
print "the first 20 anti-primes are:"
while [ inc n] [
nDiv: 1 ;; count n / n extra
if n > 1 [ repeat div n / 2 [ if n % div = 0 [inc nDiv] ] ]
if nDiv > max_div [
max_div: nDiv
prin [n ""]
if... |
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.
| #Julia | Julia | numbers = [1, 3, 5, 7]
@show [n ^ 2 for n in numbers] # list comprehension
square(x) = x ^ 2; @show map(square, numbers) # functional form
@show map(x -> x ^ 2, numbers) # functional form with anonymous function
@show [n * n for n in numbers] # no need for a function,
@show ... |
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.
| #Kotlin | Kotlin | fun main(args: Array<String>) {
val array = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) // build
val function = { i: Int -> i * i } // function to apply
val list = array.map { function(it) } // process each item
println(list) // print results
} |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat... | #Vlang | Vlang | fn main() {
println(mode([2, 7, 1, 8, 2]))
println(mode([2, 7, 1, 8, 2, 8]))
}
fn mode(a []int) []int {
mut m := map[int]int{}
for v in a {
m[v]++
}
mut mode := []int{}
mut n := 0
for k, v in m {
match true {
v > n {
n = v
mod... |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat... | #Wren | Wren | class Arithmetic {
static mode(arr) {
var map = {}
for (e in arr) {
if (map[e] == null) map[e] = 0
map[e] = map[e] + 1
}
var max = map.values.reduce {|x, y| x > y ? x : y}
return map.keys.where {|x| map[x] == max}.toList
}
}
System.print(Arithmet... |
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 ... | #Maxima | Maxima | h[1]: 6$
h[9]: 2$
/* iterate over values */
for val in listarray(h) do (
print(val))$
/* iterate over the keys */
for key in rest(arrayinfo(h), 2) do (
val: arrayapply(h, key),
print(key, 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 ... | #MiniScript | MiniScript | d = { 3: "test", "foo": 3 }
for keyVal in d
print keyVal // produces results like: { "key": 3, "value": "test" }
end for
for key in d.indexes
print key
end for
for val in d.values
print val
end for |
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... | #LSL | LSL | integer MAX_ELEMENTS = 10;
integer MAX_VALUE = 100;
default {
state_entry() {
list lst = [];
integer x = 0;
for(x=0 ; x<MAX_ELEMENTS ; x++) {
lst += llFrand(MAX_VALUE);
}
llOwnerSay("lst=["+llList2CSV(lst)+"]");
llOwnerSay("Geometric Mean: "+(string)llList... |
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... | #Lua | Lua | function mean (numlist)
if type(numlist) ~= 'table' then return numlist end
num = 0
table.foreach(numlist,function(i,v) num=num+v end)
return num / #numlist
end
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 ... | #Picat | Picat | go =>
Lists = [
[1.121,10.3223,3.41,12.1,0.01],
1..10,
1..11,
[3],
[3,4],
[],
[4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2],
[4.1, 7.2, 1.7, 9.3, 4.4, 3.2],
[5.1, 2.6, 6.2, 8.8, 4.6, 4.1],
... |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches ... | #PicoLisp | PicoLisp | (de median (Lst)
(let N (length Lst)
(if (bit? 1 N)
(get (sort Lst) (/ (inc N) 2))
(setq Lst (nth (sort Lst) (/ N 2)))
(/ (+ (car Lst) (cadr Lst)) 2) ) ) )
(scl 2)
(prinl (round (median (1.0 2.0 3.0))))
(prinl (round (median (1.0 2.0 3.0 4.0))))
(prinl (round (median (5.1 2.6 6.2 8... |
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... | #PL.2FI | PL/I |
declare n fixed binary,
(Average, Geometric, Harmonic) float;
declare A(10) float static initial (1,2,3,4,5,6,7,8,9,10);
n = hbound(A,1);
/* compute the average */
Average = sum(A)/n;
/* Compute the geometric mean: */
Geometric = prod(A)**(1/n);
/* Compute the Harmonic mean: */
Harmonic = n / sum(1/A)... |
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... | #PostScript | PostScript |
/pythamean{
/x exch def
/sum 0 def
/prod 1 def
/invsum 0 def
/i 1 def
x{
/sum sum i add def
/prod prod i mul def
/invsum invsum i -1 exp add def
/i i 1 add def
}repeat
(Arithmetic Mean : ) print
sum x div =
(Geometric Mean : ) print
prod x -1 exp exp =
(Harmonic Mean : ) print
x invsum div =
}def
10 pythamean
|
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) ... | #Lasso | Lasso | define randomparens(num::integer,open::string='[',close::string=']') => {
local(out) = array
with i in 1 to #num do {
#out->insert(']', integer_random(1,#out->size || 1))
#out->insert('[', integer_random(1,#out->size || 1))
}
return #out->join
}
define validateparens(input::string,o... |
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... | #Elena | Elena | import system'collections;
public program()
{
// 1. Create
var map := Dictionary.new();
map["key"] := "foox";
map["key"] := "foo";
map["key2"]:= "foo2";
map["key3"]:= "foo3";
map["key4"]:= "foo4";
} |
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... | #Elixir | Elixir | defmodule RC do
def test_create do
IO.puts "< create Map.new >"
m = Map.new #=> creates an empty Map
m1 = Map.put(m,:foo,1)
m2 = Map.put(m1,:bar,2)
print_vals(m2)
print_vals(%{m2 | foo: 3})
end
defp print_vals(m) do
IO.inspect m
Enum.each(m, fn {k,v} -> IO.puts ... |
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
| #REXX | REXX | /*REXX program finds and displays N number of anti─primes or highly─composite numbers.*/
parse arg N . /*obtain optional argument from the CL.*/
if N=='' | N=="," then N= 20 /*Not specified? Then use the default.*/
maxD= 0 ... |
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.
| #Klingphix | Klingphix | include ..\Utilitys.tlhy
( 1 2 3 4 ) [dup *] map
pstack
" " input |
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.
| #Lambdatalk | Lambdatalk |
{A.map {lambda {:x} {* :x :x}} {A.new 1 2 3 4 5 6 7 8 9 10}}
-> [1,4,9,16,25,36,49,64,81,100]
|
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat... | #XEmacs_Lisp | XEmacs Lisp | (defun mode ( predicate &rest values)
"Finds the mode of all values passed in.
Uses `predicate' to compare items."
(let ((modes nil) ; Declare local variables
(mode-count 0)
(value-list nil)
current-value)
(loop for value in values do
(if (setq current-value (assoc*... |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat... | #Yabasic | Yabasic | sub floor(x)
return int(x + .05)
end sub
SUB ASort$(matriz$())
local last, gap, first, tempi$, tempj$, i, j
last = arraysize(matriz$(), 1)
gap = floor(last / 10) + 1
while(TRUE)
first = gap + 1
for i = first to last
tempi$ = matriz$(i)
j = i - gap
while(TRUE)
tempj$ =... |
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 ... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols
surname = 'Unknown' -- default value
surname['Fred'] = 'Bloggs'
surname['Davy'] = 'Jones'
try = 'Fred'
say surname[try] surname['Bert']
-- extract the keys
loop fn over surname
say fn.right(10) ':' surname[fn]
end fn |
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 ... | #NewLISP | NewLISP | ;; using an association list:
(setq alist '(("A" "a") ("B" "b") ("C" "c")))
;; list keys
(map first alist)
;; list values
(map last alist)
;; loop over the assocation list:
(dolist (elem alist)
(println (format "%s -> %s" (first elem) (last elem)))) |
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... | #Lucid | Lucid | avg(x)
where
sum = first(x) fby sum + next(x);
n = 1 fby n + 1;
avg = sum / n;
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... | #M4 | M4 | define(`extractdec', `ifelse(eval(`$1%100 < 10'),1,`0',`')eval($1%100)')dnl
define(`fmean', `eval(`($2/$1)/100').extractdec(eval(`$2/$1'))')dnl
define(`mean', `rmean(`$#', $@)')dnl
define(`rmean', `ifelse(`$3', `', `fmean($1,$2)',dnl
`rmean($1, eval($2+$3), shift(shift(shift($@))))')')dnl |
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 ... | #PL.2FI | PL/I | call sort(A);
n = dimension(A,1);
if iand(n,1) = 1 then /* an odd number of elements */
median = A(n/2);
else /* an even number of elements */
median = (a(n/2) + a(trunc(n/2)+1) )/2; |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches ... | #PowerShell | PowerShell |
function Measure-Data
{
[CmdletBinding()]
[OutputType([PSCustomObject])]
Param
(
[Parameter(Mandatory=$true,
Position=0)]
[double[]]
$Data
)
Begin
{
function Get-Mode ([double[]]$Data)
{
if ($Data.Count -gt ($Data | S... |
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... | #PowerShell | PowerShell | $A = 0
$LogG = 0
$InvH = 0
$ii = 1..10
foreach($i in $ii) {
# Arithmetic mean is computed directly
$A += $i / $ii.Count
# Geometric mean is computed using Logarithms
$LogG += [Math]::Log($i) / $ii.Count
# Harmonic mean is computed using its inverse
$InvH += 1 / ($i * $ii.Count)
}
$G = [Math]::Exp($LogG)
$H = ... |
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) ... | #Liberty_BASIC | Liberty BASIC |
print "Supplied examples"
for i =1 to 7
read test$
print "The string '"; test$; "' is "; validString$( test$)
next i
print
data "", "[]", "][","[][]","][][","[[][]]","[]][[]"
print "Random generated examples"
for example =1 to 10
test$ =generate$( int( 1 +10 *rnd(1)))
print "The string '"; test$; "'... |
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... | #Emacs_Lisp | Emacs Lisp | (setq my-table (make-hash-table))
(puthash 'key 'value my-table) |
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
| #Ring | Ring |
# Project : Anti-primes
see "working..." + nl
see "wait for done..." + nl + nl
see "the first 20 anti-primes are:" + nl + nl
maxDivisor = 0
num = 0
n = 0
result = list(20)
while num < 20
n = n + 1
div = factors(n)
if (div > maxDivisor)
maxDivisor = div
num = num + 1
resu... |
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
| #Ruby | Ruby | require 'prime'
def num_divisors(n)
n.prime_division.inject(1){|prod, (_p,n)| prod *= (n + 1) }
end
anti_primes = Enumerator.new do |y| # y is the yielder
max = 0
y << 1 # yield 1
2.step(nil,2) do |candidate| # nil is taken as Infinity
num = num_divisors(candidate)
... |
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.
| #Lang5 | Lang5 | : square(*) dup * ;
[1 2 3 4 5] square . "\n" .
[1 2 3 4 5] 'square apply . "\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.
| #langur | langur | writeln map f{^2}, 1..10 |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat... | #zkl | zkl | fcn mode(items){
d:=Dictionary(); foreach i in (items){ d.incV(i) }
m:=d.reduce(fcn(m,[(_,v)]){ v.max(m) },0);
d.filter('wrap([(_,v)]){ v==m }).apply("get",0);
} |
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 ... | #Nim | Nim |
import tables
var t: Table[int,string]
t[1] = "one"
t[2] = "two"
t[3] = "three"
t[4] = "four"
echo "t has " & $t.len & " elements"
echo "has t key 4? " & $t.hasKey(4)
echo "has t key 5? " & $t.hasKey(5)
#iterate keys
echo "key iteration:"
for k in t.keys:
echo "at[" & $k & "]=" & t[k]
#iterate pairs
ec... |
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 ... | #Oberon-2 | Oberon-2 |
MODULE AssociativeArray;
IMPORT
ADT:Dictionary,
Object:Boxed,
Out;
TYPE
Key = STRING;
Value = Boxed.LongInt;
VAR
assocArray: Dictionary.Dictionary(Key,Value);
iterK: Dictionary.IterKeys(Key,Value);
iterV: Dictionary.IterValues(Key,Value);
aux: Value;
k: Key;
BEGIN
assocArray := NEW(Dictionar... |
http://rosettacode.org/wiki/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... | #Maple | Maple |
mean := proc( a :: indexable )
local i;
Normalizer( add( i, i in a ) / numelems( a ) )
end proc:
|
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | Unprotect[Mean];
Mean[{}] := 0 |
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 ... | #Processing | Processing | void setup() {
float[] numbers = {3.1, 4.1, 5.9, 2.6, 5.3, 5.8};
println(median(numbers));
numbers = shorten(numbers);
println(median(numbers));
}
float median(float[] nums) {
nums = sort(nums);
float median = (nums[(nums.length - 1) / 2] + nums[nums.length / 2]) / 2.0;
return median;
} |
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.