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 appropriate or possible to support an unspecified value type, use integers.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Scala | Scala | 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(_._2 == max).map(_._1)(breakOut)
} |
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 list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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("Key is: " + key + '. Value is: ' + myhash[key]);
}
}
//iterate using ES5.1 Object.keys() and Array.prototype.Map()
var keys = Object.keys(); //get Array of object keys (doesn't get prototype keys)
keys.map(function (key) {
console.log("Key is: " + key + '. Value is: ' + myhash[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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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.
Reference
The OEIS entry: A063989: Numbers with a prime number of prime divisors.
| #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
} else {
loop {
let prime = Primes::all().nth(i).unwrap() as u64;
if num % prime == 0 {
return Some((prime, num / prime));
} else {
i += 1;
}
}
}
}
/// Returns a vector containing all the prime factors of num
fn factorize(num: u64) -> Vec<u64> {
let mut factorized = Vec::new();
let mut rest = num;
while let Some((prime, factorizable_rest)) = extract_prime_factor(rest) {
factorized.push(prime);
rest = factorizable_rest;
}
factorized.push(rest);
factorized
}
fn main() {
let mut output: Vec<u64> = Vec::new();
for num in 4 ..= MAX {
if primal::is_prime(factorize(num).len() as u64) {
output.push(num);
}
}
println!("The attractive numbers up to and including 120 are\n{:?}", output);
} |
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.
Reference
The OEIS entry: A063989: Numbers with a prime number of prime divisors.
| #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)
case _ => factors(x, f + 1, acc)
}
factors(n, 2, 0)
}
private def ls: Seq[String] =
for (i <- 4 to max;
n = nFactors(i)
if n >= 2 && nFactors(n) == 1 // isPrime(n)
) yield f"$i%4d($n)"
println(f"The attractive numbers up to and including $max%d are: [number(factors)]\n")
ls.zipWithIndex
.groupBy { case (_, index) => index / 20 }
.foreach { case (_, row) => println(row.map(_._1).mkString) }
} |
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 to this. One is to sort the elements, and then pick the element(s) in the middle.
Sorting would take at least O(n logn). Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s). This would also take O(n logn). The best solution is to use the selection algorithm to find the median in O(n) time.
See also
Quickselect_algorithm
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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), precision = 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 to this. One is to sort the elements, and then pick the element(s) in the middle.
Sorting would take at least O(n logn). Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s). This would also take O(n logn). The best solution is to use the selection algorithm to find the median in O(n) time.
See also
Quickselect_algorithm
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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;
FOR i := left TO right -1 DO
IF a[i] <= pValue THEN
aux := a[store];a[store] := a[i];a[i]:=aux;
INC(store)
END
END;
aux := a[right];a[right] := a[store]; a[store] := aux;
RETURN store
END Partition;
(* QuickSelect algorithm *)
PROCEDURE Select(a: ARRAY OF REAL; left,right,k: INTEGER;VAR r: REAL);
VAR
pIndex, pDist : INTEGER;
BEGIN
IF left = right THEN r := a[left]; RETURN END;
pIndex := Partition(a,left,right);
pDist := pIndex - left + 1;
IF pDist = k THEN
r := a[pIndex];RETURN
ELSIF k < pDist THEN
Select(a,left, pIndex - 1, k, r)
ELSE
Select(a,pIndex + 1, right, k - pDist, r)
END
END Select;
PROCEDURE Median(a: ARRAY OF REAL;left,right: INTEGER): REAL;
VAR
idx,len : INTEGER;
r1,r2 : REAL;
BEGIN
len := right - left + 1;
idx := len DIV 2 + 1;
r1 := 0.0;r2 := 0.0;
Select(a,left,right,idx,r1);
IF ODD(len) THEN RETURN r1 END;
Select(a,left,right,idx - 1,r2);
RETURN (r1 + r2) / 2;
END Median;
VAR
ary: ARRAY MAXSIZE OF REAL;
r: REAL;
BEGIN
r := 0.0;
Out.Fixed(Median(ary,0,0),4,2);Out.Ln; (* empty *)
ary[0] := 5;
ary[1] := 3;
ary[2] := 4;
Out.Fixed(Median(ary,0,2),4,2);Out.Ln;
ary[0] := 5;
ary[1] := 4;
ary[2] := 2;
ary[3] := 3;
Out.Fixed(Median(ary,0,3),4,2);Out.Ln;
ary[0] := 3;
ary[1] := 4;
ary[2] := 1;
ary[3] := -8.4;
ary[4] := 7.2;
ary[5] := 4;
ary[6] := 1;
ary[7] := 1.2;
Out.Fixed(Median(ary,0,7),4,2);Out.Ln;
END Median.
|
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 positive integers.
The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
A
(
x
1
,
…
,
x
n
)
=
x
1
+
⋯
+
x
n
n
{\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}}
The geometric mean is the
n
{\displaystyle n}
th root of the product of the list:
G
(
x
1
,
…
,
x
n
)
=
x
1
⋯
x
n
n
{\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}}
The harmonic mean is
n
{\displaystyle n}
divided by the sum of the reciprocal of each item in the list:
H
(
x
1
,
…
,
x
n
)
=
n
1
x
1
+
⋯
+
1
x
n
{\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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 ]
"Harmonic mean :" . 10 seq H dup . g <= ifTrue: [ " ==> G >= H" .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) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #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 := ""
every 1 to i do s ||:= "[]" # generate i pairs
every !s := ?s # shuffle
return s
end |
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, where many jobs may be appending to the log file at the same time, or where care must be taken to avoid concurrently overwriting the same record from another job.
Task
Given a two record sample for a mythical "passwd" file:
Write these records out in the typical system format.
Ideally these records will have named fields of various types.
Close the file, then reopen the file for append.
Append a new record to the file and close the file again.
Take appropriate care to avoid concurrently overwrites from another job.
Open the file and demonstrate the new record has indeed written to the end.
Source record field types and contents.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
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
Record to be appended.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
xyz
x
1003
1000
X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]
/home/xyz
/bin/bash
Resulting file format: should mimic Linux's /etc/passwd file format with particular attention to the "," separator used in the GECOS field. But if the specific language has a particular or unique format of storing records in text file, then this format should be named and demonstrated with an additional example.
Expected output:
Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash
Finally: Provide a summary of the language's "append record" capabilities in a table. eg.
Append Capabilities.
Data Representation
IO
Library
Append
Possible
Automatic
Append
Multi-tasking
Safe
In core
On disk
C struct
CSV text file
glibc/stdio
☑
☑
☑ (Not all, eg NFS)
Alternatively: If the language's appends can not guarantee its writes will always append, then note this restriction in the table. If possible, provide an actual code example (possibly using file/record locking) to guarantee correct concurrent appends.
| #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,[email protected]:/home/jsmith:/bin/bash"
file.writeline "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jsmith:/bin/bash"
file.close
'Append record
file.open(filename, fmOpenWrite)
file.position = File.size
file.writeline "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash"
file.close
'Read last record
file.open (filename, fmOpenRead)
while not file.EOF
LogRec = File.Readline
wend
file.close
showmessage "Appended record: " + LogRec
|
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, where many jobs may be appending to the log file at the same time, or where care must be taken to avoid concurrently overwriting the same record from another job.
Task
Given a two record sample for a mythical "passwd" file:
Write these records out in the typical system format.
Ideally these records will have named fields of various types.
Close the file, then reopen the file for append.
Append a new record to the file and close the file again.
Take appropriate care to avoid concurrently overwrites from another job.
Open the file and demonstrate the new record has indeed written to the end.
Source record field types and contents.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
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
Record to be appended.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
xyz
x
1003
1000
X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]
/home/xyz
/bin/bash
Resulting file format: should mimic Linux's /etc/passwd file format with particular attention to the "," separator used in the GECOS field. But if the specific language has a particular or unique format of storing records in text file, then this format should be named and demonstrated with an additional example.
Expected output:
Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash
Finally: Provide a summary of the language's "append record" capabilities in a table. eg.
Append Capabilities.
Data Representation
IO
Library
Append
Possible
Automatic
Append
Multi-tasking
Safe
In core
On disk
C struct
CSV text file
glibc/stdio
☑
☑
☑ (Not all, eg NFS)
Alternatively: If the language's appends can not guarantee its writes will always append, then note this restriction in the table. If possible, provide an actual code example (possibly using file/record locking) to guarantee correct concurrent appends.
| #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,*/
/* it could be open from calling pgm.*/
call writeRec tFID,, /*append the 1st record to the file. */
'jsmith',"x", 1001, 1000, 'Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]', "/home/jsmith", '/bin/bash'
call writeRec tFID,, /*append the 2nd record to the file. */
'jdoe', "x", 1002, 1000, 'Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]', "/home/jsmith", '/bin/bash'
call lineout fid /*close the outfile (just to be tidy).*/
call writeRec tFID,, /*append the 3rd record to the file. */
'xyz', "x", 1003, 1000, 'X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]', "/home/xyz", '/bin/bash'
/*─account─pw────uid───gid──────────────fullname,office,extension,homephone,Email────────────────────────directory───────shell──*/
call lineout fid /*"be safe" programming: close the file*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1) /*pluralizer*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
writeRec: parse arg fid,_ /*get the fileID, and also the 1st arg.*/
sep=':' /*field delimiter used in file, it ··· */
/* ··· can be unique and any size.*/
do i=3 to arg() /*get each argument and append it to */
_=_ || sep || arg(i) /* the previous arg, with a : sep.*/
end /*i*/
do tries=0 for 11 /*keep trying for 66 seconds. */
r=lineout(fid, _) /*write (append) the new record. */
if r==0 then return /*Zero? Then record was written. */
call sleep tries /*Error? So try again after a delay. */
end /*tries*/ /*Note: not all REXXes have SLEEP. */
say '***error***'; say r 'record's(r) "not written to file" fid; exit 13
/*some error causes: no write access, disk is full, file lockout, no authority*/ |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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")
(setf (gethash "CO" my-hash) "Carbon Monoxide")
;; That was actually a hash table, an associative array or
;; alist is written like this:
(defparameter *legs* '((cow . 4) (flamingo . 2) (centipede . 100)))
;; you can use assoc to do lookups and cons new elements onto it to make it longer. |
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 appropriate or possible to support an unspecified value type, use integers.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Scheme | Scheme | (define (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 car
(filter (lambda (x) (= (cdr x) (apply max (map cdr (helper collection '())))))
(helper collection '()))) |
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 list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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 list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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 value in values(dict)
@show value
end
|
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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.
Reference
The OEIS entry: A063989: Numbers with a prime number of prime divisors.
| #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.
Reference
The OEIS entry: A063989: Numbers with a prime number of prime divisors.
| #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((Double(self).squareRoot())))
for i in stride(from: 2, through: max, by: 1) {
if self % i == 0 {
return false
}
}
return true
}
@inlinable
public func primeDecomposition() -> [Self] {
guard self > 1 else { return [] }
func step(_ x: Self) -> Self {
return 1 + (x << 2) - ((x >> 1) << 1)
}
let maxQ = Self(Double(self).squareRoot())
var d: Self = 1
var q: Self = self & 1 == 0 ? 2 : 3
while q <= maxQ && self % q != 0 {
q = step(d)
d += 1
}
return q <= maxQ ? [q] + (self / q).primeDecomposition() : [self]
}
}
let attractive = Array((1...).lazy.filter({ $0.isAttractive }).prefix(while: { $0 <= 120 }))
print("Attractive numbers up to and including 120: \(attractive)") |
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 to this. One is to sort the elements, and then pick the element(s) in the middle.
Sorting would take at least O(n logn). Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s). This would also take O(n logn). The best solution is to use the selection algorithm to find the median in O(n) time.
See also
Quickselect_algorithm
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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();
}
function : native : DoMedian(numbers : FloatVector) ~ Float {
if(numbers->Size() = 0) {
return 0.0;
}
else if(numbers->Size() = 1) {
return numbers->Get(0);
};
numbers->Sort();
i := numbers->Size() / 2;
if(numbers->Size() % 2 = 0) {
return (numbers->Get(i - 1) + numbers->Get(i)) / 2.0;
};
return numbers->Get(i);
}
}
}
|
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 positive integers.
The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
A
(
x
1
,
…
,
x
n
)
=
x
1
+
⋯
+
x
n
n
{\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}}
The geometric mean is the
n
{\displaystyle n}
th root of the product of the list:
G
(
x
1
,
…
,
x
n
)
=
x
1
⋯
x
n
n
{\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}}
The harmonic mean is
n
{\displaystyle n}
divided by the sum of the reciprocal of each item in the list:
H
(
x
1
,
…
,
x
n
)
=
n
1
x
1
+
⋯
+
1
x
n
{\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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 over numbers
mean += number
end
return mean / numbers~items
::routine geometricMean
use arg numbers
-- somewhat arbitrary return for ooRexx
if numbers~isEmpty then return "NaN"
mean = 1
loop number over numbers
mean *= number
end
return rxcalcPower(mean, 1 / numbers~items)
::routine harmonicMean
use arg numbers
-- somewhat arbitrary return for ooRexx
if numbers~isEmpty then return "NaN"
mean = 0
loop number over numbers
if number = 0 then return "Nan"
mean += 1 / number
end
-- problem here....
return numbers~items / mean
::requires rxmath LIBRARY |
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #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, where many jobs may be appending to the log file at the same time, or where care must be taken to avoid concurrently overwriting the same record from another job.
Task
Given a two record sample for a mythical "passwd" file:
Write these records out in the typical system format.
Ideally these records will have named fields of various types.
Close the file, then reopen the file for append.
Append a new record to the file and close the file again.
Take appropriate care to avoid concurrently overwrites from another job.
Open the file and demonstrate the new record has indeed written to the end.
Source record field types and contents.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
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
Record to be appended.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
xyz
x
1003
1000
X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]
/home/xyz
/bin/bash
Resulting file format: should mimic Linux's /etc/passwd file format with particular attention to the "," separator used in the GECOS field. But if the specific language has a particular or unique format of storing records in text file, then this format should be named and demonstrated with an additional example.
Expected output:
Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash
Finally: Provide a summary of the language's "append record" capabilities in a table. eg.
Append Capabilities.
Data Representation
IO
Library
Append
Possible
Automatic
Append
Multi-tasking
Safe
In core
On disk
C struct
CSV text file
glibc/stdio
☑
☑
☑ (Not all, eg NFS)
Alternatively: If the language's appends can not guarantee its writes will always append, then note this restriction in the table. If possible, provide an actual code example (possibly using file/record locking) to guarantee correct concurrent appends.
| #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('jsmith','x',1001, 1000, Gecos.new('Joe Smith', 'Room 1007', '(234)555-8917', '(234)555-0077', '[email protected]'), '/home/jsmith', '/bin/bash')
jdoe = Passwd.new('jdoe','x',1002, 1000, Gecos.new('Jane Doe', 'Room 1004', '(234)555-8914', '(234)555-0044', '[email protected]'), '/home/jdoe', '/bin/bash')
xyz = Passwd.new('xyz','x',1003, 1000, Gecos.new('X Yz', 'Room 1003', '(234)555-8913', '(234)555-0033', '[email protected]'), '/home/xyz', '/bin/bash')
filename = 'append.records.test'
# create the passwd file with two records
File.open(filename, 'w') do |io|
io.puts jsmith
io.puts jdoe
end
puts "before appending:"
puts File.readlines(filename)
# append the third record
File.open(filename, 'a') do |io|
io.puts xyz
end
puts "after appending:"
puts File.readlines(filename) |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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): Boxes.Object, NEW;
(h: Hash) Remove (k: Boxes.Object): Boxes.Object, NEW;
(h: Hash) Reset, NEW
END;
HashMap = POINTER TO RECORD
cap-, size-: INTEGER;
(hm: HashMap) ContainsKey (k: Boxes.Object): BOOLEAN, NEW;
(hm: HashMap) ContainsValue (v: Boxes.Object): BOOLEAN, NEW;
(hm: HashMap) Get (k: Boxes.Object): Boxes.Object, NEW;
(hm: HashMap) IsEmpty (): BOOLEAN, NEW;
(hm: HashMap) Keys (): POINTER TO ARRAY OF Boxes.Object, NEW;
(hm: HashMap) Put (k, v: Boxes.Object): Boxes.Object, NEW;
(hm: HashMap) Remove (k: Boxes.Object): Boxes.Object, NEW;
(hm: HashMap) Reset, NEW;
(hm: HashMap) Values (): POINTER TO ARRAY OF Boxes.Object, NEW
END;
LinkedList = POINTER TO RECORD
first-, last-: Node;
size-: INTEGER;
(ll: LinkedList) Add (item: Boxes.Object), NEW;
(ll: LinkedList) Append (item: Boxes.Object), NEW;
(ll: LinkedList) AsString (): POINTER TO ARRAY OF CHAR, NEW;
(ll: LinkedList) Contains (item: Boxes.Object): BOOLEAN, NEW;
(ll: LinkedList) Get (at: INTEGER): Boxes.Object, NEW;
(ll: LinkedList) IndexOf (item: Boxes.Object): INTEGER, NEW;
(ll: LinkedList) Insert (at: INTEGER; item: Boxes.Object), NEW;
(ll: LinkedList) IsEmpty (): BOOLEAN, NEW;
(ll: LinkedList) Remove (item: Boxes.Object), NEW;
(ll: LinkedList) RemoveAt (at: INTEGER), NEW;
(ll: LinkedList) Reset, NEW;
(ll: LinkedList) Set (at: INTEGER; item: Boxes.Object), NEW
END;
Vector = POINTER TO RECORD
size-, cap-: LONGINT;
(v: Vector) Add (item: Boxes.Object), NEW;
(v: Vector) AddAt (item: Boxes.Object; i: INTEGER), NEW;
(v: Vector) Contains (o: Boxes.Object): BOOLEAN, NEW;
(v: Vector) Get (i: LONGINT): Boxes.Object, NEW;
(v: Vector) IndexOf (o: Boxes.Object): LONGINT, NEW;
(v: Vector) Remove (o: Boxes.Object), NEW;
(v: Vector) RemoveIndex (i: LONGINT): Boxes.Object, NEW;
(v: Vector) Set (i: LONGINT; o: Boxes.Object): Boxes.Object, NEW;
(v: Vector) Trim, NEW
END;
PROCEDURE NewHash (cap: INTEGER): Hash;
PROCEDURE NewHashMap (cap: INTEGER): HashMap;
PROCEDURE NewLinkedList (): LinkedList;
PROCEDURE NewVector (cap: INTEGER): Vector;
END Collections.
|
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
count 20 < dup if
n 1 + var n
n count_divisors
dup max_divisors > if
n print " " print
var max_divisors
count 1 + var count
else
drop
endif
endif
endwhile
nl
msec print |
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 appropriate or possible to support an unspecified value type, use integers.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
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] integer).value;
var elemType: aValue is elemType.value;
var integer: maximum is 0;
begin
for aValue range data do
if aValue in counts then
incr(counts[aValue]);
else
counts @:= [aValue] 1;
end if;
if counts[aValue] > maximum then
maximum := counts[aValue];
maxElems := [] (aValue);
elsif counts[aValue] = maximum then
maxElems &:= aValue;
end if;
end for;
end func;
const func string: str (in array elemType: data) is func
result
var string: stri is "";
local
var elemType: anElement is elemType.value;
begin
for anElement range data do
stri &:= " " & str(anElement);
end for;
stri := stri[2 ..];
end func;
enable_output(array elemType);
end func;
createModeFunction(integer);
const proc: main is func
begin
writeln(mode([] (1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17)));
writeln(mode([] (1, 1, 2, 4, 4)));
end func; |
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 appropriate or possible to support an unspecified value type, use integers.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Sidef | Sidef | func 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 list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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 list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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.
Reference
The OEIS entry: A063989: Numbers with a prime number of prime divisors.
| #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 divisor found
}
proc cntPF {n} {
set cnt 0
while {0 == ($n % 2)} {
set n [expr {$n / 2}]
incr cnt
}
for {set d 3} {($d * $d) <= $n} {incr d 2} {
while {0 == ($n % $d)} {
set n [expr {$n / $d}]
incr cnt
}
}
if {$n > 1} {
incr cnt
}
return $cnt
}
proc showRange {lo hi} {
puts "Attractive numbers in range $lo..$hi are:"
set k 0
for {set n $lo} {$n <= $hi} {incr n} {
if {[isPrime [cntPF $n]]} {
puts -nonewline " [format %3s $n]"
incr k
}
if {$k >= 20} {
puts ""
set k 0
}
}
if {$k > 0} {
puts ""
}
}
showRange 1 120 |
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 to this. One is to sort the elements, and then pick the element(s) in the middle.
Sorting would take at least O(n logn). Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s). This would also take O(n logn). The best solution is to use the selection algorithm to find the median in O(n) time.
See also
Quickselect_algorithm
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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 positive integers.
The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
A
(
x
1
,
…
,
x
n
)
=
x
1
+
⋯
+
x
n
n
{\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}}
The geometric mean is the
n
{\displaystyle n}
th root of the product of the list:
G
(
x
1
,
…
,
x
n
)
=
x
1
⋯
x
n
n
{\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}}
The harmonic mean is
n
{\displaystyle n}
divided by the sum of the reciprocal of each item in the list:
H
(
x
1
,
…
,
x
n
)
=
n
1
x
1
+
⋯
+
1
x
n
{\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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}
{Len Xs}
/
{Sum {Map Xs fun {$ X} 1.0 / X end}}
end
Numbers = {Map {List.number 1 10 1} Int.toFloat}
[A G H] = [{AMean Numbers} {GMean Numbers} {HMean Numbers}]
in
{Show [A G H]}
A >= G = true
G >= H = true |
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #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 {
return false; // non-bracket chars
}
if (brackets < 0) { // closing bracket before opening bracket
return false;
}
}
return brackets == 0;
}
public static String generateBalancedBrackets(int n) {
assert n % 2 == 0; // if n is odd we can't match brackets
char[] ans = new char[n];
int openBracketsLeft = n / 2;
int unclosed = 0;
for (int i = 0; i < n; i++) {
if (Math.random() >= 0.5 && openBracketsLeft > 0 || unclosed == 0) {
ans[i] = '[';
openBracketsLeft--;
unclosed++;
} else {
ans[i] = ']';
unclosed--;
}
}
return String.valueOf(ans);
}
public static void main(String[] args) {
for (int i = 0; i <= 16; i += 2) {
String brackets = generateBalancedBrackets(i);
System.out.println(brackets + ": " + hasBalancedBrackets(brackets));
}
String[] tests = {"", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]"};
for (String test : tests) {
System.out.println(test + ": " + hasBalancedBrackets(test));
}
}
} |
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, where many jobs may be appending to the log file at the same time, or where care must be taken to avoid concurrently overwriting the same record from another job.
Task
Given a two record sample for a mythical "passwd" file:
Write these records out in the typical system format.
Ideally these records will have named fields of various types.
Close the file, then reopen the file for append.
Append a new record to the file and close the file again.
Take appropriate care to avoid concurrently overwrites from another job.
Open the file and demonstrate the new record has indeed written to the end.
Source record field types and contents.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
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
Record to be appended.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
xyz
x
1003
1000
X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]
/home/xyz
/bin/bash
Resulting file format: should mimic Linux's /etc/passwd file format with particular attention to the "," separator used in the GECOS field. But if the specific language has a particular or unique format of storing records in text file, then this format should be named and demonstrated with an additional example.
Expected output:
Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash
Finally: Provide a summary of the language's "append record" capabilities in a table. eg.
Append Capabilities.
Data Representation
IO
Library
Append
Possible
Automatic
Append
Multi-tasking
Safe
In core
On disk
C struct
CSV text file
glibc/stdio
☑
☑
☑ (Not all, eg NFS)
Alternatively: If the language's appends can not guarantee its writes will always append, then note this restriction in the table. If possible, provide an actual code example (possibly using file/record locking) to guarantee correct concurrent appends.
| #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: String,
pub uid: u64,
pub gid: u64,
pub gecos: Vec<String>,
pub directory: String,
pub shell: String,
}
impl PasswordRecord {
/// new instance, cloning all fields
pub fn new(
account: &str,
password: &str,
uid: u64,
gid: u64,
gecos: Vec<&str>,
directory: &str,
shell: &str,
) -> PasswordRecord {
PasswordRecord {
account: account.to_string(),
password: password.to_string(),
uid,
gid,
gecos: gecos.iter().map(|s| s.to_string()).collect(),
directory: directory.to_string(),
shell: shell.to_string(),
}
}
/// convert to one line string
pub fn to_line(&self) -> String {
let gecos = self.gecos.join(",");
format!(
"{}:{}:{}:{}:{}:{}:{}",
self.account, self.password, self.uid, self.gid, gecos, self.directory, self.shell
)
}
/// read record from line
pub fn from_line(line: &str) -> PasswordRecord {
let sp: Vec<&str> = line.split(":").collect();
if sp.len() < 7 {
panic!("Less than 7 fields found");
} else {
let uid = sp[2].parse().expect("Cannot parse uid");
let gid = sp[3].parse().expect("Cannot parse gid");
let gecos = sp[4].split(",").collect();
PasswordRecord::new(sp[0], sp[1], uid, gid, gecos, sp[5], sp[6])
}
}
}
/// read all records from file
pub fn read_password_file(file_name: &str) -> Result<Vec<PasswordRecord>> {
let p = Path::new(file_name);
if !p.exists() {
Ok(vec![])
} else {
let f = OpenOptions::new().read(true).open(p)?;
Ok(BufReader::new(&f)
.lines()
.map(|l| PasswordRecord::from_line(&l.unwrap()))
.collect())
}
}
/// overwrite file with records
pub fn overwrite_password_file(file_name: &str, recs: &Vec<PasswordRecord>) -> Result<()> {
let f = OpenOptions::new()
.create(true)
.write(true)
.open(file_name)?;
write_records(f, recs)
}
/// append records to file
pub fn append_password_file(file_name: &str, recs: &Vec<PasswordRecord>) -> Result<()> {
let f = OpenOptions::new()
.create(true)
.append(true)
.open(file_name)?;
write_records(f, recs)
}
/// internal, write records line by line
fn write_records(f: File, recs: &Vec<PasswordRecord>) -> Result<()> {
let mut writer = BufWriter::new(f);
for rec in recs {
write!(writer, "{}\n", rec.to_line())?;
}
Ok(())
}
fn main(){
let recs1 = vec![
PasswordRecord::new(
"jsmith",
"x",
1001,
1000,
vec![
"Joe Smith",
"Room 1007",
"(234)555-8917",
"(234)555-0077",
"[email protected]",
],
"/home/jsmith",
"/bin/bash",
),
PasswordRecord::new(
"jdoe",
"x",
1002,
1000,
vec![
"Jane Doe",
"Room 1004",
"(234)555-8914",
"(234)555-0044",
"[email protected]",
],
"/home/jdoe",
"/bin/bash",
),
];
overwrite_password_file("passwd", &recs1).expect("cannot write file");
let recs2 = read_password_file("passwd").expect("cannot read file");
println!("Original file:");
for r in recs2 {
println!("{}",r.to_line());
}
let append0 = vec![PasswordRecord::new(
"xyz",
"x",
1003,
1000,
vec![
"X Yz",
"Room 1003",
"(234)555-8913",
"(234)555-0033",
"[email protected]",
],
"/home/xyz",
"/bin/bash",
)];
append_password_file("passwd", &append0).expect("cannot append to file");
let recs2 = read_password_file("passwd").expect("cannot read file");
println!("");
println!("Appended file:");
for r in recs2 {
println!("{}",r.to_line());
}
}
|
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, where many jobs may be appending to the log file at the same time, or where care must be taken to avoid concurrently overwriting the same record from another job.
Task
Given a two record sample for a mythical "passwd" file:
Write these records out in the typical system format.
Ideally these records will have named fields of various types.
Close the file, then reopen the file for append.
Append a new record to the file and close the file again.
Take appropriate care to avoid concurrently overwrites from another job.
Open the file and demonstrate the new record has indeed written to the end.
Source record field types and contents.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
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
Record to be appended.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
xyz
x
1003
1000
X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]
/home/xyz
/bin/bash
Resulting file format: should mimic Linux's /etc/passwd file format with particular attention to the "," separator used in the GECOS field. But if the specific language has a particular or unique format of storing records in text file, then this format should be named and demonstrated with an additional example.
Expected output:
Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash
Finally: Provide a summary of the language's "append record" capabilities in a table. eg.
Append Capabilities.
Data Representation
IO
Library
Append
Possible
Automatic
Append
Multi-tasking
Safe
In core
On disk
C struct
CSV text file
glibc/stdio
☑
☑
☑ (Not all, eg NFS)
Alternatively: If the language's appends can not guarantee its writes will always append, then note this restriction in the table. If possible, provide an actual code example (possibly using file/record locking) to guarantee correct concurrent appends.
| #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 <: {def close() : Unit}, B](resource: A)(f: A => B): B =
try f(resource) finally resource.close()
def rawData =
"""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
|xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash""".stripMargin
case class Record(account: String,
password: String,
uid: Int,
gid: Int,
gecos: Array[String],
directory: String,
shell: String) {
def asLine: String = s"$account:$password:$uid:$gid:${gecos.mkString(",")}:$directory:$shell\n"
}
object Record {
def apply(line: String): Record = {
val token = line.trim.split(":")
require((token != null) || (token.length == 7))
this(token(0).trim,
token(1).trim,
Integer.parseInt(token(2).trim),
Integer.parseInt(token(3).trim),
token(4).split(","),
token(5).trim,
token(6).trim)
}
}
try {
val file = File.createTempFile("_rosetta", ".passwd")
using(new FileWriter(file))(writer => rawDataIt.take(2).foreach(line => writer.write(Record(line).asLine)))
writeStringToFile(file, Record(rawDataIt.next()).asLine, appending = true) // Append a record
Source.fromFile(file).getLines().foreach(line => {
if (line startsWith """xyz""") print(s"Selected record: ${Record(line).asLine}")
})
scala.compat.Platform.collectGarbage() // JVM Windows related bug workaround JDK-4715154
file.deleteOnExit()
} catch {
case e: IOException => println(s"Running Example failed: ${e.getMessage}")
}
} // 57 lines |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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 := count_divisors(N),
if (D > MaxDiv) then
printf("%d ", N),
MaxDiv := D,
Count := Count + 1
end,
N := N + 1
end,
nl.
|
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)
(link N)
(setq M R)
(inc 'I) ) ) ) ) ) )
(println (anti 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
| #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 1; \terminate the program; pass optional error code to DOS
];
if X#42 then Fatal("X#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.
| #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 appropriate or possible to support an unspecified value type, use integers.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Slate | Slate | 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 appropriate or possible to support an unspecified value type, use integers.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Smalltalk | Smalltalk | 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 list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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 list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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 separately
'\n'
' Map Keys: '+#aMap->keys->join(',')+'\n'
' Map values: '+#aMap->values->join(',')+'\n'
//display using forEach
'\n'
' Use ForEach to iterate Map keys: \n'
#aMap->keys->forEach => {^
#1+'\n'
^}
'\n'
' Use ForEach to iterate Map values: \n'
#aMap->values->forEach => {^
#1+'\n'
^}
//the {^ ^} indicates that output should be printed (AutoCollect) ,
// if output is not desired, just { } is used
|
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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.
Reference
The OEIS entry: A063989: Numbers with a prime number of prime divisors.
| #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;
var f = 2;
if (n == 1) return 0;
if (is_prime(n)) return 1;
while (true) {
if (n % f == 0) {
count++;
n /= f;
if (n == 1) return count;
if (is_prime(n)) f = n;
} else if (f >= 3) {
f += 2;
} else {
f = 3;
}
}
}
void main() {
const int MAX = 120;
var n = 0;
var count = 0;
stdout.printf(@"The attractive numbers up to and including $MAX are:\n");
for (int i = 1; i <= MAX; i++) {
n = count_prime_factors(i);
if (is_prime(n)) {
stdout.printf("%4d", i);
count++;
if (count % 20 == 0)
stdout.printf("\n");
}
}
stdout.printf("\n");
} |
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 to this. One is to sort the elements, and then pick the element(s) in the middle.
Sorting would take at least O(n logn). Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s). This would also take O(n logn). The best solution is to use the selection algorithm to find the median in O(n) time.
See also
Quickselect_algorithm
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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];
disp(median2(a)) % 4.4
disp(median(a))
disp(median2(b)) % 4.25
disp(median(b)) |
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 positive integers.
The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
A
(
x
1
,
…
,
x
n
)
=
x
1
+
⋯
+
x
n
n
{\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}}
The geometric mean is the
n
{\displaystyle n}
th root of the product of the list:
G
(
x
1
,
…
,
x
n
)
=
x
1
⋯
x
n
n
{\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}}
The harmonic mean is
n
{\displaystyle n}
divided by the sum of the reciprocal of each item in the list:
H
(
x
1
,
…
,
x
n
)
=
n
1
x
1
+
⋯
+
1
x
n
{\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #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 = Math.random() * 10 | 0, bs = shuffle('['.repeat(N) + ']'.repeat(N))
console.log('"' + bs + '" is ' + (isBalanced(bs) ? '' : 'un') + 'balanced')
} |
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, where many jobs may be appending to the log file at the same time, or where care must be taken to avoid concurrently overwriting the same record from another job.
Task
Given a two record sample for a mythical "passwd" file:
Write these records out in the typical system format.
Ideally these records will have named fields of various types.
Close the file, then reopen the file for append.
Append a new record to the file and close the file again.
Take appropriate care to avoid concurrently overwrites from another job.
Open the file and demonstrate the new record has indeed written to the end.
Source record field types and contents.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
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
Record to be appended.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
xyz
x
1003
1000
X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]
/home/xyz
/bin/bash
Resulting file format: should mimic Linux's /etc/passwd file format with particular attention to the "," separator used in the GECOS field. But if the specific language has a particular or unique format of storing records in text file, then this format should be named and demonstrated with an additional example.
Expected output:
Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash
Finally: Provide a summary of the language's "append record" capabilities in a table. eg.
Append Capabilities.
Data Representation
IO
Library
Append
Possible
Automatic
Append
Multi-tasking
Safe
In core
On disk
C struct
CSV text file
glibc/stdio
☑
☑
☑ (Not all, eg NFS)
Alternatively: If the language's appends can not guarantee its writes will always append, then note this restriction in the table. If possible, provide an actual code example (possibly using file/record locking) to guarantee correct concurrent appends.
| #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 => 'jsmith',
password => 'x',
UID => 1001,
GID => 1000,
GECOS => Hash(
fullname => 'John Smith',
office => 'Room 1007',
extension => '(234)555-8917',
homephone => '(234)555-0077',
email => '[email protected]',
),
directory => '/home/jsmith',
shell => '/bin/bash',
),
Hash(
account => 'jdoe',
password => 'x',
UID => 1002,
GID => 1000,
GECOS => Hash(
fullname => 'Jane Doe',
office => 'Room 1004',
extension => '(234)555-8914',
homephone => '(234)555-0044',
email => '[email protected]',
),
directory => '/home/jdoe',
shell => '/bin/bash',
),
];
var record_to_append = Hash(
account => 'xyz',
password => 'x',
UID => 1003,
GID => 1000,
GECOS => Hash(
fullname => 'X Yz',
office => 'Room 1003',
extension => '(234)555-8913',
homephone => '(234)555-0033',
email => '[email protected]',
),
directory => '/home/xyz',
shell => '/bin/bash',
);
func record_to_string(rec, sep = RECORD_SEP, fields = RECORD_FIELDS) {
gather {
fields.each { |field|
var r = rec{field} \\ die "Field #{field} not found"
take(field == 'GECOS' ? record_to_string(r, GECOS_SEP, GECOS_FIELDS)
: r)
}
}.join(sep)
}
func write_records_to_file(records, filename = PASSWD_FILE, append = false) {
File(filename).(append ? :open_a : :open_w)(\var fh, \var err)
err && die "Can't open #{filename}: #{err}";
fh.flock(File.LOCK_EX) || die "Can't lock #{filename}: $!"
fh.seek(0, File.SEEK_END) || die "Can't seek #{filename}: $!"
records.each { |record| fh.say(record_to_string(record)) }
fh.flock(File.LOCK_UN) || die "Can't unlock #{filename}: $!"
fh.close
}
# write two records to file
write_records_to_file(records: records_to_write);
# append one more record to file
write_records_to_file(records: [record_to_append], append: true);
# test
File(PASSWD_FILE).open_r(\var fh, \var err)
err && die "Can't open file #{PASSWD_FILE}: #{err}"
var lines = fh.lines
# There should be more than one line
assert(lines.len > 1)
# Check the last line
assert_eq(lines[-1], 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,' +
'(234)555-0033,[email protected]:/home/xyz:/bin/bash')
say "** Test passed!" |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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(count);
end countFactors;
declare maxFactors fixed static init (0);
declare seen fixed static init (0);
declare n fixed;
declare factors fixed;
do n=1 repeat(n+1) while(seen < 20);
factors = countFactors(n);
if factors > maxFactors then do;
put edit(n) (F(5));
maxFactors = factors;
seen = seen + 1;
if mod(seen,15) = 0 then put skip;
end;
end;
end antiprimes; |
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 appropriate or possible to support an unspecified value type, use integers.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #SQL | SQL | -- 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 INTO averages VALUES (2);
INSERT INTO averages VALUES (3);
INSERT INTO averages VALUES (3);
INSERT INTO averages VALUES (1);
INSERT INTO averages VALUES (3);
INSERT INTO averages VALUES (6);
-- find the mode
WITH
counts AS
(
SELECT
val,
COUNT(*) AS num
FROM
averages
GROUP BY
val
)
SELECT
val AS mode_val
FROM
counts
WHERE
num IN (SELECT MAX(num) FROM counts); |
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 list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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 list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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.Keys( myAssocList$, keys$)
print " Number of key-data pairs ="; keys
For i = 1 To keys
keyName$ = sl.Get$( keys$, Str$( i))
Print " Key "; i; ":", keyName$, "Data: ", sl.Get$( myAssocList$, keyName$)
Next i
end
|
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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 conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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.
Reference
The OEIS entry: A063989: Numbers with a prime number of prime divisors.
| #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 Then
IsPrime = False
GoTo Finish
End If
If n Mod 2 = 0 Then
IsPrime = (n = 2)
GoTo Finish
End If
If n Mod 3 = 0 Then
IsPrime = (n = 3)
GoTo Finish
End If
While (d * d <= n)
If (n Mod d = 0) Then IsPrime = False
d = d + 2
If (n Mod d = 0) Then IsPrime = False
d = d + 4
Wend
Finish:
End Function
Public Function CountPrimeFactors(ByVal n As Integer) As Integer
Dim count As Integer, f As Integer
If n = 1 Then
CountPrimeFactors = 0
GoTo Finish2
End If
If (IsPrime(n)) Then
CountPrimeFactors = 1
GoTo Finish2
End If
count = 0
f = 2
Do While (True)
If n Mod f = 0 Then
count = count + 1
n = n / f
If n = 1 Then
CountPrimeFactors = count
Exit Do
End If
If IsPrime(n) Then f = n
ElseIf f >= 3 Then
f = f + 2
Else
f = 3
End If
Loop
Finish2:
End Function |
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.
Reference
The OEIS entry: A063989: Numbers with a prime number of prime divisors.
| #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
If n Mod d = 0 Then Return False
d += 4
End While
Return True
End Function
Function PrimefactorCount(n As Integer) As Integer
If n = 1 Then Return 0
If IsPrime(n) Then Return 1
Dim count = 0
Dim f = 2
While True
If n Mod f = 0 Then
count += 1
n /= f
If n = 1 Then Return count
If IsPrime(n) Then f = n
ElseIf f >= 3 Then
f += 2
Else
f = 3
End If
End While
Throw New Exception("Unexpected")
End Function
Sub Main()
Console.WriteLine("The attractive numbers up to and including {0} are:", MAX)
Dim i = 1
Dim count = 0
While i <= MAX
Dim n = PrimefactorCount(i)
If IsPrime(n) Then
Console.Write("{0,4}", i)
count += 1
If count Mod 20 = 0 Then
Console.WriteLine()
End If
End If
i += 1
End While
Console.WriteLine()
End Sub
End Module |
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 to this. One is to sort the elements, and then pick the element(s) in the middle.
Sorting would take at least O(n logn). Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s). This would also take O(n logn). The best solution is to use the selection algorithm to find the median in O(n) time.
See also
Quickselect_algorithm
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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 "median =" median(numbers)
say
::routine median
use arg numbers
if numbers~isempty then return 0
-- make a copy so the sort does not alter the
-- original set. This also means this will
-- work with lists and queues as well
numbers = numbers~makearray
-- sort and return the middle element
numbers~sortWith(.numbercomparator~new)
size = numbers~items
-- this handles the odd value too
return numbers[size%2 + size//2]
-- a custom comparator that sorts strings as numeric values rather than
-- strings
::class numberComparator subclass comparator
::method compare
use strict arg left, right
-- perform the comparison on the names. By subtracting
-- the two and returning the sign, we give the expected
-- results for the compares
return (left - right)~sign
|
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 positive integers.
The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
A
(
x
1
,
…
,
x
n
)
=
x
1
+
⋯
+
x
n
n
{\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}}
The geometric mean is the
n
{\displaystyle n}
th root of the product of the list:
G
(
x
1
,
…
,
x
n
)
=
x
1
⋯
x
n
n
{\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}}
The harmonic mean is
n
{\displaystyle n}
divided by the sum of the reciprocal of each item in the list:
H
(
x
1
,
…
,
x
n
)
=
n
1
x
1
+
⋯
+
1
x
n
{\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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(@ints);
my $h = H(@ints);
print "A=$a\nG=$g\nH=$h\n";
die "Error" unless $a >= $g and $g >= $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) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #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, balancedbrackets(x)), collect(brackets(i) for i = 0:8))
@printf("%22s%10s\n", test, pass ? "pass" : "fail")
end |
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, where many jobs may be appending to the log file at the same time, or where care must be taken to avoid concurrently overwriting the same record from another job.
Task
Given a two record sample for a mythical "passwd" file:
Write these records out in the typical system format.
Ideally these records will have named fields of various types.
Close the file, then reopen the file for append.
Append a new record to the file and close the file again.
Take appropriate care to avoid concurrently overwrites from another job.
Open the file and demonstrate the new record has indeed written to the end.
Source record field types and contents.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
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
Record to be appended.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
xyz
x
1003
1000
X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]
/home/xyz
/bin/bash
Resulting file format: should mimic Linux's /etc/passwd file format with particular attention to the "," separator used in the GECOS field. But if the specific language has a particular or unique format of storing records in text file, then this format should be named and demonstrated with an additional example.
Expected output:
Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash
Finally: Provide a summary of the language's "append record" capabilities in a table. eg.
Append Capabilities.
Data Representation
IO
Library
Append
Possible
Automatic
Append
Multi-tasking
Safe
In core
On disk
C struct
CSV text file
glibc/stdio
☑
☑
☑ (Not all, eg NFS)
Alternatively: If the language's appends can not guarantee its writes will always append, then note this restriction in the table. If possible, provide an actual code example (possibly using file/record locking) to guarantee correct concurrent appends.
| #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
[email protected]
}
/home/jsmith
/bin/bash
}
{
jdoe
x
1002
1000
{
{Jane Doe}
{Room 1004}
(234)555-8914
(234)555-0044
[email protected]
}
/home/jsmith
/bin/bash
}
}
set addedRecords {
{
xyz
x
1003
1000
{
{X Yz}
{Room 1003}
(234)555-8913
(234)555-0033
[email protected]
}
/home/xyz
/bin/bash
}
}
proc printRecords {records fd} {
fconfigure $fd -buffering none
foreach record $records {
lset record 4 [join [lindex $record 4] ","]
puts -nonewline $fd [join $record ":"]\n
}
}
proc readRecords fd {
set result {}
foreach line [split [read $fd] "\n"] {
if {$line eq ""} continue
set record [split $line ":"]
# Special handling for GECOS
lset record 4 [split [lindex $record 4] ","]
lappend result $record
}
return $result
}
# Write basic set
set f [open ./passwd w]
printRecords $basicRecords $f
close $f
# Append the extra ones
# Use {WRONLY APPEND} on Tcl 8.4
set f [open ./passwd a]
printRecords $addedRecords $f
close $f
set f [open ./passwd]
set recs [readRecords $f]
close $f
puts "last record is for [lindex $recs end 0], named [lindex $recs end 4 0]" |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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 insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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 to use if key is present
ifAbsent: () => 'yes!' // Value to use if key is absent
);
assert( rosettaCode.toString() == '{task: Associative Array Creation, language: Dart, is fun: yes!}');
// If we type the Map with dynamic keys and values, it is like a JavaScript object
Map<dynamic, dynamic> jsObject = {
'key': 'value',
1: 2,
1.5: [ 'more', 'stuff' ],
#doStuff: () => print('doing stuff!') // #doStuff is a symbol, only one instance of this exists in the program. Would be :doStuff in Ruby
};
print( jsObject['key'] );
print( jsObject[1] );
for ( var value in jsObject[1.5] )
print('item: $value');
jsObject[ #doStuff ](); // Calling the function
print('\nKey types:');
jsObject.keys.forEach( (key) => print( key.runtimeType ) );
}
|
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, P) ADDRESS, C BASED P BYTE;
P = .S(5);
DIGIT:
P = P - 1;
C = N MOD 10 + '0';
N = N / 10;
IF N > 0 THEN GO TO DIGIT;
CALL PRINT(P);
END PRINT$NUMBER;
/* COUNT THE FACTORS OF A NUMBER */
COUNT$FACTORS: PROCEDURE (N) ADDRESS;
DECLARE (N, I, COUNT) ADDRESS;
IF N<2 THEN RETURN 1;
COUNT = 1;
DO I=1 TO N/2;
IF N MOD I = 0 THEN COUNT = COUNT + 1;
END;
RETURN COUNT;
END COUNT$FACTORS;
DECLARE MAX$FACTORS ADDRESS INITIAL (0);
DECLARE SEEN BYTE INITIAL (0);
DECLARE N ADDRESS INITIAL (1);
DECLARE FACTORS ADDRESS;
DO WHILE SEEN < 20;
FACTORS = COUNT$FACTORS(N);
IF FACTORS > MAX$FACTORS THEN DO;
CALL PRINT$NUMBER(N);
MAX$FACTORS = FACTORS;
SEEN = SEEN + 1;
END;
N = N + 1;
END;
CALL EXIT;
EOF |
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 appropriate or possible to support an unspecified value type, use integers.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Swift | Swift |
// 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 = [Element: Int]()
// Standard for loop. Can also use the forEach(_:) or reduce(into:) methods on self.
for element in self {
frequencies[element] = (frequencies[element] ?? 0) + 1
}
// The max(by:) method used here to find one of the elements with the highest associated count.
if let ( mode, _ ) = frequencies.max(by: { $0.value < $1.value }) {
return mode
} else {
return nil
}
}
}
["q", "a", "a", "a", "a", "b", "b", "z", "c", "c", "c"].mode() // returns "a"
[1, 1, 2, 3, 3, 3, 3, 4, 4, 4].mode() // returns 3
let emptyArray: [Int] = []
emptyArray.mode() // returns nil
|
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 appropriate or possible to support an unspecified value type, use integers.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Tcl | Tcl | # 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 best $n
} else break
}
return $best
}
# Testing
puts [mode 1 3 6 6 6 6 7 7 12 12 17]; # --> 6
puts [mode 1 1 2 4 4]; # --> 1 4 |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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 list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #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 array as combine will change variable
put fruit into fruit2
combine fruit2 using comma
put cr & "Values2:" & tab after tTmp
repeat for each item f2val in fruit2
put f2val & comma after tTmp
end repeat
combine fruit using return and ":"
put cr & "Key:Values" & cr & fruit after tTmp
-- alternatively, use same loop as for values 1 with tkey && fruit[tKey]
put tTmp |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.