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/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.
| #Frink | Frink |
f = {|x| x^2} // Anonymous function to square input
a = [1,2,3,5,7]
println[map[f, a]]
|
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #FunL | FunL | [1, 2, 3].foreach( println )
[1, 2, 3].foreach( a -> println(2a) ) |
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... | #Scala | Scala | import scala.collection.breakOut
import scala.collection.generic.CanBuildFrom
def mode
[T, CC[X] <: Seq[X]](coll: CC[T])
(implicit o: T => Ordered[T], cbf: CanBuildFrom[Nothing, T, CC[T]])
: CC[T] = {
val grouped = coll.groupBy(x => x).mapValues(_.size).toSeq
val max = grouped.map(_._2).max
grouped.filter(_... |
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 ... | #JavaScript | JavaScript | var myhash = {}; //a new, empty object
myhash["hello"] = 3;
myhash.world = 6; //obj.name is equivalent to obj["name"] for certain values of name
myhash["!"] = 9;
//iterate using for..in loop
for (var key in myhash) {
//ensure key is in object and not in prototype
if (myhash.hasOwnProperty(key)) {
console.log(... |
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... | #Java | Java | public static double avg(double... arr) {
double sum = 0.0;
for (double x : arr) {
sum += x;
}
return sum / arr.length;
} |
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... | #JavaScript | JavaScript | function mean(array)
{
var sum = 0, i;
for (i = 0; i < array.length; i++)
{
sum += array[i];
}
return array.length ? sum / array.length : 0;
}
alert( mean( [1,2,3,4,5] ) ); // 3
alert( mean( [] ) ); // 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.... | #Rust | Rust | use primal::Primes;
const MAX: u64 = 120;
/// Returns an Option with a tuple => Ok((smaller prime factor, num divided by that prime factor))
/// If num is a prime number itself, returns None
fn extract_prime_factor(num: u64) -> Option<(u64, u64)> {
let mut i = 0;
if primal::is_prime(num) {
None
... |
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.... | #Scala | Scala | object AttractiveNumbers extends App {
private val max = 120
private var count = 0
private def nFactors(n: Int): Int = {
@scala.annotation.tailrec
def factors(x: Int, f: Int, acc: Int): Int =
if (f * f > x) acc + 1
else
x % f match {
case 0 => factors(x / f, f, acc + 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 ... | #Nim | Nim | import algorithm, strutils
proc median(xs: seq[float]): float =
var ys = xs
sort(ys, system.cmp[float])
0.5 * (ys[ys.high div 2] + ys[ys.len div 2])
var a = @[4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2]
echo formatFloat(median(a), precision = 0)
a = @[4.1, 7.2, 1.7, 9.3, 4.4, 3.2]
echo formatFloat(median(a), precisio... |
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 ... | #Oberon-2 | Oberon-2 |
MODULE Median;
IMPORT Out;
CONST
MAXSIZE = 100;
PROCEDURE Partition(VAR a: ARRAY OF REAL; left, right: INTEGER): INTEGER;
VAR
pValue,aux: REAL;
store,i,pivot: INTEGER;
BEGIN
pivot := right;
pValue := a[pivot];
aux := a[right];a[right] := a[pivot];a[pivot] := aux; (* a[pivot] <-> a[right] *)
store := left;
F... |
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... | #Oforth | Oforth | import: mapping
: A ( x )
x sum
x size dup ifZero: [ 2drop null ] else: [ >float / ]
;
: G( x ) #* x reduce x size inv powf ;
: H( x ) x size x map( #inv ) sum / ;
: averages
| g |
"Geometric mean :" . 10 seq G dup .cr ->g
"Arithmetic mean :" . 10 seq A dup . g >= ifTrue: [ " ==> A >= G" .cr ... |
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) ... | #Icon_and_Unicon | Icon and Unicon | procedure main(arglist)
every s := genbs(!arglist) do
write(image(s), if isbalanced(s) then " is balanced." else " is unbalanced")
end
procedure isbalanced(s) # test if a string is balanced re: []
return (s || " ") ? (bal(,'[',']') = *s+1)
end
procedure genbs(i) # generate strings of i pairs of []
s := ""
eve... |
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,... | #RapidQ | RapidQ |
'Short solution: Append record and read last record
$Include "Rapidq.inc"
dim file as qfilestream
dim filename as string
dim LogRec as string
'First create our logfile
filename = "C:\Logfile2.txt"
file.open(filename, fmCreate)
file.writeline "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmi... |
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,... | #REXX | REXX | /*REXX program writes (appends) two records, closes the file, appends another record.*/
tFID= 'PASSWD.TXT' /*define the name of the output file.*/
call lineout tFID /*close the output file, just in case,*/
... |
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... | #Common_Lisp | Common Lisp | ;; default :test is #'eql, which is suitable for numbers only,
;; or for implementation identity for other types!
;; Use #'equalp if you want case-insensitive keying on strings.
(setf my-hash (make-hash-table :test #'equal))
(setf (gethash "H2O" my-hash) "Water")
(setf (gethash "HCl" my-hash) "Hydrochloric Acid")
(se... |
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
| #PARI.2FGP | PARI/GP |
countfactors(n)={
my(count(m)= prod(i=1,#factor(m)~,factor(m)[i,2]+1));
v=vector(n);
v[1]=1;
for(x=2,n,
v[x]=v[x-1]+1;
while(count(v[x-1])>=count(v[x]),v[x]++));
return(v)}
countfactors(20)
|
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
| #Perl | Perl | use ntheory qw(divisors);
my @anti_primes;
for (my ($k, $m) = (1, 0) ; @anti_primes < 20 ; ++$k) {
my $sigma0 = divisors($k);
if ($sigma0 > $m) {
$m = $sigma0;
push @anti_primes, $k;
}
}
printf("%s\n", join(' ', @anti_primes)); |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #VBScript | VBScript | sub Assert( boolExpr, strOnFail )
if not boolExpr then
Err.Raise vbObjectError + 99999, , strOnFail
end if
end sub
|
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Visual_Basic | Visual Basic | Debug.Assert i = 42 |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Visual_Basic_.NET | Visual Basic .NET | var assertEnabled = true
var assert = Fn.new { |cond|
if (assertEnabled && !cond) Fiber.abort("Assertion failure")
}
var x = 42
assert.call(x == 42) // fine
assertEnabled = false
assert.call(x > 42) // no error
assertEnabled = true
assert.call(x > 42) // error |
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.
| #Futhark | Futhark |
map f l
|
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.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | a := [1 .. 4];
b := ShallowCopy(a);
# Apply and replace values
Apply(a, n -> n*n);
a;
# [ 1, 4, 9, 16 ]
# Apply and don't change values
List(b, n -> n*n);
# [ 1, 4, 9, 16 ]
# Apply and don't return anything (only side effects)
Perform(b, Display);
1
2
3
4
b;
# [ 1 .. 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... | #Scheme | Scheme | (define (mode collection)
(define (helper collection counts)
(if (null? collection)
counts
(helper (remove (car collection) collection)
(cons (cons (car collection)
(appearances (car collection) collection)) counts))))
(map ca... |
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 ... | #Jq | Jq | - functionally, e.g. using map on an array
- by enumeration, i.e. by generating a stream
- by performing a reduction
|
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 ... | #Julia | Julia | dict = Dict("hello" => 13, "world" => 31, "!" => 71)
# applying a function to key-value pairs:
foreach(println, dict)
# iterating over key-value pairs:
for (key, value) in dict
println("dict[$key] = $value")
end
# iterating over keys:
for key in keys(dict)
@show key
end
# iterating over values:
for valu... |
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... | #jq | jq | add/length |
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... | #Julia | Julia | julia> using Statistics; mean([1,2,3])
2.0
julia> mean(1:10)
5.5
julia> mean([])
ERROR: mean of empty collection undefined: [] |
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.... | #Sidef | Sidef | func is_attractive(n) {
n.bigomega.is_prime
}
1..120 -> grep(is_attractive).say |
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.... | #Swift | Swift | import Foundation
extension BinaryInteger {
@inlinable
public var isAttractive: Bool {
return primeDecomposition().count.isPrime
}
@inlinable
public var isPrime: Bool {
if self == 0 || self == 1 {
return false
} else if self == 2 {
return true
}
let max = Self(ceil((Doubl... |
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 ... | #Objeck | Objeck |
use Structure;
bundle Default {
class Median {
function : Main(args : String[]) ~ Nil {
numbers := FloatVector->New([4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2]);
DoMedian(numbers)->PrintLine();
numbers := FloatVector->New([4.1, 7.2, 1.7, 9.3, 4.4, 3.2]);
DoMedian(numbers)->PrintLine();
}... |
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... | #ooRexx | ooRexx | a = .array~of(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)
say "Arithmetic =" arithmeticMean(a)", Geometric =" geometricMean(a)", Harmonic =" harmonicMean(a)
::routine arithmeticMean
use arg numbers
-- somewhat arbitrary return for ooRexx
if numbers~isEmpty then return "NaN"
mean = 0
loop number ove... |
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) ... | #J | J | bracketDepth =: '[]' -&(+/\)/@:(=/) ]
checkBalanced =: _1 -.@e. bracketDepth
genBracketPairs =: (?~@# { ])@#"0 1&'[]' NB. bracket pairs in arbitrary order |
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,... | #Ruby | Ruby | Gecos = Struct.new :fullname, :office, :extension, :homephone, :email
class Gecos
def to_s
"%s,%s,%s,%s,%s" % to_a
end
end
# Another way define 'to_s' method
Passwd = Struct.new(:account, :password, :uid, :gid, :gecos, :directory, :shell) do
def to_s
to_a.join(':')
end
end
jsmith = Passwd.new('jsmi... |
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... | #Component_Pascal | Component Pascal |
DEFINITION Collections;
IMPORT Boxes;
CONST
notFound = -1;
TYPE
Hash = POINTER TO RECORD
cap-, size-: INTEGER;
(h: Hash) ContainsKey (k: Boxes.Object): BOOLEAN, NEW;
(h: Hash) Get (k: Boxes.Object): Boxes.Object, NEW;
(h: Hash) IsEmpty (): BOOLEAN, NEW;
(h: Hash) Put (k, v: Boxes.Object):... |
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
| #Phix | Phix | with javascript_semantics
integer n=1, maxd = -1
sequence res = {}
while length(res)<20 do
integer lf = length(factors(n,1))
if lf>maxd then
res &= n
maxd = lf
end if
n += iff(n>1?2:1)
end while
printf(1,"The first 20 anti-primes are: %V\n",{res})
|
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
| #Phixmonti | Phixmonti | 0 var count
0 var n
0 var max_divisors
"The first 20 anti-primes are:" print nl
def count_divisors
dup 2 < if
drop
1
else
2
swap 1 over 2 / 2 tolist
for
over swap mod not if swap 1 + swap endif
endfor
drop
endif
enddef
true
while
... |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Wren | Wren | var assertEnabled = true
var assert = Fn.new { |cond|
if (assertEnabled && !cond) Fiber.abort("Assertion failure")
}
var x = 42
assert.call(x == 42) // fine
assertEnabled = false
assert.call(x > 42) // no error
assertEnabled = true
assert.call(x > 42) // error |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Visual_Basic_.NET_2 | Visual Basic .NET | fn main(){
x := 43
assert x == 43 // Fine
assert x > 42 // Fine
assert x == 42 // Fails
} |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Vlang | Vlang | fn main(){
x := 43
assert x == 43 // Fine
assert x > 42 // Fine
assert x == 42 // Fails
} |
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.
| #GAP | GAP | a := [1 .. 4];
b := ShallowCopy(a);
# Apply and replace values
Apply(a, n -> n*n);
a;
# [ 1, 4, 9, 16 ]
# Apply and don't change values
List(b, n -> n*n);
# [ 1, 4, 9, 16 ]
# Apply and don't return anything (only side effects)
Perform(b, Display);
1
2
3
4
b;
# [ 1 .. 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.
| #Go | Go | package main
import "fmt"
func main() {
for _, i := range []int{1, 2, 3, 4, 5} {
fmt.Println(i * i)
}
} |
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: createModeFunction (in type: elemType) is func
begin
const func array elemType: mode (in array elemType: data) is func
result
var array elemType: maxElems is 0 times elemType.value;
local
var hash [elemType] integer: counts is (hash [elemType] ... |
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... | #Sidef | Sidef | func mode(array) {
var c = Hash.new;
array.each{|i| c{i} := 0 ++};
var max = c.values.max;
c.keys.grep{|i| c{i} == max};
} |
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 ... | #K | K | d: .((`"hello";1); (`"world";2);(`"!";3)) |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked ... | #Kotlin | Kotlin | fun main(a: Array<String>) {
val map = mapOf("hello" to 1, "world" to 2, "!" to 3)
with(map) {
entries.forEach { println("key = ${it.key}, value = ${it.value}") }
keys.forEach { println("key = $it") }
values.forEach { println("value = $it") }
}
} |
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... | #K | K | mean: {(+/x)%#x}
mean 1 2 3 5 7
3.6
mean@!0 / empty array
0.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... | #Kotlin | Kotlin | fun main(args: Array<String>) {
val nums = doubleArrayOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)
println("average = %f".format(nums.average()))
} |
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.... | #Tcl | Tcl | proc isPrime {n} {
if {$n < 2} {
return 0
}
if {$n > 3} {
if {0 == ($n % 2)} {
return 0
}
for {set d 3} {($d * $d) <= $n} {incr d 2} {
if {0 == ($n % $d)} {
return 0
}
}
}
return 1 ;# no di... |
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 ... | #OCaml | OCaml | (* note: this modifies the input array *)
let median array =
let len = Array.length array in
Array.sort compare array;
(array.((len-1)/2) +. array.(len/2)) /. 2.0;;
let a = [|4.1; 5.6; 7.2; 1.7; 9.3; 4.4; 3.2|];;
median a;;
let a = [|4.1; 7.2; 1.7; 9.3; 4.4; 3.2|];;
median 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... | #Oz | Oz | declare
%% helpers
fun {Sum Xs} {FoldL Xs Number.'+' 0.0} end
fun {Product Xs} {FoldL Xs Number.'*' 1.0} end
fun {Len Xs} {Int.toFloat {Length Xs}} end
fun {AMean Xs}
{Sum Xs}
/
{Len Xs}
end
fun {GMean Xs}
{Pow
{Product Xs}
1.0/{Len Xs}}
end
fun {HMean Xs}
{L... |
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) ... | #Java_2 | Java | public class BalancedBrackets {
public static boolean hasBalancedBrackets(String str) {
int brackets = 0;
for (char ch : str.toCharArray()) {
if (ch == '[') {
brackets++;
} else if (ch == ']') {
brackets--;
} else {
... |
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,... | #Rust | Rust |
use std::fs::File;
use std::fs::OpenOptions;
use std::io::BufRead;
use std::io::BufReader;
use std::io::BufWriter;
use std::io::Result;
use std::io::Write;
use std::path::Path;
/// Password record with all fields
#[derive(Eq, PartialEq, Debug)]
pub struct PasswordRecord {
pub account: String,
pub password: ... |
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,... | #Scala | Scala | import java.io.{File, FileWriter, IOException}
import scala.io.Source
object RecordAppender extends App {
val rawDataIt = Source.fromString(rawData).getLines()
def writeStringToFile(file: File, data: String, appending: Boolean = false) =
using(new FileWriter(file, appending))(_.write(data))
def using[A ... |
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... | #Crystal | Crystal | hash1 = {"foo" => "bar"}
# hash literals that don't perfectly match the intended hash type must be given an explicit type specification
# the following would fail without `of String => String|Int32`
hash2 : Hash(String, String|Int32) = {"foo" => "bar"} of String => String|Int32 |
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
| #Picat | Picat |
count_divisors(1) = 1.
count_divisors(N) = Count, N >= 2 =>
Count = 2,
foreach (I in 2..N/2)
if (N mod I == 0) then
Count := Count + 1
end
end.
main =>
println("The first 20 anti-primes are:"),
MaxDiv = 0,
Count = 0,
N = 1,
while (Count < 20)
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
| #PicoLisp | PicoLisp | (de factors (N)
(let C 1
(when (>= N 2)
(inc 'C)
(for (I 2 (>= (/ N 2) I) (inc I))
(and (=0 (% N I)) (inc 'C)) ) )
C ) )
(de anti (X)
(let (M 0 I 0 N 0)
(make
(while (> X I)
(inc 'N)
(let R (factors N)
(when (> R M)
... |
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
| #PILOT | PILOT | C :n=1
:max=0
:seen=0
*number
U :*count
T (c>max):#n
C (c>max):seen=seen+1
C (c>max):max=c
:n=n+1
J (seen<20):*number
E :
*count
C (n=1):c=1
E (n=1):
C :c=2
:i=2
*cnloop
E (i>n/2):
C (i*(n/i)=n):c=c+1
:i=i+1
J :*cnloop |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #XPL0 | XPL0 | proc Fatal(Str); \Display error message and terminate program
char Str;
[\return; uncomment this if "assertions" are to be disabled
SetVid(3); \set normal text display if program uses graphics
Text(0, Str); \display error message
ChOut(0, 7); \sound the bell
exit ... |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Yabasic | Yabasic | sub assert(a)
if not a then
error "Assertion failed"
end if
end sub
assert(myVar = 42) |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Zig | Zig | const assert = @import("std").debug.assert;
pub fn main() void {
assert(1 == 0); // On failure, an `unreachable` is reached
} |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Z80_Assembly | Z80 Assembly | ld a,(&C005) ;load A from memory (this is an arbitrary memory location designated as the home of our variable)
cp 42
jp nz,ErrorHandler |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #zkl | zkl | n:=42; (n==42) or throw(Exception.AssertionError);
n=41; (n==42) or throw(Exception.AssertionError("I wanted 42!")); |
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.
| #Groovy | Groovy | [1,2,3,4].each { println it } |
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.
| #Haskell | Haskell | let square x = x*x
let values = [1..10]
map square values |
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... | #Slate | Slate | s@(Sequence traits) mode
[| sortedCounts |
sortedCounts: (s as: Bag) sortedCounts.
(sortedCounts mapSelect: [| :count :elem | sortedCounts last count = count]) valueSet
]. |
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... | #Smalltalk | Smalltalk | OrderedCollection extend [
mode [ |s|
s := self asBag sortedByCount.
^ (s select: [ :k | ((s at: 1) key) = (k key) ]) collect: [:k| k value]
]
].
#( 1 3 6 6 6 6 7 7 12 12 17 ) asOrderedCollection
mode displayNl.
#( 1 1 2 4 4) asOrderedCollection
mode displayNl. |
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 ... | #Lang5 | Lang5 | : first 0 extract nip ; : second 1 extract nip ; : nip swap drop ;
: say(*) dup first " => " 2 compress "" join . second . ;
[['foo 5] ['bar 10] ['baz 20]] 'say apply drop |
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 ... | #Lasso | Lasso |
//iterate over associative array
//Lasso maps
local('aMap' = map('weight' = 112,
'height' = 45,
'name' = 'jason'))
' Map output: \n '
#aMap->forEachPair => {^
//display pair, then show accessing key and value individually
#1+'\n '
#1->first+': '+#1->second+'\n '
^}
//display keys and values 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... | #KQL | KQL |
let dataset = datatable(values:real)[
1, 1.5, 3, 5, 6.5];
dataset|summarize avg(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... | #LabVIEW | LabVIEW |
{def mean
{lambda {:s}
{if {S.empty? :s}
then 0
else {/ {+ :s} {S.length :s}}}}}
{mean {S.serie 0 1000}}
-> 500
|
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.... | #Vala | Vala | bool is_prime(int n) {
var d = 5;
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
if (n % 3 == 0) return n == 3;
while (d * d <= n) {
if (n % d == 0) return false;
d += 2;
if (n % d == 0) return false;
d += 4;
}
return true;
}
int count_prime_factors(int n) {
var count = 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 ... | #Octave | Octave | function y = median2(v)
if (numel(v) < 1)
y = NA;
else
sv = sort(v);
l = numel(v);
if ( mod(l, 2) == 0 )
y = (sv(floor(l/2)+1) + sv(floor(l/2)))/2;
else
y = sv(floor(l/2)+1);
endif
endif
endfunction
a = [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2];
b = [4.1, 7.2, 1.7, 9.3, 4.4, 3.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... | #PARI.2FGP | PARI/GP | arithmetic(v)={
sum(i=1,#v,v[i])/#v
};
geometric(v)={
prod(i=1,#v,v[i])^(1/#v)
};
harmonic(v)={
#v/sum(i=1,#v,1/v[i])
};
v=vector(10,i,i);
[arithmetic(v),geometric(v),harmonic(v)] |
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) ... | #JavaScript | JavaScript | function shuffle(str) {
var a = str.split(''), b, c = a.length, d
while (c) b = Math.random() * c-- | 0, d = a[c], a[c] = a[b], a[b] = d
return a.join('')
}
function isBalanced(str) {
var a = str, b
do { b = a, a = a.replace(/\[\]/g, '') } while (a != b)
return !a
}
var M = 20
while (M-- > 0) {
var N ... |
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,... | #Sidef | Sidef | define (
RECORD_FIELDS = %w(account password UID GID GECOS directory shell),
GECOS_FIELDS = %w(fullname office extension homephone email),
RECORD_SEP = ':',
GECOS_SEP = ',',
PASSWD_FILE = 'passwd.txt',
)
# here's our three records
var records_to_write = [
Hash(
account => 'j... |
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... | #D | D | void main() {
auto hash = ["foo":42, "bar":100];
assert("foo" in hash);
} |
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
| #PL.2FI | PL/I | antiprimes: procedure options(main);
/* count the factors of a number */
countFactors: procedure(n) returns(fixed);
declare (n, i, count) fixed;
if n<2 then return(1);
count = 1;
do i=1 to n/2;
if mod(n,i) = 0 then count = count + 1;
end;
return(coun... |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #zonnon | zonnon |
module Assertions;
var
a: integer;
begin
a := 40;
assert(a = 42,100)
end Assertions.
|
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.
| #Icon_and_Unicon | Icon and Unicon | procedure main()
local lst
lst := [10, 20, 30, 40]
every callback(write,!lst)
end
procedure callback(p,arg)
return p(" -> ", arg)
end |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #IDL | IDL | b = a^3 |
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... | #SQL | SQL | -- setup
CREATE TABLE averages (val INTEGER);
INSERT INTO averages VALUES (1);
INSERT INTO averages VALUES (2);
INSERT INTO averages VALUES (3);
INSERT INTO averages VALUES (1);
INSERT INTO averages VALUES (2);
INSERT INTO averages VALUES (4);
INSERT INTO averages VALUES (2);
INSERT INTO averages VALUES (5);
INSERT INT... |
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 ... | #LFE | LFE |
(let ((data '(#(key1 "foo") #(key2 "bar")))
(hash (: dict from_list data)))
(: dict fold
(lambda (key val accum)
(: io format '"~s: ~s~n" (list key val)))
0
hash))
|
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 ... | #Liberty_BASIC | Liberty BASIC |
data "red", "255 50 50", "green", "50 255 50", "blue", "50 50 255"
data "my fave", "220 120 120", "black", "0 0 0"
myAssocList$ =""
for i =1 to 5
read k$
read dat$
call sl.Set myAssocList$, k$, dat$
next i
keys$ = "" ' List to hold the keys in myList$.
keys = 0
keys = sl.Key... |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin... | #Lambdatalk | Lambdatalk |
{def mean
{lambda {:s}
{if {S.empty? :s}
then 0
else {/ {+ :s} {S.length :s}}}}}
{mean {S.serie 0 1000}}
-> 500
|
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... | #langur | langur | val .mean = f(.x) fold(f{+}, .x) / len(.x)
writeln " custom: ", .mean([7, 3, 12])
writeln "built-in: ", mean([7, 3, 12]) |
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.... | #VBA | VBA | Option Explicit
Public Sub AttractiveNumbers()
Dim max As Integer, i As Integer, n As Integer
max = 120
For i = 1 To max
n = CountPrimeFactors(i)
If IsPrime(n) Then Debug.Print i
Next i
End Sub
Public Function IsPrime(ByVal n As Integer) As Boolean
Dim d As Integer
IsPrime = True
d = 5
If n < 2 Th... |
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.... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Const MAX = 120
Function IsPrime(n As Integer) As Boolean
If n < 2 Then Return False
If n Mod 2 = 0 Then Return n = 2
If n Mod 3 = 0 Then Return n = 3
Dim d = 5
While d * d <= n
If n Mod d = 0 Then Return False
d += 2
I... |
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 ... | #ooRexx | ooRexx |
call testMedian .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
call testMedian .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11)
call testMedian .array~of(10, 20, 30, 40, 50, -100, 4.7, -11e2)
call testMedian .array~new
::routine testMedian
use arg numbers
say "numbers =" numbers~toString("l", ", ")
say "me... |
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... | #Pascal | Pascal | 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) ... | #Julia | Julia | using Printf
function balancedbrackets(str::AbstractString)
i = 0
for c in str
if c == '[' i += 1 elseif c == ']' i -=1 end
if i < 0 return false end
end
return i == 0
end
brackets(n::Integer) = join(shuffle(collect(Char, "[]" ^ n)))
for (test, pass) in map(x -> (x, balancedbracket... |
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,... | #Tcl | Tcl | # Model the data as nested lists, as that is a natural fit for Tcl
set basicRecords {
{
jsmith
x
1001
1000
{
{Joe Smith}
{Room 1007}
(234)555-8917
(234)555-0077
jsmith@rosettacode.org
}
/home/jsmith
/bin/bash
}
{
jdoe
x
1002
1000
{
{Jane Doe}
{Room 1004}
... |
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... | #Dao | Dao | m = { => } # empty ordered map, future inserted keys will be ordered
h = { -> } # empty hash map, future inserted keys will not be ordered
m = { 'foo' => 42, 'bar' => 100 } # with ordered keys
h = { 'foo' -> 42, 'bar' -> 100 } # with unordered keys |
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... | #Dart | Dart |
main() {
var rosettaCode = { // Type is inferred to be Map<String, String>
'task': 'Associative Array Creation'
};
rosettaCode['language'] = 'Dart';
// The update function can be used to update a key using a callback
rosettaCode.update( 'is fun', // Key to update
(value) => "i don't know", // New value ... |
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
| #PL.2FM | PL/M | 100H:
/* CP/M CALLS */
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;
/* PRINT A NUMBER */
PRINT$NUMBER: PROCEDURE (N);
DECLARE S (7) BYTE INITIAL ('..... $');
DECLARE (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.
| #Io | Io | list(1,2,3,4,5) map(squared) |
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.
| #J | J | "_1 |
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... | #Swift | Swift |
// Extend the Collection protocol. Any type that conforms to extension where its Element type conforms to Hashable will automatically gain this method.
extension Collection where Element: Hashable {
/// Return a Mode of the function, or nil if none exist.
func mode() -> Element? {
var frequencies = ... |
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... | #Tcl | Tcl | # Can find the modal value of any vector of values
proc mode {n args} {
foreach n [list $n {*}$args] {
dict incr counter $n
}
set counts [lsort -stride 2 -index 1 -decreasing $counter]
set best {}
foreach {n count} $counts {
if {[lindex $counts 1] == $count} {
lappend bes... |
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 ... | #Lingo | Lingo | hash = [#key1:"value1", #key2:"value2", #key3:"value3"]
-- iterate over key-value pairs
repeat with i = 1 to hash.count
put hash.getPropAt(i) & "=" & hash[i]
end repeat
-- iterating over values only can be written shorter
repeat with val in hash
put val
end repeat |
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 ... | #LiveCode | LiveCode | put 3 into fruit["apples"]
put 5 into fruit["pears"]
put 6 into fruit["oranges"]
put "none" into fruit["bananas"]
put "Keys:" & cr & the keys of fruit & cr into tTmp
put "Values 1:" & tab after tTmp
repeat for each line tKey in the keys of fruit
put fruit[tkey] & comma after tTmp
end repeat
-- need to copy arra... |
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.