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/Average_loop_length | Average loop length | Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence.
Task
Write a program or a script that estimates, for each N, the average length until the first such repetition.
Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.
This problem comes from the end of Donald Knuth's Christmas tree lecture 2011.
Example of expected output:
N average analytical (error)
=== ========= ============ =========
1 1.0000 1.0000 ( 0.00%)
2 1.4992 1.5000 ( 0.05%)
3 1.8784 1.8889 ( 0.56%)
4 2.2316 2.2188 ( 0.58%)
5 2.4982 2.5104 ( 0.49%)
6 2.7897 2.7747 ( 0.54%)
7 3.0153 3.0181 ( 0.09%)
8 3.2429 3.2450 ( 0.07%)
9 3.4536 3.4583 ( 0.14%)
10 3.6649 3.6602 ( 0.13%)
11 3.8091 3.8524 ( 1.12%)
12 3.9986 4.0361 ( 0.93%)
13 4.2074 4.2123 ( 0.12%)
14 4.3711 4.3820 ( 0.25%)
15 4.5275 4.5458 ( 0.40%)
16 4.6755 4.7043 ( 0.61%)
17 4.8877 4.8579 ( 0.61%)
18 4.9951 5.0071 ( 0.24%)
19 5.1312 5.1522 ( 0.41%)
20 5.2699 5.2936 ( 0.45%)
| #Python | Python | from __future__ import division # Only necessary for Python 2.X
from math import factorial
from random import randrange
MAX_N = 20
TIMES = 1000000
def analytical(n):
return sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))
def test(n, times):
count = 0
for i in range(times):
x, bits = 1, 0
while not (bits & x):
count += 1
bits |= x
x = 1 << randrange(n)
return count / times
if __name__ == '__main__':
print(" n\tavg\texp.\tdiff\n-------------------------------")
for n in range(1, MAX_N+1):
avg = test(n, TIMES)
theory = analytical(n)
diff = (avg / theory - 1) * 100
print("%2d %8.4f %8.4f %6.3f%%" % (n, avg, theory, diff)) |
http://rosettacode.org/wiki/Average_loop_length | Average loop length | Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence.
Task
Write a program or a script that estimates, for each N, the average length until the first such repetition.
Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.
This problem comes from the end of Donald Knuth's Christmas tree lecture 2011.
Example of expected output:
N average analytical (error)
=== ========= ============ =========
1 1.0000 1.0000 ( 0.00%)
2 1.4992 1.5000 ( 0.05%)
3 1.8784 1.8889 ( 0.56%)
4 2.2316 2.2188 ( 0.58%)
5 2.4982 2.5104 ( 0.49%)
6 2.7897 2.7747 ( 0.54%)
7 3.0153 3.0181 ( 0.09%)
8 3.2429 3.2450 ( 0.07%)
9 3.4536 3.4583 ( 0.14%)
10 3.6649 3.6602 ( 0.13%)
11 3.8091 3.8524 ( 1.12%)
12 3.9986 4.0361 ( 0.93%)
13 4.2074 4.2123 ( 0.12%)
14 4.3711 4.3820 ( 0.25%)
15 4.5275 4.5458 ( 0.40%)
16 4.6755 4.7043 ( 0.61%)
17 4.8877 4.8579 ( 0.61%)
18 4.9951 5.0071 ( 0.24%)
19 5.1312 5.1522 ( 0.41%)
20 5.2699 5.2936 ( 0.45%)
| #R | R |
expected <- function(size) {
result <- 0
for (i in 1:size) {
result <- result + factorial(size) / size^i / factorial(size -i)
}
result
}
knuth <- function(size) {
v <- sample(1:size, size, replace = TRUE)
visit <- vector('logical',size)
place <- 1
visit[[1]] <- TRUE
steps <- 0
repeat {
place <- v[[place]]
steps <- steps + 1
if (visit[[place]]) break
visit[[place]] <- TRUE
}
steps
}
cat(" N average analytical (error)\n")
cat("=== ========= ============ ==========\n")
for (num in 1:20) {
average <- mean(replicate(1e6, knuth(num)))
analytical <- expected(num)
error <- abs(average/analytical-1)*100
cat(sprintf("%3d%11.4f%14.4f ( %4.4f%%)\n", num, round(average,4), round(analytical,4), round(error,2)))
}
|
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period.
It can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA().
The word stateful in the task description refers to the need for SMA() to remember certain information between calls to it:
The period, P
An ordered container of at least the last P numbers from each of its individual calls.
Stateful also means that successive calls to I(), the initializer, should return separate routines that do not share saved state so they could be used on two independent streams of data.
Pseudo-code for an implementation of SMA is:
function SMA(number: N):
stateful integer: P
stateful list: stream
number: average
stream.append_last(N)
if stream.length() > P:
# Only average the last P elements of the stream
stream.delete_first()
if stream.length() == 0:
average = 0
else:
average = sum( stream.values() ) / stream.length()
return average
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 | class MovingAverage(period: Int) {
private var queue = new scala.collection.mutable.Queue[Double]()
def apply(n: Double) = {
queue.enqueue(n)
if (queue.size > period)
queue.dequeue
queue.sum / queue.size
}
override def toString = queue.mkString("(", ", ", ")")+", period "+period+", average "+(queue.sum / queue.size)
def clear = queue.clear
} |
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.
| #jq | jq |
def count(s): reduce s as $x (null; .+1);
def is_attractive:
count(prime_factors) | is_prime;
def printattractive($m; $n):
"The attractive numbers from \($m) to \($n) are:\n",
[range($m; $n+1) | select(is_attractive)];
printattractive(1; 120) |
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.
| #Julia | Julia | using Primes
# oneliner is println("The attractive numbers from 1 to 120 are:\n", filter(x -> isprime(sum(values(factor(x)))), 1:120))
isattractive(n) = isprime(sum(values(factor(n))))
printattractive(m, n) = println("The attractive numbers from $m to $n are:\n", filter(isattractive, m:n))
printattractive(1, 120)
|
http://rosettacode.org/wiki/Averages/Mean_time_of_day | Averages/Mean time of day | Task[edit]
A particular activity of bats occurs at these times of the day:
23:00:17, 23:40:20, 00:12:45, 00:17:19
Using the idea that there are twenty-four hours in a day,
which is analogous to there being 360 degrees in a circle,
map times of day to and from angles;
and using the ideas of Averages/Mean angle
compute and show the average time of the nocturnal activity
to an accuracy of one second of time.
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 | meanAngle(v)=atan(sum(i=1,#v,sin(v[i]))/sum(i=1,#v,cos(v[i])))%(2*Pi)
meanTime(v)=my(x=meanAngle(2*Pi*apply(u->u[1]/24+u[2]/1440+u[3]/86400, v))*12/Pi); [x\1, 60*(x-=x\1)\1, round(60*(60*x-60*x\1))]
meanTime([[23,0,17], [23,40,20], [0,12,45], [0,17,19]]) |
http://rosettacode.org/wiki/AVL_tree | AVL tree |
This page uses content from Wikipedia. The original article was at AVL tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In computer science, an AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; at no time do they differ by more than one because rebalancing is done ensure this is the case. Lookup, insertion, and deletion all take O(log n) time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations. Note the tree of nodes comprise a set, so duplicate node keys are not allowed.
AVL trees are often compared with red-black trees because they support the same set of operations and because red-black trees also take O(log n) time for the basic operations. Because AVL trees are more rigidly balanced, they are faster than red-black trees for lookup-intensive applications. Similar to red-black trees, AVL trees are height-balanced, but in general not weight-balanced nor μ-balanced; that is, sibling nodes can have hugely differing numbers of descendants.
Task
Implement an AVL tree in the language of choice, and provide at least basic operations.
| #Raku | Raku |
class AVL-Tree {
has $.root is rw = 0;
class Node {
has $.key is rw = '';
has $.parent is rw = 0;
has $.data is rw = 0;
has $.left is rw = 0;
has $.right is rw = 0;
has Int $.balance is rw = 0;
has Int $.height is rw = 0;
}
#=====================================================
# public methods
#=====================================================
#| returns a node object or 0 if not found
method find($key) {
return 0 if !$.root;
self!find: $key, $.root;
}
#| returns a list of tree keys
method keys() {
return () if !$.root;
my @list;
self!keys: $.root, @list;
@list;
}
#| returns a list of tree nodes
method nodes() {
return () if !$.root;
my @list;
self!nodes: $.root, @list;
@list;
}
#| insert a node key, optionally add data (the `parent` arg is for
#| internal use only)
method insert($key, :$data = 0, :$parent = 0,) {
return $.root = Node.new: :$key, :$parent, :$data if !$.root;
my $n = $.root;
while True {
return False if $n.key eq $key;
my $parent = $n;
my $goLeft = $n.key > $key;
$n = $goLeft ?? $n.left !! $n.right;
if !$n {
if $goLeft {
$parent.left = Node.new: :$key, :$parent, :$data;
}
else {
$parent.right = Node.new: :$key, :$parent, :$data;
}
self!rebalance: $parent;
last
}
}
True
}
#| delete one or more nodes by key
method delete(*@del-key) {
return if !$.root;
for @del-key -> $del-key {
my $child = $.root;
while $child {
my $node = $child;
$child = $del-key >= $node.key ?? $node.right !! $node.left;
if $del-key eq $node.key {
self!delete: $node;
next;
}
}
}
}
#| show a list of all nodes by key
method show-keys {
self!show-keys: $.root;
say()
}
#| show a list of all nodes' balances (not normally needed)
method show-balances {
self!show-balances: $.root;
say()
}
#=====================================================
# private methods
#=====================================================
method !delete($node) {
if !$node.left && !$node.right {
if !$node.parent {
$.root = 0;
}
else {
my $parent = $node.parent;
if $parent.left === $node {
$parent.left = 0;
}
else {
$parent.right = 0;
}
self!rebalance: $parent;
}
return
}
if $node.left {
my $child = $node.left;
while $child.right {
$child = $child.right;
}
$node.key = $child.key;
self!delete: $child;
}
else {
my $child = $node.right;
while $child.left {
$child = $child.left;
}
$node.key = $child.key;
self!delete: $child;
}
}
method !rebalance($n is copy) {
self!set-balance: $n;
if $n.balance == -2 {
if self!height($n.left.left) >= self!height($n.left.right) {
$n = self!rotate-right: $n;
}
else {
$n = self!rotate-left'right: $n;
}
}
elsif $n.balance == 2 {
if self!height($n.right.right) >= self!height($n.right.left) {
$n = self!rotate-left: $n;
}
else {
$n = self!rotate-right'left: $n;
}
}
if $n.parent {
self!rebalance: $n.parent;
}
else {
$.root = $n;
}
}
method !rotate-left($a) {
my $b = $a.right;
$b.parent = $a.parent;
$a.right = $b.left;
if $a.right {
$a.right.parent = $a;
}
$b.left = $a;
$a.parent = $b;
if $b.parent {
if $b.parent.right === $a {
$b.parent.right = $b;
}
else {
$b.parent.left = $b;
}
}
self!set-balance: $a, $b;
$b;
}
method !rotate-right($a) {
my $b = $a.left;
$b.parent = $a.parent;
$a.left = $b.right;
if $a.left {
$a.left.parent = $a;
}
$b.right = $a;
$a.parent = $b;
if $b.parent {
if $b.parent.right === $a {
$b.parent.right = $b;
}
else {
$b.parent.left = $b;
}
}
self!set-balance: $a, $b;
$b;
}
method !rotate-left'right($n) {
$n.left = self!rotate-left: $n.left;
self!rotate-right: $n;
}
method !rotate-right'left($n) {
$n.right = self!rotate-right: $n.right;
self!rotate-left: $n;
}
method !height($n) {
$n ?? $n.height !! -1;
}
method !set-balance(*@n) {
for @n -> $n {
self!reheight: $n;
$n.balance = self!height($n.right) - self!height($n.left);
}
}
method !show-balances($n) {
if $n {
self!show-balances: $n.left;
printf "%s ", $n.balance;
self!show-balances: $n.right;
}
}
method !reheight($node) {
if $node {
$node.height = 1 + max self!height($node.left), self!height($node.right);
}
}
method !show-keys($n) {
if $n {
self!show-keys: $n.left;
printf "%s ", $n.key;
self!show-keys: $n.right;
}
}
method !nodes($n, @list) {
if $n {
self!nodes: $n.left, @list;
@list.push: $n if $n;
self!nodes: $n.right, @list;
}
}
method !keys($n, @list) {
if $n {
self!keys: $n.left, @list;
@list.push: $n.key if $n;
self!keys: $n.right, @list;
}
}
method !find($key, $n) {
if $n {
self!find: $key, $n.left;
return $n if $n.key eq $key;
self!find: $key, $n.right;
}
}
}
|
http://rosettacode.org/wiki/Averages/Mean_angle | Averages/Mean angle | When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle.
If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the second was of 10 degrees then the average of the numbers is 180 degrees, whereas if you can note that 350 degrees is equivalent to -10 degrees and so you have two readings at 10 degrees either side of zero degrees leading to a more fitting mean angle of zero degrees.
To calculate the mean angle of several angles:
Assume all angles are on the unit circle and convert them to complex numbers expressed in real and imaginary form.
Compute the mean of the complex numbers.
Convert the complex mean to polar coordinates whereupon the phase of the complex mean is the required angular mean.
(Note that, since the mean is the sum divided by the number of numbers, and division by a positive real number does not affect the angle, you can also simply compute the sum for step 2.)
You can alternatively use this formula:
Given the angles
α
1
,
…
,
α
n
{\displaystyle \alpha _{1},\dots ,\alpha _{n}}
the mean is computed by
α
¯
=
atan2
(
1
n
⋅
∑
j
=
1
n
sin
α
j
,
1
n
⋅
∑
j
=
1
n
cos
α
j
)
{\displaystyle {\bar {\alpha }}=\operatorname {atan2} \left({\frac {1}{n}}\cdot \sum _{j=1}^{n}\sin \alpha _{j},{\frac {1}{n}}\cdot \sum _{j=1}^{n}\cos \alpha _{j}\right)}
Task[edit]
write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle.
(You should use a built-in function if you have one that does this for degrees or radians).
Use the function to compute the means of these lists of angles (in degrees):
[350, 10]
[90, 180, 270, 360]
[10, 20, 30]
Show your output here.
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
| #OCaml | OCaml | let pi = 3.14159_26535_89793_23846_2643
let deg2rad d =
d *. pi /. 180.0
let rad2deg r =
r *. 180.0 /. pi
let mean_angle angles =
let rad_angles = List.map deg2rad angles in
let sum_sin = List.fold_left (fun sum a -> sum +. sin a) 0.0 rad_angles
and sum_cos = List.fold_left (fun sum a -> sum +. cos a) 0.0 rad_angles
in
rad2deg (atan2 sum_sin sum_cos)
let test angles =
Printf.printf "The mean angle of [%s] is: %g degrees\n"
(String.concat "; " (List.map (Printf.sprintf "%g") angles))
(mean_angle angles)
let () =
test [350.0; 10.0];
test [90.0; 180.0; 270.0; 360.0];
test [10.0; 20.0; 30.0];
;; |
http://rosettacode.org/wiki/Averages/Mean_angle | Averages/Mean angle | When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle.
If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the second was of 10 degrees then the average of the numbers is 180 degrees, whereas if you can note that 350 degrees is equivalent to -10 degrees and so you have two readings at 10 degrees either side of zero degrees leading to a more fitting mean angle of zero degrees.
To calculate the mean angle of several angles:
Assume all angles are on the unit circle and convert them to complex numbers expressed in real and imaginary form.
Compute the mean of the complex numbers.
Convert the complex mean to polar coordinates whereupon the phase of the complex mean is the required angular mean.
(Note that, since the mean is the sum divided by the number of numbers, and division by a positive real number does not affect the angle, you can also simply compute the sum for step 2.)
You can alternatively use this formula:
Given the angles
α
1
,
…
,
α
n
{\displaystyle \alpha _{1},\dots ,\alpha _{n}}
the mean is computed by
α
¯
=
atan2
(
1
n
⋅
∑
j
=
1
n
sin
α
j
,
1
n
⋅
∑
j
=
1
n
cos
α
j
)
{\displaystyle {\bar {\alpha }}=\operatorname {atan2} \left({\frac {1}{n}}\cdot \sum _{j=1}^{n}\sin \alpha _{j},{\frac {1}{n}}\cdot \sum _{j=1}^{n}\cos \alpha _{j}\right)}
Task[edit]
write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle.
(You should use a built-in function if you have one that does this for degrees or radians).
Use the function to compute the means of these lists of angles (in degrees):
[350, 10]
[90, 180, 270, 360]
[10, 20, 30]
Show your output here.
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 | /*REXX program computes the mean angle (angles expressed in degrees). */
numeric digits 50 /*use fifty digits of precision, */
showDig=10 /*··· but only display 10 digits.*/
xl = 350 10 ; say showit(xl, meanAngleD(xl) )
xl = 90 180 270 360 ; say showit(xl, meanAngleD(xl) )
xl = 10 20 30 ; say showit(xl, meanAngleD(xl) )
exit /*stick a fork in it, we're done.*/
/*----------------------------------MEANANGD subroutine-----------------*/
meanAngleD: procedure; parse arg xl; numeric digits digits()+digits()%4
sum.=0
n=words(xl)
do j=1 to n
sum.0sin+=rxCalcSin(word(xl,j))
sum.0cos+=rxCalcCos(word(xl,j))
End
If sum.0cos=0 Then
Return sign(sum.0sin/n)*90
Else
Return rxCalcArcTan((sum.0sin/n)/(sum.0cos/n))
showit: procedure expose showDig; numeric digits showDig; parse arg a,mA
return left('angles='a,30) 'mean angle=' format(mA,,showDig,0)/1
::requires rxMath library; |
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
| #Excel | Excel |
=MEDIAN(A1:A10)
|
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
| #F.23 | F# |
let rec splitToFives list =
match list with
| a::b::c::d::e::tail ->
([a;b;c;d;e])::(splitToFives tail)
| [] -> []
| _ ->
let left = 5 - List.length (list)
let last = List.append list (List.init left (fun _ -> System.Double.PositiveInfinity) )
in [last]
let medianFromFives =
List.map ( fun (i:float list) ->
List.nth (List.sort i) 2 )
let start l =
let rec magicFives list k =
if List.length(list) <= 10 then
List.nth (List.sort list) (k-1)
else
let s = splitToFives list
let M = medianFromFives s
let m = magicFives M (int(System.Math.Ceiling((float(List.length M))/2.)))
let (ll,lg) = List.partition ( fun i -> i < m ) list
let (le,lg) = List.partition ( fun i -> i = m ) lg
in
if (List.length ll >= k) then
magicFives ll k
else if (List.length ll + List.length le >= k ) then m
else
magicFives lg (k-(List.length ll)-(List.length le))
in
let len = List.length l in
if (len % 2 = 1) then
magicFives l ((len+1)/2)
else
let a = magicFives l (len/2)
let b = magicFives l ((len/2)+1)
in (a+b)/2.
let z = [1.;5.;2.;8.;7.;2.]
start z
let z' = [1.;5.;2.;8.;7.]
start z'
|
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
| #jq | jq | def amean: add/length;
def logProduct: map(log) | add;
def gmean: (logProduct / length) | exp;
def hmean: length / (map(1/.) | add);
# Tasks:
[range(1;11) ] | [amean, gmean, hmean] as $ans
| ( $ans[],
"amean > gmean > hmean => \($ans[0] > $ans[1] and $ans[1] > $ans[2] )" )
|
http://rosettacode.org/wiki/Balanced_ternary | Balanced ternary | Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1.
Examples
Decimal 11 = 32 + 31 − 30, thus it can be written as "++−"
Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0"
Task
Implement balanced ternary representation of integers with the following:
Support arbitrarily large integers, both positive and negative;
Provide ways to convert to and from text strings, using digits '+', '-' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5).
Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type is balanced ternary). If your native integers can't support arbitrary length, overflows during conversion must be indicated.
Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do not convert to native integers first.
Make your implementation efficient, with a reasonable definition of "efficient" (and with a reasonable definition of "reasonable").
Test case With balanced ternaries a from string "+-0++0+", b from native integer -436, c "+-++-":
write out a, b and c in decimal notation;
calculate a × (b − c), write out the result in both ternary and decimal notations.
Note: The pages generalised floating point addition and generalised floating point multiplication have code implementing arbitrary precision floating point balanced ternary.
| #Python | Python | class BalancedTernary:
# Represented as a list of 0, 1 or -1s, with least significant digit first.
str2dig = {'+': 1, '-': -1, '0': 0} # immutable
dig2str = {1: '+', -1: '-', 0: '0'} # immutable
table = ((0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)) # immutable
def __init__(self, inp):
if isinstance(inp, str):
self.digits = [BalancedTernary.str2dig[c] for c in reversed(inp)]
elif isinstance(inp, int):
self.digits = self._int2ternary(inp)
elif isinstance(inp, BalancedTernary):
self.digits = list(inp.digits)
elif isinstance(inp, list):
if all(d in (0, 1, -1) for d in inp):
self.digits = list(inp)
else:
raise ValueError("BalancedTernary: Wrong input digits.")
else:
raise TypeError("BalancedTernary: Wrong constructor input.")
@staticmethod
def _int2ternary(n):
if n == 0: return []
if (n % 3) == 0: return [0] + BalancedTernary._int2ternary(n // 3)
if (n % 3) == 1: return [1] + BalancedTernary._int2ternary(n // 3)
if (n % 3) == 2: return [-1] + BalancedTernary._int2ternary((n + 1) // 3)
def to_int(self):
return reduce(lambda y,x: x + 3 * y, reversed(self.digits), 0)
def __repr__(self):
if not self.digits: return "0"
return "".join(BalancedTernary.dig2str[d] for d in reversed(self.digits))
@staticmethod
def _neg(digs):
return [-d for d in digs]
def __neg__(self):
return BalancedTernary(BalancedTernary._neg(self.digits))
@staticmethod
def _add(a, b, c=0):
if not (a and b):
if c == 0:
return a or b
else:
return BalancedTernary._add([c], a or b)
else:
(d, c) = BalancedTernary.table[3 + (a[0] if a else 0) + (b[0] if b else 0) + c]
res = BalancedTernary._add(a[1:], b[1:], c)
# trim leading zeros
if res or d != 0:
return [d] + res
else:
return res
def __add__(self, b):
return BalancedTernary(BalancedTernary._add(self.digits, b.digits))
def __sub__(self, b):
return self + (-b)
@staticmethod
def _mul(a, b):
if not (a and b):
return []
else:
if a[0] == -1: x = BalancedTernary._neg(b)
elif a[0] == 0: x = []
elif a[0] == 1: x = b
else: assert False
y = [0] + BalancedTernary._mul(a[1:], b)
return BalancedTernary._add(x, y)
def __mul__(self, b):
return BalancedTernary(BalancedTernary._mul(self.digits, b.digits))
def main():
a = BalancedTernary("+-0++0+")
print "a:", a.to_int(), a
b = BalancedTernary(-436)
print "b:", b.to_int(), b
c = BalancedTernary("+-++-")
print "c:", c.to_int(), c
r = a * (b - c)
print "a * (b - c):", r.to_int(), r
main() |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #Red | Red | Red []
number: 510 ;; starting number
;; repeat, until the last condition in the block is true
until [
number: number + 2 ;; only even numbers can have even squares
;; The word modulo computes the non-negative remainder of the
;; first argument divided by the second argument.
;; ** => Returns a number raised to a given power (exponent)
269696 = modulo (number ** 2) 1000000
]
?? number
|
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #REXX | REXX | /*REXX program finds the lowest (positive) integer whose square ends in 269,696. */
do j=2 by 2 until right(j * j, 6) == 269696 /*start J at two, increment by two. */
end /*◄── signifies the end of the DO loop.*/
/* [↑] * means multiplication. */
say "The smallest integer whose square ends in 269,696 is: " j |
http://rosettacode.org/wiki/Approximate_equality | Approximate equality | Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the
difference in floating point calculations between different language implementations becomes significant.
For example, a difference between 32 bit and 64 bit floating point calculations may appear by
about the 8th significant digit in base 10 arithmetic.
Task
Create a function which returns true if two floating point numbers are approximately equal.
The function should allow for differences in the magnitude of numbers, so that, for example,
100000000000000.01 may be approximately equal to 100000000000000.011,
even though 100.01 is not approximately equal to 100.011.
If the language has such a feature in its standard library, this may be used instead of a custom function.
Show the function results with comparisons on the following pairs of values:
100000000000000.01, 100000000000000.011 (note: should return true)
100.01, 100.011 (note: should return false)
10000000000000.001 / 10000.0, 1000000000.0000001000
0.001, 0.0010000001
0.000000000000000000000101, 0.0
sqrt(2) * sqrt(2), 2.0
-sqrt(2) * sqrt(2), -2.0
3.14159265358979323846, 3.14159265358979324
Answers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.
| #Perl | Perl | use strict;
use warnings;
sub is_close {
my($a,$b,$eps) = @_;
$eps //= 15;
my $epse = $eps;
$epse++ if sprintf("%.${eps}f",$a) =~ /\./;
$epse++ if sprintf("%.${eps}f",$a) =~ /\-/;
my $afmt = substr((sprintf "%.${eps}f", $a), 0, $epse);
my $bfmt = substr((sprintf "%.${eps}f", $b), 0, $epse);
printf "%-5s %s ≅ %s\n", ($afmt eq $bfmt ? 'True' : 'False'), $afmt, $bfmt;
}
for (
[100000000000000.01, 100000000000000.011],
[100.01, 100.011],
[10000000000000.001 / 10000.0, 1000000000.0000001000],
[0.001, 0.0010000001],
[0.000000000000000000000101, 0.0],
[sqrt(2) * sqrt(2), 2.0],
[-sqrt(2) * sqrt(2), -2.0],
[100000000000000003.0, 100000000000000004.0],
[3.14159265358979323846, 3.14159265358979324]
) {
my($a,$b) = @$_;
is_close($a,$b);
}
print "\nTolerance may be adjusted.\n";
my $real_pi = 2 * atan2(1, 0);
my $roman_pi = 22/7;
is_close($real_pi,$roman_pi,$_) for <10 3>; |
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
| #D | D | import std.stdio, std.algorithm, std.random, std.range;
void main() {
foreach (immutable i; 1 .. 9) {
immutable s = iota(i * 2).map!(_ => "[]"[uniform(0, 2)]).array;
writeln(s.balancedParens('[', ']') ? " OK: " : "bad: ", s);
}
} |
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.
| #Elixir | Elixir |
defmodule Gecos do
defstruct [:fullname, :office, :extension, :homephone, :email]
defimpl String.Chars do
def to_string(gecos) do
[:fullname, :office, :extension, :homephone, :email]
|> Enum.map_join(",", &Map.get(gecos, &1))
end
end
end
defmodule Passwd do
defstruct [:account, :password, :uid, :gid, :gecos, :directory, :shell]
defimpl String.Chars do
def to_string(passwd) do
[:account, :password, :uid, :gid, :gecos, :directory, :shell]
|> Enum.map_join(":", &Map.get(passwd, &1))
end
end
end
defmodule Appender do
def write(filename) do
jsmith = %Passwd{
account: "jsmith",
password: "x",
uid: 1001,
gid: 1000,
gecos: %Gecos{
fullname: "Joe Smith",
office: "Room 1007",
extension: "(234)555-8917",
homephone: "(234)555-0077",
email: "[email protected]"
},
directory: "/home/jsmith",
shell: "/bin/bash"
}
jdoe = %Passwd{
account: "jdoe",
password: "x",
uid: 1002,
gid: 1000,
gecos: %Gecos{
fullname: "Jane Doe",
office: "Room 1004",
extension: "(234)555-8914",
homephone: "(234)555-0044",
email: "[email protected]"
},
directory: "/home/jdoe",
shell: "/bin/bash"
}
xyz = %Passwd{
account: "xyz",
password: "x",
uid: 1003,
gid: 1000,
gecos: %Gecos{
fullname: "X Yz",
office: "Room 1003",
extension: "(234)555-8913",
homephone: "(234)555-0033",
email: "[email protected]"
},
directory: "/home/xyz",
shell: "/bin/bash"
}
File.open!(filename, [:write], fn file ->
IO.puts(file, jsmith)
IO.puts(file, jdoe)
end)
File.open!(filename, [:append], fn file ->
IO.puts(file, xyz)
end)
IO.puts File.read!(filename)
end
end
Appender.write("passwd.txt")
|
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.
| #Fortran | Fortran | PROGRAM DEMO !As per the described task, more or less.
TYPE DETAILS !Define a component.
CHARACTER*28 FULLNAME
CHARACTER*12 OFFICE
CHARACTER*16 EXTENSION
CHARACTER*16 HOMEPHONE
CHARACTER*88 EMAIL
END TYPE DETAILS
TYPE USERSTUFF !Define the desired data aggregate.
CHARACTER*8 ACCOUNT
CHARACTER*8 PASSWORD !Plain text!! Eeek!!!
INTEGER*2 UID
INTEGER*2 GID
TYPE(DETAILS) PERSON
CHARACTER*18 DIRECTORY
CHARACTER*12 SHELL
END TYPE USERSTUFF
TYPE(USERSTUFF) NOTE !After all that, I'll have one.
NAMELIST /STUFF/ NOTE !Enables free-format I/O, with names.
INTEGER F,MSG,N
MSG = 6 !Standard output.
F = 10 !Suitable for some arbitrary file.
OPEN(MSG, DELIM = "QUOTE") !Text variables are to be enquoted.
Create the file and supply its initial content.
OPEN (F, FILE="Staff.txt",STATUS="REPLACE",ACTION="WRITE",
1 DELIM="QUOTE",RECL=666) !Special parameters for the free-format WRITE working.
WRITE (F,*) USERSTUFF("jsmith","x",1001,1000,
1 DETAILS("Joe Smith","Room 1007","(234)555-8917",
2 "(234)555-0077","[email protected]"),
2 "/home/jsmith","/bin/bash")
WRITE (F,*) USERSTUFF("jdoe","x",1002,1000,
1 DETAILS("Jane Doe","Room 1004","(234)555-8914",
2 "(234)555-0044","[email protected]"),
3 "home/jdoe","/bin/bash")
CLOSE (F) !The file is now existing.
Choose the existing file, and append a further record to it.
OPEN (F, FILE="Staff.txt",STATUS="OLD",ACTION="WRITE",
1 DELIM="QUOTE",RECL=666,ACCESS="APPEND")
NOTE = USERSTUFF("xyz","x",1003,1000, !Create a new record's worth of stuff.
1 DETAILS("X Yz","Room 1003","(234)555-8193",
2 "(234)555-033","[email protected]"),
3 "/home/xyz","/bin/bash")
WRITE (F,*) NOTE !Append its content to the file.
CLOSE (F)
Chase through the file, revealing what had been written..
OPEN (F, FILE="Staff.txt",STATUS="OLD",ACTION="READ",
1 DELIM="QUOTE",RECL=666)
N = 0
10 READ (F,*,END = 20) NOTE !As it went out, so it comes in.
N = N + 1 !Another record read.
WRITE (MSG,11) N !Announce.
11 FORMAT (/,"Record ",I0) !Thus without quotes around the text part.
WRITE (MSG,STUFF) !Reveal.
GO TO 10 !Try again.
Closedown.
20 CLOSE (F)
END |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI or android 32 bits */
/* program hashmap.s */
/* */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
.equ MAXI, 10 @ size hashmap
.equ HEAPSIZE,20000
.equ LIMIT, 10 @ key characters number for compute index
.equ COEFF, 80 @ filling rate 80 = 80%
/*******************************************/
/* Structures */
/********************************************/
/* structure hashMap */
.struct 0
hash_count: // stored values counter
.struct hash_count + 4
hash_key: // key
.struct hash_key + (4 * MAXI)
hash_data: // data
.struct hash_data + (4 * MAXI)
hash_fin:
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessFin: .asciz "End program.\n"
szCarriageReturn: .asciz "\n"
szMessNoP: .asciz "Key not found !!!\n"
szKey1: .asciz "one"
szData1: .asciz "Ceret"
szKey2: .asciz "two"
szData2: .asciz "Maureillas"
szKey3: .asciz "three"
szData3: .asciz "Le Perthus"
szKey4: .asciz "four"
szData4: .asciz "Le Boulou"
.align 4
iptZoneHeap: .int sZoneHeap // start heap address
iptZoneHeapEnd: .int sZoneHeap + HEAPSIZE // end heap address
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
//sZoneConv: .skip 24
tbHashMap1: .skip hash_fin @ hashmap
sZoneHeap: .skip HEAPSIZE @ heap
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrtbHashMap1
bl hashInit @ init hashmap
ldr r0,iAdrtbHashMap1
ldr r1,iAdrszKey1 @ store key one
ldr r2,iAdrszData1
bl hashInsert
cmp r0,#0 @ error ?
bne 100f
ldr r0,iAdrtbHashMap1
ldr r1,iAdrszKey2 @ store key two
ldr r2,iAdrszData2
bl hashInsert
cmp r0,#0
bne 100f
ldr r0,iAdrtbHashMap1
ldr r1,iAdrszKey3 @ store key three
ldr r2,iAdrszData3
bl hashInsert
cmp r0,#0
bne 100f
ldr r0,iAdrtbHashMap1
ldr r1,iAdrszKey4 @ store key four
ldr r2,iAdrszData4
bl hashInsert
cmp r0,#0
bne 100f
ldr r0,iAdrtbHashMap1
ldr r1,iAdrszKey2 @ remove key two
bl hashRemoveKey
cmp r0,#0
bne 100f
ldr r0,iAdrtbHashMap1
ldr r1,iAdrszKey1 @ search key
bl searchKey
cmp r0,#-1
beq 1f
bl affichageMess
ldr r0,iAdrszCarriageReturn
bl affichageMess
b 2f
1:
ldr r0,iAdrszMessNoP
bl affichageMess
2:
ldr r0,iAdrtbHashMap1
ldr r1,iAdrszKey2
bl searchKey
cmp r0,#-1
beq 3f
bl affichageMess
ldr r0,iAdrszCarriageReturn
bl affichageMess
b 4f
3:
ldr r0,iAdrszMessNoP
bl affichageMess
4:
ldr r0,iAdrtbHashMap1
ldr r1,iAdrszKey4
bl searchKey
cmp r0,#-1
beq 5f
bl affichageMess
ldr r0,iAdrszCarriageReturn
bl affichageMess
b 6f
5:
ldr r0,iAdrszMessNoP
bl affichageMess
6:
ldr r0,iAdrszMessFin
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrszMessFin: .int szMessFin
iAdrtbHashMap1: .int tbHashMap1
iAdrszKey1: .int szKey1
iAdrszData1: .int szData1
iAdrszKey2: .int szKey2
iAdrszData2: .int szData2
iAdrszKey3: .int szKey3
iAdrszData3: .int szData3
iAdrszKey4: .int szKey4
iAdrszData4: .int szData4
iAdrszMessNoP: .int szMessNoP
/***************************************************/
/* init hashMap */
/***************************************************/
// r0 contains address to hashMap
hashInit:
push {r1-r3,lr} @ save registers
mov r1,#0
mov r2,#0
str r2,[r0,#hash_count] @ init counter
add r0,r0,#hash_key @ start zone key/value
1:
lsl r3,r1,#3
add r3,r3,r0
str r2,[r3,#hash_key]
str r2,[r3,#hash_data]
add r1,r1,#1
cmp r1,#MAXI
blt 1b
100:
pop {r1-r3,pc} @ restaur registers
/***************************************************/
/* insert key/datas */
/***************************************************/
// r0 contains address to hashMap
// r1 contains address to key
// r2 contains address to datas
hashInsert:
push {r1-r8,lr} @ save registers
mov r6,r0 @ save address
bl hashIndex @ search void key or identical key
cmp r0,#0 @ error ?
blt 100f
ldr r3,iAdriptZoneHeap
ldr r3,[r3]
ldr r8,iAdriptZoneHeapEnd
ldr r8,[r8]
sub r8,r8,#50
lsl r0,r0,#2 @ 4 bytes
add r7,r6,#hash_key @ start zone key/value
ldr r4,[r7,r0]
cmp r4,#0 @ key already stored ?
bne 1f
ldr r4,[r6,#hash_count] @ no -> increment counter
add r4,r4,#1
cmp r4,#(MAXI * COEFF / 100)
bge 98f
str r4,[r6,#hash_count]
1:
str r3,[r7,r0]
mov r4,#0
2: @ copy key loop in heap
ldrb r5,[r1,r4]
strb r5,[r3,r4]
cmp r5,#0
add r4,r4,#1
bne 2b
add r3,r3,r4
cmp r3,r8
bge 99f
add r7,r6,#hash_data
str r3,[r7,r0]
mov r4,#0
3: @ copy data loop in heap
ldrb r5,[r2,r4]
strb r5,[r3,r4]
cmp r5,#0
add r4,r4,#1
bne 3b
add r3,r3,r4
cmp r3,r8
bge 99f
ldr r0,iAdriptZoneHeap
str r3,[r0] @ new heap address
mov r0,#0 @ insertion OK
b 100f
98: @ error hashmap
adr r0,szMessErrInd
bl affichageMess
mov r0,#-1
b 100f
99: @ error heap
adr r0,szMessErrHeap
bl affichageMess
mov r0,#-1
100:
pop {r1-r8,lr} @ restaur registers
bx lr @ return
szMessErrInd: .asciz "Error : HashMap size Filling rate Maxi !!\n"
szMessErrHeap: .asciz "Error : Heap size Maxi !!\n"
.align 4
iAdriptZoneHeap: .int iptZoneHeap
iAdriptZoneHeapEnd: .int iptZoneHeapEnd
/***************************************************/
/* search void index in hashmap */
/***************************************************/
// r0 contains hashMap address
// r1 contains key address
hashIndex:
push {r1-r4,lr} @ save registers
add r4,r0,#hash_key
mov r2,#0 @ index
mov r3,#0 @ characters sum
1: @ loop to compute characters sum
ldrb r0,[r1,r2]
cmp r0,#0 @ string end ?
beq 2f
add r3,r3,r0 @ add to sum
add r2,r2,#1
cmp r2,#LIMIT
blt 1b
2:
mov r5,r1 @ save key address
mov r0,r3
mov r1,#MAXI
bl division @ compute remainder -> r3
mov r1,r5 @ key address
3:
ldr r0,[r4,r3,lsl #2] @ loak key for computed index
cmp r0,#0 @ void key ?
beq 4f
bl comparStrings @ identical key ?
cmp r0,#0
beq 4f @ yes
add r3,r3,#1 @ no search next void key
cmp r3,#MAXI @ maxi ?
movge r3,#0 @ restart to index 0
b 3b
4:
mov r0,r3 @ return index void array or key equal
100:
pop {r1-r4,pc} @ restaur registers
/***************************************************/
/* search key in hashmap */
/***************************************************/
// r0 contains hash map address
// r1 contains key address
searchKey:
push {r1-r2,lr} @ save registers
mov r2,r0
bl hashIndex
lsl r0,r0,#2
add r1,r0,#hash_key
ldr r1,[r2,r1]
cmp r1,#0
moveq r0,#-1
beq 100f
add r1,r0,#hash_data
ldr r0,[r2,r1]
100:
pop {r1-r2,pc} @ restaur registers
/***************************************************/
/* remove key in hashmap */
/***************************************************/
// r0 contains hash map address
// r1 contains key address
hashRemoveKey: @ INFO: hashRemoveKey
push {r1-r3,lr} @ save registers
mov r2,r0
bl hashIndex
lsl r0,r0,#2
add r1,r0,#hash_key
ldr r3,[r2,r1]
cmp r3,#0
beq 2f
add r3,r2,r1
mov r1,#0 @ raz key address
str r1,[r3]
add r1,r0,#hash_data
add r3,r2,r1
mov r1,#0
str r1,[r3] @ raz datas address
mov r0,#0
b 100f
2:
adr r0,szMessErrRemove
bl affichageMess
mov r0,#-1
100:
pop {r1-r3,pc} @ restaur registers
szMessErrRemove: .asciz "\033[31mError remove key !!\033[0m\n"
.align 4
/************************************/
/* Strings case sensitive comparisons */
/************************************/
/* r0 et r1 contains the address of strings */
/* return 0 in r0 if equals */
/* return -1 if string r0 < string r1 */
/* return 1 if string r0 > string r1 */
comparStrings:
push {r1-r4} @ save des registres
mov r2,#0 @ characters counter
1:
ldrb r3,[r0,r2] @ byte string 1
ldrb r4,[r1,r2] @ byte string 2
cmp r3,r4
movlt r0,#-1 @ smaller
movgt r0,#1 @ greather
bne 100f @ not equals
cmp r3,#0 @ 0 end string ?
moveq r0,#0 @ equals
beq 100f @ end string
add r2,r2,#1 @ else add 1 in counter
b 1b @ and loop
100:
pop {r1-r4}
bx lr
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
|
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
| #BCPL | BCPL | get "libhdr"
manifest $( LIMIT = 20 $)
let nfactors(n) =
n < 2 -> 1, valof
$( let c = 2
for i=2 to n/2
if n rem i = 0 then c := c + 1
resultis c
$)
let start() be
$( let max = 0 and seen = 0 and n = 1
while seen < LIMIT
$( let f = nfactors(n)
if f > max
$( writef("%N ",n)
max := f
seen := seen + 1
$)
n := n + 1
$)
wrch('*N')
$) |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #C | C | #include <stdio.h>
int countDivisors(int n) {
int i, count;
if (n < 2) return 1;
count = 2; // 1 and n
for (i = 2; i <= n/2; ++i) {
if (n%i == 0) ++count;
}
return count;
}
int main() {
int n, d, maxDiv = 0, count = 0;
printf("The first 20 anti-primes are:\n");
for (n = 1; count < 20; ++n) {
d = countDivisors(n);
if (d > maxDiv) {
printf("%d ", n);
maxDiv = d;
count++;
}
}
printf("\n");
return 0;
} |
http://rosettacode.org/wiki/Atomic_updates | Atomic updates |
Task
Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to:
get the current value of any bucket
remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the transferred amount to ensure the values remain non-negative
In order to exercise this data type, create one set of buckets, and start three concurrent tasks:
As often as possible, pick two buckets and make their values closer to equal.
As often as possible, pick two buckets and arbitrarily redistribute their values.
At whatever rate is convenient, display (by any means) the total value and, optionally, the individual values of each bucket.
The display task need not be explicit; use of e.g. a debugger or trace tool is acceptable provided it is simple to set up to provide the display.
This task is intended as an exercise in atomic operations. The sum of the bucket values must be preserved even if the two tasks attempt to perform transfers simultaneously, and a straightforward solution is to ensure that at any time, only one transfer is actually occurring — that the transfer operation is atomic.
| #Julia | Julia | using StatsBase
function runall()
nbuckets = 16
unfinish = true
spinner = ReentrantLock()
buckets = rand(1:99, nbuckets)
totaltrans = 0
bucketsum() = sum(buckets)
smallpause() = sleep(rand() / 2000)
picktwo() = (samplepair(nbuckets)...)
function equalizer()
while unfinish
smallpause()
if trylock(spinner)
i, j = picktwo()
sm = buckets[i] + buckets[j]
m = fld(sm + 1, 2)
buckets[i], buckets[j] = m, sm - m
totaltrans += 1
unlock(spinner)
end
end
end
function redistributor()
while unfinish
smallpause()
if trylock(spinner)
i, j = picktwo()
sm = buckets[i] + buckets[j]
buckets[i] = rand(0:sm)
buckets[j] = sm - buckets[i]
totaltrans += 1
unlock(spinner)
end
end
end
function accountant()
count = 0
while count < 16
smallpause()
if trylock(spinner)
println("Current state of buckets: $buckets. Total in buckets: $(bucketsum())")
unlock(spinner)
count += 1
sleep(1)
end
end
unfinish = false
end
t = time()
@async equalizer()
@async redistributor()
@async accountant()
while unfinish sleep(0.25) end
println("Total transactions: $totaltrans ($(round(Int, totaltrans / (time() - t))) unlocks per second).")
end
runall() |
http://rosettacode.org/wiki/Atomic_updates | Atomic updates |
Task
Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to:
get the current value of any bucket
remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the transferred amount to ensure the values remain non-negative
In order to exercise this data type, create one set of buckets, and start three concurrent tasks:
As often as possible, pick two buckets and make their values closer to equal.
As often as possible, pick two buckets and arbitrarily redistribute their values.
At whatever rate is convenient, display (by any means) the total value and, optionally, the individual values of each bucket.
The display task need not be explicit; use of e.g. a debugger or trace tool is acceptable provided it is simple to set up to provide the display.
This task is intended as an exercise in atomic operations. The sum of the bucket values must be preserved even if the two tasks attempt to perform transfers simultaneously, and a straightforward solution is to ensure that at any time, only one transfer is actually occurring — that the transfer operation is atomic.
| #Kotlin | Kotlin | // version 1.2.0
import java.util.concurrent.ThreadLocalRandom
import kotlin.concurrent.thread
const val NUM_BUCKETS = 10
class Buckets(data: IntArray) {
private val data = data.copyOf()
operator fun get(index: Int) = synchronized(data) { data[index] }
fun transfer(srcIndex: Int, dstIndex: Int, amount: Int): Int {
if (amount < 0) {
throw IllegalArgumentException("Negative amount: $amount")
}
if (amount == 0) return 0
synchronized(data) {
var a = amount
if (data[srcIndex] - a < 0) a = data[srcIndex]
if (data[dstIndex] + a < 0) a = Int.MAX_VALUE - data[dstIndex]
if (a < 0) throw IllegalStateException()
data[srcIndex] -= a
data[dstIndex] += a
return a
}
}
val buckets get() = synchronized(data) { data.copyOf() }
fun transferRandomAmount() {
val rnd = ThreadLocalRandom.current()
while (true) {
val srcIndex = rnd.nextInt(NUM_BUCKETS)
val dstIndex = rnd.nextInt(NUM_BUCKETS)
val amount = rnd.nextInt() and Int.MAX_VALUE
transfer(srcIndex, dstIndex, amount)
}
}
fun equalize() {
val rnd = ThreadLocalRandom.current()
while (true) {
val srcIndex = rnd.nextInt(NUM_BUCKETS)
val dstIndex = rnd.nextInt(NUM_BUCKETS)
val amount = (this[srcIndex] - this[dstIndex]) / 2
if (amount >= 0) transfer(srcIndex, dstIndex, amount)
}
}
fun print() {
while (true) {
val nextPrintTime = System.currentTimeMillis() + 3000
while (true) {
val now = System.currentTimeMillis()
if (now >= nextPrintTime) break
try {
Thread.sleep(nextPrintTime - now)
}
catch (e: InterruptedException) {
return
}
}
val bucketValues = buckets
println("Current values: ${bucketValues.total} ${bucketValues.asList()}")
}
}
}
val IntArray.total: Long get() {
var sum = 0L
for (d in this) sum += d
return sum
}
fun main(args: Array<String>) {
val rnd = ThreadLocalRandom.current()
val values = IntArray(NUM_BUCKETS) { rnd.nextInt() and Int.MAX_VALUE }
println("Initial array: ${values.total} ${values.asList()}")
val buckets = Buckets(values)
thread(name = "equalizer") { buckets.equalize() }
thread(name = "transferrer") { buckets.transferRandomAmount() }
thread(name = "printer") { buckets.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.
| #Haskell | Haskell | import Control.Exception
main = let a = someValue in
assert (a == 42) -- throws AssertionFailed when a is not 42
somethingElse -- what to return when a is 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.
| #Icon_and_Unicon | Icon and Unicon | ...
runerr(n,( expression ,"Assertion/error - message.")) # Throw (and possibly trap) an error number n if expression succeeds.
...
stop(( expression ,"Assertion/stop - message.")) # Terminate program if expression succeeds.
... |
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.
| #J | J | assert n = 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.
| #Bracmat | Bracmat | ( ( callbackFunction1
= location value
. !arg:(?location,?value)
& out$(str$(array[ !location "] = " !!value))
)
& ( callbackFunction2
= location value
. !arg:(?location,?value)
& !!value^2:?!value
)
& ( mapar
= arr len callback i
. !arg:(?arr,?len,?callback)
& 0:?i
& whl
' ( !i:<!len
& !callback$(!i,!i$!arr)
& 1+!i:?i
)
)
& tbl$(array,4)
& 1:?(0$array)
& 2:?(1$array)
& 3:?(2$array)
& 4:?(3$array)
& mapar$(array,4,callbackFunction1)
& mapar$(array,4,callbackFunction2)
& mapar$(array,4,callbackFunction1)
); |
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.
| #Brat | Brat | #Print out each element in array
[:a :b :c :d :e].each { element |
p element
} |
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
| #Objective-C | Objective-C | #import <Foundation/Foundation.h>
@interface NSArray (Mode)
- (NSArray *)mode;
@end
@implementation NSArray (Mode)
- (NSArray *)mode {
NSCountedSet *seen = [NSCountedSet setWithArray:self];
int max = 0;
NSMutableArray *maxElems = [NSMutableArray array];
for ( obj in seen ) {
int count = [seen countForObject:obj];
if (count > max) {
max = count;
[maxElems removeAllObjects];
[maxElems addObject:obj];
} else if (count == max) {
[maxElems addObject:obj];
}
}
return maxElems;
}
@end |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked 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
| #Clojure | Clojure |
(doseq [[k v] {:a 1, :b 2, :c 3}]
(println k "=" v))
(doseq [k (keys {:a 1, :b 2, :c 3})]
(println k))
(doseq [v (vals {:a 1, :b 2, :c 3})]
(println v))
|
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
| #CoffeeScript | CoffeeScript | hash =
a: 'one'
b: 'two'
for key, value of hash
console.log key, value
for key of hash
console.log key
|
http://rosettacode.org/wiki/Apply_a_digital_filter_(direct_form_II_transposed) | Apply a digital filter (direct form II transposed) | Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [1]
Task
Filter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667]
The signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]
| #Julia | Julia | function DF2TFilter(a::Vector, b::Vector, sig::Vector)
rst = zeros(sig)
for i in eachindex(sig)
tmp = sum(b[j] * sig[i-j+1] for j in 1:min(i, length(b)))
tmp -= sum(a[j] * rst[i-j+1] for j in 1:min(i, length(a)))
rst[i] = tmp / a[1]
end
return rst
end
acoef = [1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17]
bcoef = [0.16666667, 0.5, 0.5, 0.16666667]
signal = [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412,
-0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044,
0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195,
0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293,
0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]
@show DF2TFilter(acoef, bcoef, signal) |
http://rosettacode.org/wiki/Apply_a_digital_filter_(direct_form_II_transposed) | Apply a digital filter (direct form II transposed) | Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [1]
Task
Filter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667]
The signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]
| #Kotlin | Kotlin | // version 1.1.3
fun filter(a: DoubleArray, b: DoubleArray, signal: DoubleArray): DoubleArray {
val result = DoubleArray(signal.size)
for (i in 0 until signal.size) {
var tmp = 0.0
for (j in 0 until b.size) {
if (i - j < 0) continue
tmp += b[j] * signal[i - j]
}
for (j in 1 until a.size) {
if (i - j < 0) continue
tmp -= a[j] * result[i - j]
}
tmp /= a[0]
result[i] = tmp
}
return result
}
fun main(args: Array<String>) {
val a = doubleArrayOf(1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17)
val b = doubleArrayOf(0.16666667, 0.5, 0.5, 0.16666667)
val signal = doubleArrayOf(
-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412,
-0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044,
0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195,
0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293,
0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589
)
val result = filter(a, b, signal)
for (i in 0 until result.size) {
print("% .8f".format(result[i]))
print(if ((i + 1) % 5 != 0) ", " else "\n")
}
} |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Dart | Dart | num mean(List<num> l) => l.reduce((num p, num n) => p + n) / l.length;
void main(){
print(mean([1,2,3,4,5,6,7]));
} |
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
| #dc | dc | 1 2 3 5 7 zsn1k[+z1<+]ds+xln/p
3.6 |
http://rosettacode.org/wiki/Associative_array/Merging | Associative array/Merging | Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:
Key
Value
"name"
"Rocket Skates"
"price"
15.25
"color"
"red"
"year"
1974
| #Ring | Ring |
load "stdlib.ring"
list1 = [:name = "Rocket Skates", :price = 12.75, :color = "yellow"]
list2 = [:price = 15.25, :color = "red", :year = 1974]
for n = 1 to len(list2)
flag = 0
for m = 1 to len(list1)
if list2[n][1] = list1[m][1]
flag = 1
del(list1,m)
add(list1,[list2[n][1],list2[n][2]])
exit
ok
next
if flag = 0
add(list1,[list2[n][1],list2[n][2]])
ok
next
for n = 1 to len(list1)
see list1[n][1] + " = " + list1[n][2] + nl
next
|
http://rosettacode.org/wiki/Associative_array/Merging | Associative array/Merging | Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:
Key
Value
"name"
"Rocket Skates"
"price"
15.25
"color"
"red"
"year"
1974
| #Ruby | Ruby | base = {"name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"}
update = {"price" => 15.25, "color" => "red", "year" => 1974}
result = base.merge(update)
p result |
http://rosettacode.org/wiki/Associative_array/Merging | Associative array/Merging | Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:
Key
Value
"name"
"Rocket Skates"
"price"
15.25
"color"
"red"
"year"
1974
| #Rust | Rust | use std::collections::HashMap;
fn main() {
let mut original = HashMap::new();
original.insert("name", "Rocket Skates");
original.insert("price", "12.75");
original.insert("color", "yellow");
let mut update = HashMap::new();
update.insert("price", "15.25");
update.insert("color", "red");
update.insert("year", "1974");
original.extend(&update);
println!("{:#?}", original);
}
|
http://rosettacode.org/wiki/Associative_array/Merging | Associative array/Merging | Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:
Key
Value
"name"
"Rocket Skates"
"price"
15.25
"color"
"red"
"year"
1974
| #Scheme | Scheme | ; Merge alists by appending the update list onto the front of the base list.
; (The extra '() is so that append doesn't co-opt the second list.)
(define append-alists
(lambda (base update)
(append update base '())))
; Test...
(printf "~%Merge using append procedure...~%")
; The original base and update alists.
(let ((base '(("name" . "Rocket Skates") ("price" . 12.75) ("color" . "yellow" )))
(update '(("price" . 15.25) ("color" . "red") ("year" . 1974))))
; Merge by appending the update list onto the front of the base list.
(let ((merged (append-alists base update)))
; Show that everything worked.
(printf "Merged alist:~%~s~%" merged)
(printf "Values from merged alist:~%")
(let loop ((keys '("name" "price" "color" "year")))
(unless (null? keys)
(printf "~s -> ~s~%" (car keys) (cdr (assoc (car keys) merged)))
(loop (cdr keys)))))) |
http://rosettacode.org/wiki/Average_loop_length | Average loop length | Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence.
Task
Write a program or a script that estimates, for each N, the average length until the first such repetition.
Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.
This problem comes from the end of Donald Knuth's Christmas tree lecture 2011.
Example of expected output:
N average analytical (error)
=== ========= ============ =========
1 1.0000 1.0000 ( 0.00%)
2 1.4992 1.5000 ( 0.05%)
3 1.8784 1.8889 ( 0.56%)
4 2.2316 2.2188 ( 0.58%)
5 2.4982 2.5104 ( 0.49%)
6 2.7897 2.7747 ( 0.54%)
7 3.0153 3.0181 ( 0.09%)
8 3.2429 3.2450 ( 0.07%)
9 3.4536 3.4583 ( 0.14%)
10 3.6649 3.6602 ( 0.13%)
11 3.8091 3.8524 ( 1.12%)
12 3.9986 4.0361 ( 0.93%)
13 4.2074 4.2123 ( 0.12%)
14 4.3711 4.3820 ( 0.25%)
15 4.5275 4.5458 ( 0.40%)
16 4.6755 4.7043 ( 0.61%)
17 4.8877 4.8579 ( 0.61%)
18 4.9951 5.0071 ( 0.24%)
19 5.1312 5.1522 ( 0.41%)
20 5.2699 5.2936 ( 0.45%)
| #Racket | Racket |
#lang racket
(require (only-in math factorial))
(define (analytical n)
(for/sum ([i (in-range 1 (add1 n))])
(/ (factorial n) (expt n i) (factorial (- n i)))))
(define (test n times)
(define (count-times seen times)
(define x (random n))
(if (memq x seen) times (count-times (cons x seen) (add1 times))))
(/ (for/fold ([count 0]) ([i times]) (count-times '() count))
times))
(define (test-table max-n times)
(displayln " n avg theory error\n------------------------")
(for ([i (in-range 1 (add1 max-n))])
(define average (test i times))
(define theory (analytical i))
(define difference (* (abs (sub1 (/ average theory))) 100))
(displayln (~a (~a i #:width 2 #:align 'right)
" " (real->decimal-string average 4)
" " (real->decimal-string theory 4)
" " (real->decimal-string difference 4)
"%"))))
(test-table 20 10000)
|
http://rosettacode.org/wiki/Average_loop_length | Average loop length | Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence.
Task
Write a program or a script that estimates, for each N, the average length until the first such repetition.
Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.
This problem comes from the end of Donald Knuth's Christmas tree lecture 2011.
Example of expected output:
N average analytical (error)
=== ========= ============ =========
1 1.0000 1.0000 ( 0.00%)
2 1.4992 1.5000 ( 0.05%)
3 1.8784 1.8889 ( 0.56%)
4 2.2316 2.2188 ( 0.58%)
5 2.4982 2.5104 ( 0.49%)
6 2.7897 2.7747 ( 0.54%)
7 3.0153 3.0181 ( 0.09%)
8 3.2429 3.2450 ( 0.07%)
9 3.4536 3.4583 ( 0.14%)
10 3.6649 3.6602 ( 0.13%)
11 3.8091 3.8524 ( 1.12%)
12 3.9986 4.0361 ( 0.93%)
13 4.2074 4.2123 ( 0.12%)
14 4.3711 4.3820 ( 0.25%)
15 4.5275 4.5458 ( 0.40%)
16 4.6755 4.7043 ( 0.61%)
17 4.8877 4.8579 ( 0.61%)
18 4.9951 5.0071 ( 0.24%)
19 5.1312 5.1522 ( 0.41%)
20 5.2699 5.2936 ( 0.45%)
| #Raku | Raku | constant MAX_N = 20;
constant TRIALS = 100;
for 1 .. MAX_N -> $N {
my $empiric = TRIALS R/ [+] find-loop(random-mapping($N)).elems xx TRIALS;
my $theoric = [+]
map -> $k { $N ** ($k + 1) R/ [*] flat $k**2, $N - $k + 1 .. $N }, 1 .. $N;
FIRST say " N empiric theoric (error)";
FIRST say "=== ========= ============ =========";
printf "%3d %9.4f %12.4f (%4.2f%%)\n",
$N, $empiric,
$theoric, 100 * abs($theoric - $empiric) / $theoric;
}
sub random-mapping { hash .list Z=> .roll given ^$^size }
sub find-loop { 0, | %^mapping{*} ...^ { (%){$_}++ } } |
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period.
It can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA().
The word stateful in the task description refers to the need for SMA() to remember certain information between calls to it:
The period, P
An ordered container of at least the last P numbers from each of its individual calls.
Stateful also means that successive calls to I(), the initializer, should return separate routines that do not share saved state so they could be used on two independent streams of data.
Pseudo-code for an implementation of SMA is:
function SMA(number: N):
stateful integer: P
stateful list: stream
number: average
stream.append_last(N)
if stream.length() > P:
# Only average the last P elements of the stream
stream.delete_first()
if stream.length() == 0:
average = 0
else:
average = sum( stream.values() ) / stream.length()
return average
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 ((simple-moving-averager size . nums) num)
(set! nums (cons num (if (= (length nums) size) (reverse (cdr (reverse nums))) nums)))
(/ (apply + nums) (length nums)))
(define av (simple-moving-averager 3))
(map av '(1 2 3 4 5 5 4 3 2 1))
|
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.
| #Kotlin | Kotlin | // Version 1.3.21
const val MAX = 120
fun isPrime(n: Int) : Boolean {
if (n < 2) return false
if (n % 2 == 0) return n == 2
if (n % 3 == 0) return n == 3
var d : Int = 5
while (d * d <= n) {
if (n % d == 0) return false
d += 2
if (n % d == 0) return false
d += 4
}
return true
}
fun countPrimeFactors(n: Int) =
when {
n == 1 -> 0
isPrime(n) -> 1
else -> {
var nn = n
var count = 0
var f = 2
while (true) {
if (nn % f == 0) {
count++
nn /= f
if (nn == 1) break
if (isPrime(nn)) f = nn
} else if (f >= 3) {
f += 2
} else {
f = 3
}
}
count
}
}
fun main() {
println("The attractive numbers up to and including $MAX are:")
var count = 0
for (i in 1..MAX) {
val n = countPrimeFactors(i)
if (isPrime(n)) {
System.out.printf("%4d", i)
if (++count % 20 == 0) println()
}
}
println()
} |
http://rosettacode.org/wiki/Averages/Mean_time_of_day | Averages/Mean time of day | Task[edit]
A particular activity of bats occurs at these times of the day:
23:00:17, 23:40:20, 00:12:45, 00:17:19
Using the idea that there are twenty-four hours in a day,
which is analogous to there being 360 degrees in a circle,
map times of day to and from angles;
and using the ideas of Averages/Mean angle
compute and show the average time of the nocturnal activity
to an accuracy of one second of time.
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
| #Perl | Perl | use strict;
use warnings;
use POSIX 'fmod';
use Math::Complex;
use List::Util qw(sum);
use utf8;
use constant τ => 2 * 3.1415926535;
# time-of-day to radians
sub tod2rad {
($h,$m,$s) = split /:/, @_[0];
(3600*$h + 60*$m + $s) * τ / 86400;
}
# radians to time-of-day
sub rad2tod {
my $x = $_[0] * 86400 / τ;
sprintf '%02d:%02d:%02d', fm($x/3600,24), fm($x/60,60), fm($x,60);
}
# float modulus, normalized to positive values
sub fm {
my($n,$b) = @_;
$x = fmod($n,$b);
$x += $b if $x < 0;
}
sub phase { arg($_[0]) } # aka theta
sub cis { cos($_[0]) + i*sin($_[0]) }
sub mean_time { rad2tod phase sum map { cis tod2rad $_ } @_ }
@times = ("23:00:17", "23:40:20", "00:12:45", "00:17:19");
print mean_time(@times) . " is the mean time of " . join(' ', @times) . "\n"; |
http://rosettacode.org/wiki/AVL_tree | AVL tree |
This page uses content from Wikipedia. The original article was at AVL tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In computer science, an AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; at no time do they differ by more than one because rebalancing is done ensure this is the case. Lookup, insertion, and deletion all take O(log n) time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations. Note the tree of nodes comprise a set, so duplicate node keys are not allowed.
AVL trees are often compared with red-black trees because they support the same set of operations and because red-black trees also take O(log n) time for the basic operations. Because AVL trees are more rigidly balanced, they are faster than red-black trees for lookup-intensive applications. Similar to red-black trees, AVL trees are height-balanced, but in general not weight-balanced nor μ-balanced; that is, sibling nodes can have hugely differing numbers of descendants.
Task
Implement an AVL tree in the language of choice, and provide at least basic operations.
| #Rust | Rust | import scala.collection.mutable
class AVLTree[A](implicit val ordering: Ordering[A]) extends mutable.SortedSet[A] {
if (ordering eq null) throw new NullPointerException("ordering must not be null")
private var _root: AVLNode = _
private var _size = 0
override def size: Int = _size
override def foreach[U](f: A => U): Unit = {
val stack = mutable.Stack[AVLNode]()
var current = root
var done = false
while (!done) {
if (current != null) {
stack.push(current)
current = current.left
} else if (stack.nonEmpty) {
current = stack.pop()
f.apply(current.key)
current = current.right
} else {
done = true
}
}
}
def root: AVLNode = _root
override def isEmpty: Boolean = root == null
override def min[B >: A](implicit cmp: Ordering[B]): A = minNode().key
def minNode(): AVLNode = {
if (root == null) throw new UnsupportedOperationException("empty tree")
var node = root
while (node.left != null) node = node.left
node
}
override def max[B >: A](implicit cmp: Ordering[B]): A = maxNode().key
def maxNode(): AVLNode = {
if (root == null) throw new UnsupportedOperationException("empty tree")
var node = root
while (node.right != null) node = node.right
node
}
def next(node: AVLNode): Option[AVLNode] = {
var successor = node
if (successor != null) {
if (successor.right != null) {
successor = successor.right
while (successor != null && successor.left != null) {
successor = successor.left
}
} else {
successor = node.parent
var n = node
while (successor != null && successor.right == n) {
n = successor
successor = successor.parent
}
}
}
Option(successor)
}
def prev(node: AVLNode): Option[AVLNode] = {
var predecessor = node
if (predecessor != null) {
if (predecessor.left != null) {
predecessor = predecessor.left
while (predecessor != null && predecessor.right != null) {
predecessor = predecessor.right
}
} else {
predecessor = node.parent
var n = node
while (predecessor != null && predecessor.left == n) {
n = predecessor
predecessor = predecessor.parent
}
}
}
Option(predecessor)
}
override def rangeImpl(from: Option[A], until: Option[A]): mutable.SortedSet[A] = ???
override def +=(key: A): AVLTree.this.type = {
insert(key)
this
}
def insert(key: A): AVLNode = {
if (root == null) {
_root = new AVLNode(key)
_size += 1
return root
}
var node = root
var parent: AVLNode = null
var cmp = 0
while (node != null) {
parent = node
cmp = ordering.compare(key, node.key)
if (cmp == 0) return node // duplicate
node = node.matchNextChild(cmp)
}
val newNode = new AVLNode(key, parent)
if (cmp <= 0) parent._left = newNode
else parent._right = newNode
while (parent != null) {
cmp = ordering.compare(parent.key, key)
if (cmp < 0) parent.balanceFactor -= 1
else parent.balanceFactor += 1
parent = parent.balanceFactor match {
case -1 | 1 => parent.parent
case x if x < -1 =>
if (parent.right.balanceFactor == 1) rotateRight(parent.right)
val newRoot = rotateLeft(parent)
if (parent == root) _root = newRoot
null
case x if x > 1 =>
if (parent.left.balanceFactor == -1) rotateLeft(parent.left)
val newRoot = rotateRight(parent)
if (parent == root) _root = newRoot
null
case _ => null
}
}
_size += 1
newNode
}
override def -=(key: A): AVLTree.this.type = {
remove(key)
this
}
override def remove(key: A): Boolean = {
var node = findNode(key).orNull
if (node == null) return false
if (node.left != null) {
var max = node.left
while (max.left != null || max.right != null) {
while (max.right != null) max = max.right
node._key = max.key
if (max.left != null) {
node = max
max = max.left
}
}
node._key = max.key
node = max
}
if (node.right != null) {
var min = node.right
while (min.left != null || min.right != null) {
while (min.left != null) min = min.left
node._key = min.key
if (min.right != null) {
node = min
min = min.right
}
}
node._key = min.key
node = min
}
var current = node
var parent = node.parent
while (parent != null) {
parent.balanceFactor += (if (parent.left == current) -1 else 1)
current = parent.balanceFactor match {
case x if x < -1 =>
if (parent.right.balanceFactor == 1) rotateRight(parent.right)
val newRoot = rotateLeft(parent)
if (parent == root) _root = newRoot
newRoot
case x if x > 1 =>
if (parent.left.balanceFactor == -1) rotateLeft(parent.left)
val newRoot = rotateRight(parent)
if (parent == root) _root = newRoot
newRoot
case _ => parent
}
parent = current.balanceFactor match {
case -1 | 1 => null
case _ => current.parent
}
}
if (node.parent != null) {
if (node.parent.left == node) {
node.parent._left = null
} else {
node.parent._right = null
}
}
if (node == root) _root = null
_size -= 1
true
}
def findNode(key: A): Option[AVLNode] = {
var node = root
while (node != null) {
val cmp = ordering.compare(key, node.key)
if (cmp == 0) return Some(node)
node = node.matchNextChild(cmp)
}
None
}
private def rotateLeft(node: AVLNode): AVLNode = {
val rightNode = node.right
node._right = rightNode.left
if (node.right != null) node.right._parent = node
rightNode._parent = node.parent
if (rightNode.parent != null) {
if (rightNode.parent.left == node) {
rightNode.parent._left = rightNode
} else {
rightNode.parent._right = rightNode
}
}
node._parent = rightNode
rightNode._left = node
node.balanceFactor += 1
if (rightNode.balanceFactor < 0) {
node.balanceFactor -= rightNode.balanceFactor
}
rightNode.balanceFactor += 1
if (node.balanceFactor > 0) {
rightNode.balanceFactor += node.balanceFactor
}
rightNode
}
private def rotateRight(node: AVLNode): AVLNode = {
val leftNode = node.left
node._left = leftNode.right
if (node.left != null) node.left._parent = node
leftNode._parent = node.parent
if (leftNode.parent != null) {
if (leftNode.parent.left == node) {
leftNode.parent._left = leftNode
} else {
leftNode.parent._right = leftNode
}
}
node._parent = leftNode
leftNode._right = node
node.balanceFactor -= 1
if (leftNode.balanceFactor > 0) {
node.balanceFactor -= leftNode.balanceFactor
}
leftNode.balanceFactor -= 1
if (node.balanceFactor < 0) {
leftNode.balanceFactor += node.balanceFactor
}
leftNode
}
override def contains(elem: A): Boolean = findNode(elem).isDefined
override def iterator: Iterator[A] = ???
override def keysIteratorFrom(start: A): Iterator[A] = ???
class AVLNode private[AVLTree](k: A, p: AVLNode = null) {
private[AVLTree] var _key: A = k
private[AVLTree] var _parent: AVLNode = p
private[AVLTree] var _left: AVLNode = _
private[AVLTree] var _right: AVLNode = _
private[AVLTree] var balanceFactor: Int = 0
def parent: AVLNode = _parent
private[AVLTree] def selectNextChild(key: A): AVLNode = matchNextChild(ordering.compare(key, this.key))
def key: A = _key
private[AVLTree] def matchNextChild(cmp: Int): AVLNode = cmp match {
case x if x < 0 => left
case x if x > 0 => right
case _ => null
}
def left: AVLNode = _left
def right: AVLNode = _right
}
} |
http://rosettacode.org/wiki/Averages/Mean_angle | Averages/Mean angle | When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle.
If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the second was of 10 degrees then the average of the numbers is 180 degrees, whereas if you can note that 350 degrees is equivalent to -10 degrees and so you have two readings at 10 degrees either side of zero degrees leading to a more fitting mean angle of zero degrees.
To calculate the mean angle of several angles:
Assume all angles are on the unit circle and convert them to complex numbers expressed in real and imaginary form.
Compute the mean of the complex numbers.
Convert the complex mean to polar coordinates whereupon the phase of the complex mean is the required angular mean.
(Note that, since the mean is the sum divided by the number of numbers, and division by a positive real number does not affect the angle, you can also simply compute the sum for step 2.)
You can alternatively use this formula:
Given the angles
α
1
,
…
,
α
n
{\displaystyle \alpha _{1},\dots ,\alpha _{n}}
the mean is computed by
α
¯
=
atan2
(
1
n
⋅
∑
j
=
1
n
sin
α
j
,
1
n
⋅
∑
j
=
1
n
cos
α
j
)
{\displaystyle {\bar {\alpha }}=\operatorname {atan2} \left({\frac {1}{n}}\cdot \sum _{j=1}^{n}\sin \alpha _{j},{\frac {1}{n}}\cdot \sum _{j=1}^{n}\cos \alpha _{j}\right)}
Task[edit]
write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle.
(You should use a built-in function if you have one that does this for degrees or radians).
Use the function to compute the means of these lists of angles (in degrees):
[350, 10]
[90, 180, 270, 360]
[10, 20, 30]
Show your output here.
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 | meanAngle(v)=atan(sum(i=1,#v,sin(v[i]))/sum(i=1,#v,cos(v[i])))%(2*Pi)
meanDegrees(v)=meanAngle(v*Pi/180)*180/Pi
apply(meanDegrees,[[350, 10], [90, 180, 270, 360], [10, 20, 30]]) |
http://rosettacode.org/wiki/Averages/Mean_angle | Averages/Mean angle | When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle.
If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the second was of 10 degrees then the average of the numbers is 180 degrees, whereas if you can note that 350 degrees is equivalent to -10 degrees and so you have two readings at 10 degrees either side of zero degrees leading to a more fitting mean angle of zero degrees.
To calculate the mean angle of several angles:
Assume all angles are on the unit circle and convert them to complex numbers expressed in real and imaginary form.
Compute the mean of the complex numbers.
Convert the complex mean to polar coordinates whereupon the phase of the complex mean is the required angular mean.
(Note that, since the mean is the sum divided by the number of numbers, and division by a positive real number does not affect the angle, you can also simply compute the sum for step 2.)
You can alternatively use this formula:
Given the angles
α
1
,
…
,
α
n
{\displaystyle \alpha _{1},\dots ,\alpha _{n}}
the mean is computed by
α
¯
=
atan2
(
1
n
⋅
∑
j
=
1
n
sin
α
j
,
1
n
⋅
∑
j
=
1
n
cos
α
j
)
{\displaystyle {\bar {\alpha }}=\operatorname {atan2} \left({\frac {1}{n}}\cdot \sum _{j=1}^{n}\sin \alpha _{j},{\frac {1}{n}}\cdot \sum _{j=1}^{n}\cos \alpha _{j}\right)}
Task[edit]
write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle.
(You should use a built-in function if you have one that does this for degrees or radians).
Use the function to compute the means of these lists of angles (in degrees):
[350, 10]
[90, 180, 270, 360]
[10, 20, 30]
Show your output here.
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 | program MeanAngle;
{$IFDEF DELPHI}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
math;// sincos and atan2
type
tAngles = array of double;
function MeanAngle(const a:tAngles;cnt:longInt):double;
// calculates mean angle.
// returns 0.0 if direction is not sure.
const
eps = 1e-10;
var
i : LongInt;
s,c,
Sumsin,SumCos : extended;
begin
IF cnt = 0 then
Begin
MeanAngle := 0.0;
EXIT;
end;
SumSin:= 0;
SumCos:= 0;
For i := Cnt-1 downto 0 do
Begin
sincos(DegToRad(a[i]),s,c);
Sumsin := sumSin+s;
SumCos := sumCos+c;
end;
s := SumSin/cnt;
c := sumCos/cnt;
IF c > eps then
MeanAngle := RadToDeg(arctan2(s,c))
else
// Not meaningful
MeanAngle := 0.0;
end;
Procedure OutMeanAngle(const a:tAngles;cnt:longInt);
var
i : longInt;
Begin
IF cnt > 0 then
Begin
write('The mean angle of [');
For i := 0 to Cnt-2 do
write(a[i]:0:2,',');
write(a[Cnt-1]:0:2,'] => ');
writeln(MeanAngle(a,cnt):0:16);
end;
end;
var
a:tAngles;
Begin
setlength(a,4);
a[0] := 350;a[1] := 10;
OutMeanAngle(a,2);
a[0] := 90;a[1] := 180;a[2] := 270;a[3] := 360;
OutMeanAngle(a,4);
a[0] := 10;a[1] := 20;a[2] := 30;
OutMeanAngle(a,3);
setlength(a,0);
end. |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches 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
| #Factor | Factor | USING: arrays kernel locals math math.functions random sequences ;
IN: median
: pivot ( seq -- pivot ) random ;
: split ( seq pivot -- {lt,eq,gt} )
[ [ < ] curry partition ] keep
[ = ] curry partition
3array ;
DEFER: nth-in-order
:: nth-in-order-recur ( seq ind -- elt )
seq dup pivot split
dup [ length ] map 0 [ + ] accumulate nip
dup [ ind <= [ 1 ] [ 0 ] if ] map sum 1 -
[ swap nth ] curry bi@
ind swap -
nth-in-order ;
: nth-in-order ( seq ind -- elt )
dup 0 =
[ drop first ]
[ nth-in-order-recur ]
if ;
: median ( seq -- median )
dup length 1 - 2 / floor nth-in-order ; |
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
| #Forth | Forth | -1 cells constant -cell
: cell- -cell + ;
defer lessthan ( a@ b@ -- ? ) ' < is lessthan
: mid ( l r -- mid ) over - 2/ -cell and + ;
: exch ( addr1 addr2 -- ) dup @ >r over @ swap ! r> swap ! ;
: part ( l r -- l r r2 l2 )
2dup mid @ >r ( r: pivot )
2dup begin
swap begin dup @ r@ lessthan while cell+ repeat
swap begin r@ over @ lessthan while cell- repeat
2dup <= if 2dup exch >r cell+ r> cell- then
2dup > until r> drop ;
0 value midpoint
: select ( l r -- )
begin 2dup < while
part
dup midpoint >= if nip nip ( l l2 ) else
over midpoint <= if drop rot drop swap ( r2 r ) else
2drop 2drop exit then then
repeat 2drop ;
: median ( array len -- m )
1- cells over + 2dup mid to midpoint
select midpoint @ ; |
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
| #Julia | Julia | amean(A) = sum(A)/length(A)
gmean(A) = prod(A)^(1/length(A))
hmean(A) = length(A)/sum(1./A) |
http://rosettacode.org/wiki/Balanced_ternary | Balanced ternary | Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1.
Examples
Decimal 11 = 32 + 31 − 30, thus it can be written as "++−"
Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0"
Task
Implement balanced ternary representation of integers with the following:
Support arbitrarily large integers, both positive and negative;
Provide ways to convert to and from text strings, using digits '+', '-' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5).
Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type is balanced ternary). If your native integers can't support arbitrary length, overflows during conversion must be indicated.
Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do not convert to native integers first.
Make your implementation efficient, with a reasonable definition of "efficient" (and with a reasonable definition of "reasonable").
Test case With balanced ternaries a from string "+-0++0+", b from native integer -436, c "+-++-":
write out a, b and c in decimal notation;
calculate a × (b − c), write out the result in both ternary and decimal notations.
Note: The pages generalised floating point addition and generalised floating point multiplication have code implementing arbitrary precision floating point balanced ternary.
| #Racket | Racket | #lang racket
;; Represent a balanced-ternary number as a list of 0's, 1's and -1's.
;;
;; e.g. 11 = 3^2 + 3^1 - 3^0 ~ "++-" ~ '(-1 1 1)
;; 6 = 3^2 - 3^1 ~ "+-0" ~ '(0 -1 1)
;;
;; Note: the list-rep starts with the least signifcant tert, while
;; the string-rep starts with the most significsnt tert.
(define (bt->integer t)
(if (null? t)
0
(+ (first t) (* 3 (bt->integer (rest t))))))
(define (integer->bt n)
(letrec ([recur (λ (b r) (cons b (convert (floor (/ r 3)))))]
[convert (λ (n) (if (zero? n) null
(case (modulo n 3)
[(0) (recur 0 n)]
[(1) (recur 1 n)]
[(2) (recur -1 (add1 n))])))])
(convert n)))
(define (bt->string t)
(define (strip-leading-zeroes a)
(if (or (null? a) (not (= (first a) 0))) a (strip-leading-zeroes (rest a))))
(string-join (map (λ (u)
(case u
[(1) "+"]
[(-1) "-"]
[(0) "0"]))
(strip-leading-zeroes (reverse t))) ""))
(define (string->bt s)
(reverse
(map (λ (c)
(case c
[(#\+) 1]
[(#\-) -1]
[(#\0) 0]))
(string->list s))))
(define (bt-negate t)
(map (λ (u) (- u)) t))
(define (bt-add a b [c 0])
(cond [(and (null? a) (null? b)) (if (zero? c) null (list c))]
[(null? b) (if (zero? c) a (bt-add a (list c)))]
[(null? a) (bt-add b a c)]
[else (let* ([t (+ (first a) (first b) c)]
[carry (if (> (abs t) 1) (sgn t) 0)]
[v (case (abs t)
[(3) 0]
[(2) (- (sgn t))]
[else t])])
(cons v (bt-add (rest a) (rest b) carry)))]))
(define (bt-multiply a b)
(cond [(null? a) null]
[(null? b) null]
[else (bt-add (case (first a)
[(-1) (bt-negate b)]
[(0) null]
[(1) b])
(cons 0 (bt-multiply (rest a) b)))]))
; test case
(let* ([a (string->bt "+-0++0+")]
[b (integer->bt -436)]
[c (string->bt "+-++-")]
[d (bt-multiply a (bt-add b (bt-negate c)))])
(for ([bt (list a b c d)]
[description (list 'a 'b 'c "a×(b−c)")])
(printf "~a = ~a or ~a\n" description (bt->integer bt) (bt->string bt))))
|
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #Ring | Ring |
n = 0
while pow(n,2) % 1000000 != 269696
n = n + 1
end
see "The smallest number whose square ends in 269696 is : " + n + nl
see "Its square is : " + pow(n,2)
|
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #Ruby | Ruby | n = 0
n = n + 2 until (n*n).modulo(1000000) == 269696
print n
|
http://rosettacode.org/wiki/Approximate_equality | Approximate equality | Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the
difference in floating point calculations between different language implementations becomes significant.
For example, a difference between 32 bit and 64 bit floating point calculations may appear by
about the 8th significant digit in base 10 arithmetic.
Task
Create a function which returns true if two floating point numbers are approximately equal.
The function should allow for differences in the magnitude of numbers, so that, for example,
100000000000000.01 may be approximately equal to 100000000000000.011,
even though 100.01 is not approximately equal to 100.011.
If the language has such a feature in its standard library, this may be used instead of a custom function.
Show the function results with comparisons on the following pairs of values:
100000000000000.01, 100000000000000.011 (note: should return true)
100.01, 100.011 (note: should return false)
10000000000000.001 / 10000.0, 1000000000.0000001000
0.001, 0.0010000001
0.000000000000000000000101, 0.0
sqrt(2) * sqrt(2), 2.0
-sqrt(2) * sqrt(2), -2.0
3.14159265358979323846, 3.14159265358979324
Answers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.
| #Phix | Phix | with javascript_semantics
procedure test(atom a,b, string dfmt="%g", cfmt="%g")
string ca = sprintf(cfmt,a),
cb = sprintf(cfmt,b),
eqs = iff(ca=cb?"":"NOT "),
da = sprintf(dfmt,a),
db = sprintf(dfmt,b)
printf(1,"%30s and\n%30s are %sapproximately equal\n",{da,db,eqs})
end procedure
test(100000000000000.01,100000000000000.011,"%.3f")
test(100.01,100.011,"%.3f")
test(10000000000000.001/10000.0,1000000000.0000001000,"%.10f")
test(0.001,0.0010000001,"%.10f") -- both
test(0.001,0.0010000001,"%.10f","%.10f") -- ways
test(0.000000000000000000000101,0.0,"%f") -- both
test(0.000000000000000000000101,0.0,"%f","%6f") -- ways
test(sqrt(2)*sqrt(2),2.0)
test(-sqrt(2)*sqrt(2),-2.0)
test(3.14159265358979323846,3.14159265358979324,"%.20f")
|
http://rosettacode.org/wiki/Approximate_equality | Approximate equality | Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the
difference in floating point calculations between different language implementations becomes significant.
For example, a difference between 32 bit and 64 bit floating point calculations may appear by
about the 8th significant digit in base 10 arithmetic.
Task
Create a function which returns true if two floating point numbers are approximately equal.
The function should allow for differences in the magnitude of numbers, so that, for example,
100000000000000.01 may be approximately equal to 100000000000000.011,
even though 100.01 is not approximately equal to 100.011.
If the language has such a feature in its standard library, this may be used instead of a custom function.
Show the function results with comparisons on the following pairs of values:
100000000000000.01, 100000000000000.011 (note: should return true)
100.01, 100.011 (note: should return false)
10000000000000.001 / 10000.0, 1000000000.0000001000
0.001, 0.0010000001
0.000000000000000000000101, 0.0
sqrt(2) * sqrt(2), 2.0
-sqrt(2) * sqrt(2), -2.0
3.14159265358979323846, 3.14159265358979324
Answers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.
| #Python | Python | math.isclose -> bool
a: double
b: double
*
rel_tol: double = 1e-09
maximum difference for being considered "close", relative to the
magnitude of the input values
abs_tol: double = 0.0
maximum difference for being considered "close", regardless of the
magnitude of the input values
Determine whether two floating point numbers are close in value.
Return True if a is close in value to b, and False otherwise.
For the values to be considered close, the difference between them
must be smaller than at least one of the tolerances.
-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
is, NaN is not close to anything, even itself. inf and -inf are
only close to themselves.
|
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
| #Delphi | Delphi | procedure Balanced_Brackets;
var BracketsStr : string;
TmpStr : string;
I,J : integer;
begin
Randomize;
for I := 1 to 9 do
begin
{ Create a random string of 2*N chars with N*"[" and N*"]" }
TmpStr := '';
for J := 1 to I do
TmpStr := '['+TmpStr+']';
BracketsStr := '';
while TmpStr > '' do
begin
J := Random(Length(TmpStr))+1;
BracketsStr := BracketsStr+TmpStr[J];
Delete(TmpStr,J,1);
end;
TmpStr := BracketsStr;
{ Test for balanced brackets }
while Pos('[]',TmpStr) > 0 do
Delete(TmpStr,Pos('[]',TmpStr),2);
if TmpStr = '' then
writeln(BracketsStr+': OK')
else
writeln(BracketsStr+': not OK');
end;
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.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Type Person
As String fullname
As String office
As String extension
As String homephone
As String email
Declare Constructor()
Declare Constructor(As String, As String, As String, As String, As String)
Declare Operator Cast() As String
End Type
Constructor Person()
End Constructor
Constructor Person(fullname As String, office As String, extension As String, _
homephone As String, email As String)
With This
.fullname = fullname
.office = office
.extension = extension
.homephone = homephone
.email = email
End With
End Constructor
Operator Person.Cast() As String
Return fullname + "," + office + "," + extension + "," + homephone + "," + email
End Operator
Type Record
As String account
As String password
As Integer uid
As Integer gid
As Person user
As String directory
As String shell
Declare Constructor()
Declare Constructor(As String, As String, As Integer, As Integer, As Person, As String, As String)
Declare Operator Cast() As String
End Type
Constructor Record()
End Constructor
Constructor Record(account As String, password As String, uid As Integer, gid As Integer, user As Person, _
directory As String, shell As String)
With This
.account = account
.password = password
.uid = uid
.gid = gid
.user = user
.directory = directory
.shell = shell
End With
End Constructor
Operator Record.Cast() As String
Return account + ":" + password + ":" + Str(uid) + ":" + Str(gid) + ":" + user + ":" + directory + ":" + shell
End Operator
Dim persons(1 To 3) As Person
persons(1) = Person("Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "[email protected]")
persons(2) = Person("Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "[email protected]" )
persons(3) = Person("X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "[email protected]" )
Dim records(1 To 3) As Record
records(1) = Record("jsmith", "x", 1001, 1000, persons(1), "/home/jsmith", "/bin/bash")
records(2) = Record("jdoe", "x", 1002, 1000, persons(2), "/home/jdoe" , "/bin/bash")
records(3) = Record("xyz", "x", 1003, 1000, persons(3), "/home/xyz" , "/bin/bash")
Open "passwd.txt" For Output As #1
Print #1, records(1)
Print #1, records(2)
Close #1
Open "passwd.txt" For Append Lock Write As #1
Print #1, records(3)
Close #1 |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Arturo | Arturo | ; create a dictionary
d: #[
name: "john"
surname: "doe"
age: 34
]
print d |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #C.23 | C# | using System;
using System.Linq;
using System.Collections.Generic;
public static class Program
{
public static void Main() =>
Console.WriteLine(string.Join(" ", FindAntiPrimes().Take(20)));
static IEnumerable<int> FindAntiPrimes() {
int max = 0;
for (int i = 1; ; i++) {
int divisors = CountDivisors(i);
if (divisors > max) {
max = divisors;
yield return i;
}
}
int CountDivisors(int n) => Enumerable.Range(1, n / 2).Count(i => n % i == 0) + 1;
}
} |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #C.2B.2B | C++ | #include <iostream>
int countDivisors(int n) {
if (n < 2) return 1;
int count = 2; // 1 and n
for (int i = 2; i <= n/2; ++i) {
if (n%i == 0) ++count;
}
return count;
}
int main() {
int maxDiv = 0, count = 0;
std::cout << "The first 20 anti-primes are:" << std::endl;
for (int n = 1; count < 20; ++n) {
int d = countDivisors(n);
if (d > maxDiv) {
std::cout << n << " ";
maxDiv = d;
count++;
}
}
std::cout << std::endl;
return 0;
} |
http://rosettacode.org/wiki/Atomic_updates | Atomic updates |
Task
Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to:
get the current value of any bucket
remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the transferred amount to ensure the values remain non-negative
In order to exercise this data type, create one set of buckets, and start three concurrent tasks:
As often as possible, pick two buckets and make their values closer to equal.
As often as possible, pick two buckets and arbitrarily redistribute their values.
At whatever rate is convenient, display (by any means) the total value and, optionally, the individual values of each bucket.
The display task need not be explicit; use of e.g. a debugger or trace tool is acceptable provided it is simple to set up to provide the display.
This task is intended as an exercise in atomic operations. The sum of the bucket values must be preserved even if the two tasks attempt to perform transfers simultaneously, and a straightforward solution is to ensure that at any time, only one transfer is actually occurring — that the transfer operation is atomic.
| #Lasso | Lasso | define atomic => thread {
data
private buckets = staticarray_join(10, void),
private lock = 0
public onCreate => {
loop(.buckets->size) => {
.`buckets`->get(loop_count) = math_random(0, 1000)
}
}
public buckets => .`buckets`
public bucket(index::integer) => .`buckets`->get(#index)
public transfer(source::integer, dest::integer, amount::integer) => {
#source == #dest
? return
#amount = math_min(#amount, .`buckets`->get(#source))
.`buckets`->get(#source) -= #amount
.`buckets`->get(#dest) += #amount
}
public numBuckets => .`buckets`->size
public lock => {
.`lock` == 1
? return false
.`lock` = 1
return true
}
public unlock => {
.`lock` = 0
}
}
local(initial_total) = (with b in atomic->buckets sum #b)
local(total) = #initial_total
// Make 2 buckets close to equal
local(_) = split_thread => {
local(bucket1) = math_random(1, atomic->numBuckets)
local(bucket2) = math_random(1, atomic->numBuckets)
local(value1) = atomic->bucket(#bucket1)
local(value2) = atomic->bucket(#bucket2)
if(#value1 >= #value2) => {
atomic->transfer(#bucket1, #bucket2, (#value1 - #value2) / 2)
else
atomic->transfer(#bucket2, #bucket1, (#value2 - #value1) / 2)
}
currentCapture->restart
}
// Randomly distribute 2 buckets
local(_) = split_thread => {
local(bucket1) = math_random(1, atomic->numBuckets)
local(bucket2) = math_random(1, atomic->numBuckets)
local(value1) = atomic->bucket(#bucket1)
atomic->transfer(#bucket1, #bucket2, math_random(1, #value1))
currentCapture->restart
}
local(buckets)
while(#initial_total == #total) => {
sleep(2000)
#buckets = atomic->buckets
#total = with b in #buckets sum #b
stdoutnl(#buckets->asString + " -- total: " + #total)
}
stdoutnl(`ERROR: totals no longer match: ` + #initial_total + ', ' + #total) |
http://rosettacode.org/wiki/Atomic_updates | Atomic updates |
Task
Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to:
get the current value of any bucket
remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the transferred amount to ensure the values remain non-negative
In order to exercise this data type, create one set of buckets, and start three concurrent tasks:
As often as possible, pick two buckets and make their values closer to equal.
As often as possible, pick two buckets and arbitrarily redistribute their values.
At whatever rate is convenient, display (by any means) the total value and, optionally, the individual values of each bucket.
The display task need not be explicit; use of e.g. a debugger or trace tool is acceptable provided it is simple to set up to provide the display.
This task is intended as an exercise in atomic operations. The sum of the bucket values must be preserved even if the two tasks attempt to perform transfers simultaneously, and a straightforward solution is to ensure that at any time, only one transfer is actually occurring — that the transfer operation is atomic.
| #Logtalk | Logtalk |
:- object(buckets).
:- threaded.
:- public([start/0, start/4]).
% bucket representation
:- private(bucket_/2).
:- dynamic(bucket_/2).
% use the same mutex for all the predicates that access the buckets
:- private([bucket/2, buckets/1, transfer/3]).
:- synchronized([bucket/2, buckets/1, transfer/3]).
start :-
% by default, create ten buckets with initial random integer values
% in the interval [0, 10[ and print their contents ten times
start(10, 0, 10, 10).
start(N, Min, Max, Samples) :-
% create the buckets with random values in the
% interval [Min, Max[ and return their sum
create_buckets(N, Min, Max, Sum),
write('Sum of all bucket values: '), write(Sum), nl, nl,
% use competitive or-parallelism for the three loops such that
% the computations terminate when the display loop terminates
threaded((
display_loop(Samples)
; match_loop(N)
; redistribute_loop(N)
)).
create_buckets(N, Min, Max, Sum) :-
% remove all exisiting buckets
retractall(bucket_(_,_)),
% create the new buckets
create_buckets(N, Min, Max, 0, Sum).
create_buckets(0, _, _, Sum, Sum) :-
!.
create_buckets(N, Min, Max, Sum0, Sum) :-
random::random(Min, Max, Value),
asserta(bucket_(N,Value)),
M is N - 1,
Sum1 is Sum0 + Value,
create_buckets(M, Min, Max, Sum1, Sum).
bucket(Bucket, Value) :-
bucket_(Bucket, Value).
buckets(Values) :-
findall(Value, bucket_(_, Value), Values).
transfer(Origin, _, Origin) :-
!.
transfer(Origin, Delta, Destin) :-
retract(bucket_(Origin, OriginValue)),
retract(bucket_(Destin, DestinValue)),
% the buckets may have changed between the access to its
% values and the calling of this transfer predicate; thus,
% we must ensure that we're transfering a legal amount
Amount is min(Delta, OriginValue),
NewOriginValue is OriginValue - Amount,
NewDestinValue is DestinValue + Amount,
assertz(bucket_(Origin, NewOriginValue)),
assertz(bucket_(Destin, NewDestinValue)).
match_loop(N) :-
% randomly select two buckets
M is N + 1,
random::random(1, M, Bucket1),
random::random(1, M, Bucket2),
% access their contents
bucket(Bucket1, Value1),
bucket(Bucket2, Value2),
% make their new values approximately equal
Delta is truncate(abs(Value1 - Value2)/2),
( Value1 > Value2 ->
transfer(Bucket1, Delta, Bucket2)
; Value1 < Value2 ->
transfer(Bucket2, Delta, Bucket1)
; true
),
match_loop(N).
redistribute_loop(N) :-
% randomly select two buckets
M is N + 1,
random::random(1, M, FromBucket),
random::random(1, M, ToBucket),
% access bucket from where we transfer
bucket(FromBucket, Current),
Limit is Current + 1,
random::random(0, Limit, Delta),
transfer(FromBucket, Delta, ToBucket),
redistribute_loop(N).
display_loop(0) :-
!.
display_loop(N) :-
buckets(Values),
write(Values), nl,
thread_sleep(2),
M is N - 1,
display_loop(M).
:- end_object.
|
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.
| #Java | Java | public class Assertions {
public static void main(String[] args) {
int a = 13;
// ... some real code here ...
assert a == 42;
// Throws an AssertionError when a is not 42.
assert a == 42 : "Error message";
// Throws an AssertionError when a is not 42,
// with "Error message" for the message.
// The error message can be any non-void expression.
}
} |
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.
| #JavaScript | JavaScript |
function check() {
try {
if (isNaN(answer)) throw '$answer is not a number';
if (answer != 42) throw '$answer is not 42';
}
catch(err) {
console.log(err);
answer = 42;
}
finally { console.log(answer); }
}
console.count('try'); // 1
let answer;
check();
console.count('try'); // 2
answer = 'fourty two';
check();
console.count('try'); // 3
answer = 23;
check();
|
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.
| #C | C | #ifndef CALLBACK_H
#define CALLBACK_H
/*
* By declaring the function in a separate file, we allow
* it to be used by other source files.
*
* It also stops ICC from complaining.
*
* If you don't want to use it outside of callback.c, this
* file can be removed, provided the static keyword is prepended
* to the definition.
*/
void map(int* array, int len, void(*callback)(int,int));
#endif |
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.
| #C.23 | C# | int[] intArray = { 1, 2, 3, 4, 5 };
// Simplest method: LINQ, functional
int[] squares1 = intArray.Select(x => x * x).ToArray();
// Slightly fancier: LINQ, query expression
int[] squares2 = (from x in intArray
select x * x).ToArray();
// Or, if you only want to call a function on each element, just use foreach
foreach (var i in intArray)
Console.WriteLine(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
| #OCaml | OCaml | let mode lst =
let seen = Hashtbl.create 42 in
List.iter (fun x ->
let old = if Hashtbl.mem seen x then
Hashtbl.find seen x
else 0 in
Hashtbl.replace seen x (old + 1))
lst;
let best = Hashtbl.fold (fun _ -> max) seen 0 in
Hashtbl.fold (fun k v acc ->
if v = best then k :: acc
else acc)
seen [] |
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
| #Common_Lisp | Common Lisp | ;; iterate using dolist, destructure manually
(dolist (pair alist)
(destructuring-bind (key . value) pair
(format t "~&Key: ~a, Value: ~a." key value)))
;; iterate and destructure with loop
(loop for (key . value) in alist
do (format t "~&Key: ~a, Value: ~a." key value)) |
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
| #Crystal | Crystal | dict = {'A' => 1, 'B' => 2}
dict.each { |pair|
puts pair
}
dict.each_key { |key|
puts key
}
dict.each_value { |value|
puts value
} |
http://rosettacode.org/wiki/Apply_a_digital_filter_(direct_form_II_transposed) | Apply a digital filter (direct form II transposed) | Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [1]
Task
Filter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667]
The signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]
| #Lua | Lua | function filter(b,a,input)
local out = {}
for i=1,table.getn(input) do
local tmp = 0
local j = 0
out[i] = 0
for j=1,table.getn(b) do
if i - j < 0 then
--continue
else
tmp = tmp + b[j] * input[i - j + 1]
end
end
for j=2,table.getn(a) do
if i - j < 0 then
--continue
else
tmp = tmp - a[j] * out[i - j + 1]
end
end
tmp = tmp / a[1]
out[i] = tmp
end
return out
end
function main()
local sig = {
-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412,-0.662370894973,
-1.00700480494, -0.404707073677, 0.800482325044, 0.743500089861, 1.01090520172,
0.741527555207, 0.277841675195, 0.400833448236,-0.2085993586, -0.172842103641,
-0.134316096293, 0.0259303398477,0.490105989562, 0.549391221511, 0.9047198589
}
--Constants for a Butterworth filter (order 3, low pass)
local a = {1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17}
local b = {0.16666667, 0.5, 0.5, 0.16666667}
local result = filter(b,a,sig)
for i=1,table.getn(result) do
io.write(result[i] .. ", ")
end
print()
return nil
end
main() |
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
| #Delphi | Delphi | program AveragesArithmeticMean;
{$APPTYPE CONSOLE}
uses Types;
function ArithmeticMean(aArray: TDoubleDynArray): Double;
var
lValue: Double;
begin
Result := 0;
for lValue in aArray do
Result := Result + lValue;
if Result > 0 then
Result := Result / Length(aArray);
end;
begin
Writeln(Mean(TDoubleDynArray.Create()));
Writeln(Mean(TDoubleDynArray.Create(1,2,3,4,5)));
end. |
http://rosettacode.org/wiki/Associative_array/Merging | Associative array/Merging | Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:
Key
Value
"name"
"Rocket Skates"
"price"
15.25
"color"
"red"
"year"
1974
| #SenseTalk | SenseTalk | set base to {name:"Rocket Skates", price:12.75, color:"yellow"}
set update to {price:15.25, color:"red", year:1974}
put "Base data: " & base
put "Update data: " & update
// replacing as an operator, to generate merged data on the fly:
put "Merged data: " & base replacing properties in update
// replace as a command, to modify base data in place:
replace properties of update in base
put "Base after update: " & base
|
http://rosettacode.org/wiki/Associative_array/Merging | Associative array/Merging | Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:
Key
Value
"name"
"Rocket Skates"
"price"
15.25
"color"
"red"
"year"
1974
| #Smalltalk | Smalltalk | base := Dictionary withAssociations:{
'name'-> 'Rocket Skates' .
'price' -> 12.75 .
'color' -> 'yellow' }.
update := Dictionary withAssociations:{
'price' -> 15.25 .
'color' -> 'red' .
'year' -> 1974 }.
result := Dictionary new
declareAllFrom:base;
declareAllFrom:update.
Transcript showCR: result. |
http://rosettacode.org/wiki/Associative_array/Merging | Associative array/Merging | Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:
Key
Value
"name"
"Rocket Skates"
"price"
15.25
"color"
"red"
"year"
1974
| #Swift | Swift | let base : [String: Any] = ["name": "Rocket Skates", "price": 12.75, "color": "yellow"]
let update : [String: Any] = ["price": 15.25, "color": "red", "year": 1974]
let result = base.merging(update) { (_, new) in new }
print(result) |
http://rosettacode.org/wiki/Average_loop_length | Average loop length | Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence.
Task
Write a program or a script that estimates, for each N, the average length until the first such repetition.
Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.
This problem comes from the end of Donald Knuth's Christmas tree lecture 2011.
Example of expected output:
N average analytical (error)
=== ========= ============ =========
1 1.0000 1.0000 ( 0.00%)
2 1.4992 1.5000 ( 0.05%)
3 1.8784 1.8889 ( 0.56%)
4 2.2316 2.2188 ( 0.58%)
5 2.4982 2.5104 ( 0.49%)
6 2.7897 2.7747 ( 0.54%)
7 3.0153 3.0181 ( 0.09%)
8 3.2429 3.2450 ( 0.07%)
9 3.4536 3.4583 ( 0.14%)
10 3.6649 3.6602 ( 0.13%)
11 3.8091 3.8524 ( 1.12%)
12 3.9986 4.0361 ( 0.93%)
13 4.2074 4.2123 ( 0.12%)
14 4.3711 4.3820 ( 0.25%)
15 4.5275 4.5458 ( 0.40%)
16 4.6755 4.7043 ( 0.61%)
17 4.8877 4.8579 ( 0.61%)
18 4.9951 5.0071 ( 0.24%)
19 5.1312 5.1522 ( 0.41%)
20 5.2699 5.2936 ( 0.45%)
| #REXX | REXX | /*REXX program computes the average loop length mapping a random field 1···N ───► 1···N */
parse arg runs tests seed . /*obtain optional arguments from the CL*/
if runs =='' | runs =="," then runs = 40 /*Not specified? Then use the default.*/
if tests =='' | tests =="," then tests= 1000000 /* " " " " " " */
if datatype(seed, 'W') then call random ,, seed /*Is integer? For RAND repeatability.*/
!.=0; !.0=1 /*used for factorial (!) memoization.*/
numeric digits 100000 /*be able to calculate 25k! if need be.*/
numeric digits max(9, length( !(runs) ) ) /*set the NUMERIC DIGITS for !(runs). */
say right( runs, 24) 'runs' /*display number of runs we're using.*/
say right( tests, 24) 'tests' /* " " " tests " " */
say right( digits(), 24) 'digits' /* " " " digits " " */
say
say " N average exact % error " /* ◄─── title, header ►────────┐ */
hdr=" ═══ ═════════ ═════════ ═════════"; pad=left('',3) /* ◄────────┘ */
say hdr
do #=1 for runs; av=fmtD( exact(#) ) /*use four digits past decimal point. */
xa=fmtD( exper(#) ) /* " " " " " " */
say right(#,9) pad xa pad av pad fmtD( abs(xa-av) * 100 / av) /*show values.*/
end /*#*/
say hdr /*display the final header (some bars).*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
!: procedure expose !.; parse arg z; if !.z\==0 then return !.z
!=1; do j=2 for z -1; !=!*j; !.j=!; end; /*compute factorial*/ return !
/*──────────────────────────────────────────────────────────────────────────────────────*/
exact: parse arg x; s=0; do j=1 for x; s=s + !(x) / !(x-j) / x**j; end; return s
/*──────────────────────────────────────────────────────────────────────────────────────*/
exper: parse arg n; k=0; do tests; $.=0 /*do it TESTS times.*/
do n; r=random(1, n); if $.r then leave
$.r=1; k=k + 1 /*bump the counter. */
end /*n*/
end /*tests*/
return k/tests
/*──────────────────────────────────────────────────────────────────────────────────────*/
fmtD: parse arg y,d; d=word(d 4, 1); y=format(y, , d); parse var y w '.' f
if f=0 then return w || left('', d +1); return y |
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period.
It can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA().
The word stateful in the task description refers to the need for SMA() to remember certain information between calls to it:
The period, P
An ordered container of at least the last P numbers from each of its individual calls.
Stateful also means that successive calls to I(), the initializer, should return separate routines that do not share saved state so they could be used on two independent streams of data.
Pseudo-code for an implementation of SMA is:
function SMA(number: N):
stateful integer: P
stateful list: stream
number: average
stream.append_last(N)
if stream.length() > P:
# Only average the last P elements of the stream
stream.delete_first()
if stream.length() == 0:
average = 0
else:
average = sum( stream.values() ) / stream.length()
return average
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 simple_moving_average(period) {
var list = []
var sum = 0
func (number) {
list.append(number)
sum += number
if (list.len > period) {
sum -= list.shift
}
(sum / list.length)
}
}
var ma3 = simple_moving_average(3)
var ma5 = simple_moving_average(5)
for num (1..5, flip(1..5)) {
printf("Next number = %d, SMA_3 = %.3f, SMA_5 = %.1f\n",
num, ma3.call(num), ma5.call(num))
} |
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.
| #LLVM | LLVM | ; This is not strictly LLVM, as it uses the C library function "printf".
; LLVM does not provide a way to print values, so the alternative would be
; to just load the string into memory, and that would be boring.
$"ATTRACTIVE_STR" = comdat any
$"FORMAT_NUMBER" = comdat any
$"NEWLINE_STR" = comdat any
@"ATTRACTIVE_STR" = linkonce_odr unnamed_addr constant [52 x i8] c"The attractive numbers up to and including %d are:\0A\00", comdat, align 1
@"FORMAT_NUMBER" = linkonce_odr unnamed_addr constant [4 x i8] c"%4d\00", comdat, align 1
@"NEWLINE_STR" = linkonce_odr unnamed_addr constant [2 x i8] c"\0A\00", comdat, align 1
;--- The declaration for the external C printf function.
declare i32 @printf(i8*, ...)
; Function Attrs: noinline nounwind optnone uwtable
define zeroext i1 @is_prime(i32) #0 {
%2 = alloca i1, align 1 ;-- allocate return value
%3 = alloca i32, align 4 ;-- allocate n
%4 = alloca i32, align 4 ;-- allocate d
store i32 %0, i32* %3, align 4 ;-- store local copy of n
store i32 5, i32* %4, align 4 ;-- store 5 in d
%5 = load i32, i32* %3, align 4 ;-- load n
%6 = icmp slt i32 %5, 2 ;-- n < 2
br i1 %6, label %nlt2, label %niseven
nlt2:
store i1 false, i1* %2, align 1 ;-- store false in return value
br label %exit
niseven:
%7 = load i32, i32* %3, align 4 ;-- load n
%8 = srem i32 %7, 2 ;-- n % 2
%9 = icmp ne i32 %8, 0 ;-- (n % 2) != 0
br i1 %9, label %odd, label %even
even:
%10 = load i32, i32* %3, align 4 ;-- load n
%11 = icmp eq i32 %10, 2 ;-- n == 2
store i1 %11, i1* %2, align 1 ;-- store (n == 2) in return value
br label %exit
odd:
%12 = load i32, i32* %3, align 4 ;-- load n
%13 = srem i32 %12, 3 ;-- n % 3
%14 = icmp ne i32 %13, 0 ;-- (n % 3) != 0
br i1 %14, label %loop, label %div3
div3:
%15 = load i32, i32* %3, align 4 ;-- load n
%16 = icmp eq i32 %15, 3 ;-- n == 3
store i1 %16, i1* %2, align 1 ;-- store (n == 3) in return value
br label %exit
loop:
%17 = load i32, i32* %4, align 4 ;-- load d
%18 = load i32, i32* %4, align 4 ;-- load d
%19 = mul nsw i32 %17, %18 ;-- d * d
%20 = load i32, i32* %3, align 4 ;-- load n
%21 = icmp sle i32 %19, %20 ;-- (d * d) <= n
br i1 %21, label %first, label %prime
first:
%22 = load i32, i32* %3, align 4 ;-- load n
%23 = load i32, i32* %4, align 4 ;-- load d
%24 = srem i32 %22, %23 ;-- n % d
%25 = icmp ne i32 %24, 0 ;-- (n % d) != 0
br i1 %25, label %second, label %notprime
second:
%26 = load i32, i32* %4, align 4 ;-- load d
%27 = add nsw i32 %26, 2 ;-- increment d by 2
store i32 %27, i32* %4, align 4 ;-- store d
%28 = load i32, i32* %3, align 4 ;-- load n
%29 = load i32, i32* %4, align 4 ;-- load d
%30 = srem i32 %28, %29 ;-- n % d
%31 = icmp ne i32 %30, 0 ;-- (n % d) != 0
br i1 %31, label %loop_end, label %notprime
loop_end:
%32 = load i32, i32* %4, align 4 ;-- load d
%33 = add nsw i32 %32, 4 ;-- increment d by 4
store i32 %33, i32* %4, align 4 ;-- store d
br label %loop
notprime:
store i1 false, i1* %2, align 1 ;-- store false in return value
br label %exit
prime:
store i1 true, i1* %2, align 1 ;-- store true in return value
br label %exit
exit:
%34 = load i1, i1* %2, align 1 ;-- load return value
ret i1 %34
}
; Function Attrs: noinline nounwind optnone uwtable
define i32 @count_prime_factors(i32) #0 {
%2 = alloca i32, align 4 ;-- allocate return value
%3 = alloca i32, align 4 ;-- allocate n
%4 = alloca i32, align 4 ;-- allocate count
%5 = alloca i32, align 4 ;-- allocate f
store i32 %0, i32* %3, align 4 ;-- store local copy of n
store i32 0, i32* %4, align 4 ;-- store zero in count
store i32 2, i32* %5, align 4 ;-- store 2 in f
%6 = load i32, i32* %3, align 4 ;-- load n
%7 = icmp eq i32 %6, 1 ;-- n == 1
br i1 %7, label %eq1, label %ne1
eq1:
store i32 0, i32* %2, align 4 ;-- store zero in return value
br label %exit
ne1:
%8 = load i32, i32* %3, align 4 ;-- load n
%9 = call zeroext i1 @is_prime(i32 %8) ;-- is n prime?
br i1 %9, label %prime, label %loop
prime:
store i32 1, i32* %2, align 4 ;-- store a in return value
br label %exit
loop:
%10 = load i32, i32* %3, align 4 ;-- load n
%11 = load i32, i32* %5, align 4 ;-- load f
%12 = srem i32 %10, %11 ;-- n % f
%13 = icmp ne i32 %12, 0 ;-- (n % f) != 0
br i1 %13, label %br2, label %br1
br1:
%14 = load i32, i32* %4, align 4 ;-- load count
%15 = add nsw i32 %14, 1 ;-- increment count
store i32 %15, i32* %4, align 4 ;-- store count
%16 = load i32, i32* %5, align 4 ;-- load f
%17 = load i32, i32* %3, align 4 ;-- load n
%18 = sdiv i32 %17, %16 ;-- n / f
store i32 %18, i32* %3, align 4 ;-- n = n / f
%19 = load i32, i32* %3, align 4 ;-- load n
%20 = icmp eq i32 %19, 1 ;-- n == 1
br i1 %20, label %br1_1, label %br1_2
br1_1:
%21 = load i32, i32* %4, align 4 ;-- load count
store i32 %21, i32* %2, align 4 ;-- store the count in the return value
br label %exit
br1_2:
%22 = load i32, i32* %3, align 4 ;-- load n
%23 = call zeroext i1 @is_prime(i32 %22) ;-- is n prime?
br i1 %23, label %br1_3, label %loop
br1_3:
%24 = load i32, i32* %3, align 4 ;-- load n
store i32 %24, i32* %5, align 4 ;-- f = n
br label %loop
br2:
%25 = load i32, i32* %5, align 4 ;-- load f
%26 = icmp sge i32 %25, 3 ;-- f >= 3
br i1 %26, label %br2_1, label %br3
br2_1:
%27 = load i32, i32* %5, align 4 ;-- load f
%28 = add nsw i32 %27, 2 ;-- increment f by 2
store i32 %28, i32* %5, align 4 ;-- store f
br label %loop
br3:
store i32 3, i32* %5, align 4 ;-- store 3 in f
br label %loop
exit:
%29 = load i32, i32* %2, align 4 ;-- load return value
ret i32 %29
}
; Function Attrs: noinline nounwind optnone uwtable
define i32 @main() #0 {
%1 = alloca i32, align 4 ;-- allocate i
%2 = alloca i32, align 4 ;-- allocate n
%3 = alloca i32, align 4 ;-- count
store i32 0, i32* %3, align 4 ;-- store zero in count
%4 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([52 x i8], [52 x i8]* @"ATTRACTIVE_STR", i32 0, i32 0), i32 120)
store i32 1, i32* %1, align 4 ;-- store 1 in i
br label %loop
loop:
%5 = load i32, i32* %1, align 4 ;-- load i
%6 = icmp sle i32 %5, 120 ;-- i <= 120
br i1 %6, label %loop_body, label %exit
loop_body:
%7 = load i32, i32* %1, align 4 ;-- load i
%8 = call i32 @count_prime_factors(i32 %7) ;-- count factors of i
store i32 %8, i32* %2, align 4 ;-- store factors in n
%9 = call zeroext i1 @is_prime(i32 %8) ;-- is n prime?
br i1 %9, label %prime_branch, label %loop_inc
prime_branch:
%10 = load i32, i32* %1, align 4 ;-- load i
%11 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"FORMAT_NUMBER", i32 0, i32 0), i32 %10)
%12 = load i32, i32* %3, align 4 ;-- load count
%13 = add nsw i32 %12, 1 ;-- increment count
store i32 %13, i32* %3, align 4 ;-- store count
%14 = srem i32 %13, 20 ;-- count % 20
%15 = icmp ne i32 %14, 0 ;-- (count % 20) != 0
br i1 %15, label %loop_inc, label %row_end
row_end:
%16 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([2 x i8], [2 x i8]* @"NEWLINE_STR", i32 0, i32 0))
br label %loop_inc
loop_inc:
%17 = load i32, i32* %1, align 4 ;-- load i
%18 = add nsw i32 %17, 1 ;-- increment i
store i32 %18, i32* %1, align 4 ;-- store i
br label %loop
exit:
%19 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([2 x i8], [2 x i8]* @"NEWLINE_STR", i32 0, i32 0))
ret i32 0
}
attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" } |
http://rosettacode.org/wiki/Averages/Mean_time_of_day | Averages/Mean time of day | Task[edit]
A particular activity of bats occurs at these times of the day:
23:00:17, 23:40:20, 00:12:45, 00:17:19
Using the idea that there are twenty-four hours in a day,
which is analogous to there being 360 degrees in a circle,
map times of day to and from angles;
and using the ideas of Averages/Mean angle
compute and show the average time of the nocturnal activity
to an accuracy of one second of time.
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
| #Phix | Phix | with javascript_semantics
function MeanAngle(sequence angles)
atom x = 0, y = 0
for i=1 to length(angles) do
atom ai_rad = angles[i]*PI/180
x += cos(ai_rad)
y += sin(ai_rad)
end for
if abs(x)<1e-16 then return "not meaningful" end if
return atan2(y,x)*180/PI
end function
function toSecAngle(integer hours, integer minutes, integer seconds)
return ((hours*60+minutes)*60+seconds)/(24*60*60)*360
end function
constant Times = {toSecAngle(23,00,17),
toSecAngle(23,40,20),
toSecAngle(00,12,45),
toSecAngle(00,17,19)}
function toHMS(object s)
if not string(s) then
if s<0 then s+=360 end if
s = 24*60*60*s/360
atom hours = floor(s/3600),
mins = floor(remainder(s,3600)/60),
secs = remainder(s,60)
s = sprintf("%02d:%02d:%02d",{hours,mins,secs})
end if
return s
end function
printf(1,"Mean Time is %s\n",{toHMS(MeanAngle(Times))})
|
http://rosettacode.org/wiki/AVL_tree | AVL tree |
This page uses content from Wikipedia. The original article was at AVL tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In computer science, an AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; at no time do they differ by more than one because rebalancing is done ensure this is the case. Lookup, insertion, and deletion all take O(log n) time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations. Note the tree of nodes comprise a set, so duplicate node keys are not allowed.
AVL trees are often compared with red-black trees because they support the same set of operations and because red-black trees also take O(log n) time for the basic operations. Because AVL trees are more rigidly balanced, they are faster than red-black trees for lookup-intensive applications. Similar to red-black trees, AVL trees are height-balanced, but in general not weight-balanced nor μ-balanced; that is, sibling nodes can have hugely differing numbers of descendants.
Task
Implement an AVL tree in the language of choice, and provide at least basic operations.
| #Scala | Scala | import scala.collection.mutable
class AVLTree[A](implicit val ordering: Ordering[A]) extends mutable.SortedSet[A] {
if (ordering eq null) throw new NullPointerException("ordering must not be null")
private var _root: AVLNode = _
private var _size = 0
override def size: Int = _size
override def foreach[U](f: A => U): Unit = {
val stack = mutable.Stack[AVLNode]()
var current = root
var done = false
while (!done) {
if (current != null) {
stack.push(current)
current = current.left
} else if (stack.nonEmpty) {
current = stack.pop()
f.apply(current.key)
current = current.right
} else {
done = true
}
}
}
def root: AVLNode = _root
override def isEmpty: Boolean = root == null
override def min[B >: A](implicit cmp: Ordering[B]): A = minNode().key
def minNode(): AVLNode = {
if (root == null) throw new UnsupportedOperationException("empty tree")
var node = root
while (node.left != null) node = node.left
node
}
override def max[B >: A](implicit cmp: Ordering[B]): A = maxNode().key
def maxNode(): AVLNode = {
if (root == null) throw new UnsupportedOperationException("empty tree")
var node = root
while (node.right != null) node = node.right
node
}
def next(node: AVLNode): Option[AVLNode] = {
var successor = node
if (successor != null) {
if (successor.right != null) {
successor = successor.right
while (successor != null && successor.left != null) {
successor = successor.left
}
} else {
successor = node.parent
var n = node
while (successor != null && successor.right == n) {
n = successor
successor = successor.parent
}
}
}
Option(successor)
}
def prev(node: AVLNode): Option[AVLNode] = {
var predecessor = node
if (predecessor != null) {
if (predecessor.left != null) {
predecessor = predecessor.left
while (predecessor != null && predecessor.right != null) {
predecessor = predecessor.right
}
} else {
predecessor = node.parent
var n = node
while (predecessor != null && predecessor.left == n) {
n = predecessor
predecessor = predecessor.parent
}
}
}
Option(predecessor)
}
override def rangeImpl(from: Option[A], until: Option[A]): mutable.SortedSet[A] = ???
override def +=(key: A): AVLTree.this.type = {
insert(key)
this
}
def insert(key: A): AVLNode = {
if (root == null) {
_root = new AVLNode(key)
_size += 1
return root
}
var node = root
var parent: AVLNode = null
var cmp = 0
while (node != null) {
parent = node
cmp = ordering.compare(key, node.key)
if (cmp == 0) return node // duplicate
node = node.matchNextChild(cmp)
}
val newNode = new AVLNode(key, parent)
if (cmp <= 0) parent._left = newNode
else parent._right = newNode
while (parent != null) {
cmp = ordering.compare(parent.key, key)
if (cmp < 0) parent.balanceFactor -= 1
else parent.balanceFactor += 1
parent = parent.balanceFactor match {
case -1 | 1 => parent.parent
case x if x < -1 =>
if (parent.right.balanceFactor == 1) rotateRight(parent.right)
val newRoot = rotateLeft(parent)
if (parent == root) _root = newRoot
null
case x if x > 1 =>
if (parent.left.balanceFactor == -1) rotateLeft(parent.left)
val newRoot = rotateRight(parent)
if (parent == root) _root = newRoot
null
case _ => null
}
}
_size += 1
newNode
}
override def -=(key: A): AVLTree.this.type = {
remove(key)
this
}
override def remove(key: A): Boolean = {
var node = findNode(key).orNull
if (node == null) return false
if (node.left != null) {
var max = node.left
while (max.left != null || max.right != null) {
while (max.right != null) max = max.right
node._key = max.key
if (max.left != null) {
node = max
max = max.left
}
}
node._key = max.key
node = max
}
if (node.right != null) {
var min = node.right
while (min.left != null || min.right != null) {
while (min.left != null) min = min.left
node._key = min.key
if (min.right != null) {
node = min
min = min.right
}
}
node._key = min.key
node = min
}
var current = node
var parent = node.parent
while (parent != null) {
parent.balanceFactor += (if (parent.left == current) -1 else 1)
current = parent.balanceFactor match {
case x if x < -1 =>
if (parent.right.balanceFactor == 1) rotateRight(parent.right)
val newRoot = rotateLeft(parent)
if (parent == root) _root = newRoot
newRoot
case x if x > 1 =>
if (parent.left.balanceFactor == -1) rotateLeft(parent.left)
val newRoot = rotateRight(parent)
if (parent == root) _root = newRoot
newRoot
case _ => parent
}
parent = current.balanceFactor match {
case -1 | 1 => null
case _ => current.parent
}
}
if (node.parent != null) {
if (node.parent.left == node) {
node.parent._left = null
} else {
node.parent._right = null
}
}
if (node == root) _root = null
_size -= 1
true
}
def findNode(key: A): Option[AVLNode] = {
var node = root
while (node != null) {
val cmp = ordering.compare(key, node.key)
if (cmp == 0) return Some(node)
node = node.matchNextChild(cmp)
}
None
}
private def rotateLeft(node: AVLNode): AVLNode = {
val rightNode = node.right
node._right = rightNode.left
if (node.right != null) node.right._parent = node
rightNode._parent = node.parent
if (rightNode.parent != null) {
if (rightNode.parent.left == node) {
rightNode.parent._left = rightNode
} else {
rightNode.parent._right = rightNode
}
}
node._parent = rightNode
rightNode._left = node
node.balanceFactor += 1
if (rightNode.balanceFactor < 0) {
node.balanceFactor -= rightNode.balanceFactor
}
rightNode.balanceFactor += 1
if (node.balanceFactor > 0) {
rightNode.balanceFactor += node.balanceFactor
}
rightNode
}
private def rotateRight(node: AVLNode): AVLNode = {
val leftNode = node.left
node._left = leftNode.right
if (node.left != null) node.left._parent = node
leftNode._parent = node.parent
if (leftNode.parent != null) {
if (leftNode.parent.left == node) {
leftNode.parent._left = leftNode
} else {
leftNode.parent._right = leftNode
}
}
node._parent = leftNode
leftNode._right = node
node.balanceFactor -= 1
if (leftNode.balanceFactor > 0) {
node.balanceFactor -= leftNode.balanceFactor
}
leftNode.balanceFactor -= 1
if (node.balanceFactor < 0) {
leftNode.balanceFactor += node.balanceFactor
}
leftNode
}
override def contains(elem: A): Boolean = findNode(elem).isDefined
override def iterator: Iterator[A] = ???
override def keysIteratorFrom(start: A): Iterator[A] = ???
class AVLNode private[AVLTree](k: A, p: AVLNode = null) {
private[AVLTree] var _key: A = k
private[AVLTree] var _parent: AVLNode = p
private[AVLTree] var _left: AVLNode = _
private[AVLTree] var _right: AVLNode = _
private[AVLTree] var balanceFactor: Int = 0
def parent: AVLNode = _parent
private[AVLTree] def selectNextChild(key: A): AVLNode = matchNextChild(ordering.compare(key, this.key))
def key: A = _key
private[AVLTree] def matchNextChild(cmp: Int): AVLNode = cmp match {
case x if x < 0 => left
case x if x > 0 => right
case _ => null
}
def left: AVLNode = _left
def right: AVLNode = _right
}
} |
http://rosettacode.org/wiki/Averages/Mean_angle | Averages/Mean angle | When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle.
If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the second was of 10 degrees then the average of the numbers is 180 degrees, whereas if you can note that 350 degrees is equivalent to -10 degrees and so you have two readings at 10 degrees either side of zero degrees leading to a more fitting mean angle of zero degrees.
To calculate the mean angle of several angles:
Assume all angles are on the unit circle and convert them to complex numbers expressed in real and imaginary form.
Compute the mean of the complex numbers.
Convert the complex mean to polar coordinates whereupon the phase of the complex mean is the required angular mean.
(Note that, since the mean is the sum divided by the number of numbers, and division by a positive real number does not affect the angle, you can also simply compute the sum for step 2.)
You can alternatively use this formula:
Given the angles
α
1
,
…
,
α
n
{\displaystyle \alpha _{1},\dots ,\alpha _{n}}
the mean is computed by
α
¯
=
atan2
(
1
n
⋅
∑
j
=
1
n
sin
α
j
,
1
n
⋅
∑
j
=
1
n
cos
α
j
)
{\displaystyle {\bar {\alpha }}=\operatorname {atan2} \left({\frac {1}{n}}\cdot \sum _{j=1}^{n}\sin \alpha _{j},{\frac {1}{n}}\cdot \sum _{j=1}^{n}\cos \alpha _{j}\right)}
Task[edit]
write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle.
(You should use a built-in function if you have one that does this for degrees or radians).
Use the function to compute the means of these lists of angles (in degrees):
[350, 10]
[90, 180, 270, 360]
[10, 20, 30]
Show your output here.
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
| #Perl | Perl | sub Pi () { 3.1415926535897932384626433832795028842 }
sub meanangle {
my($x, $y) = (0,0);
($x,$y) = ($x + sin($_), $y + cos($_)) for @_;
my $atan = atan2($x,$y);
$atan += 2*Pi while $atan < 0; # Ghetto fmod
$atan -= 2*Pi while $atan > 2*Pi;
$atan;
}
sub meandegrees {
meanangle( map { $_ * Pi/180 } @_ ) * 180/Pi;
}
print "The mean angle of [@$_] is: ", meandegrees(@$_), " degrees\n"
for ([350,10], [90,180,270,360], [10,20,30]); |
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
| #Fortran | Fortran | program Median_Test
real :: a(7) = (/ 4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2 /), &
b(6) = (/ 4.1, 7.2, 1.7, 9.3, 4.4, 3.2 /)
print *, median(a)
print *, median(b)
contains
function median(a, found)
real, dimension(:), intent(in) :: a
! the optional found argument can be used to check
! if the function returned a valid value; we need this
! just if we suspect our "vector" can be "empty"
logical, optional, intent(out) :: found
real :: median
integer :: l
real, dimension(size(a,1)) :: ac
if ( size(a,1) < 1 ) then
if ( present(found) ) found = .false.
else
ac = a
! this is not an intrinsic: peek a sort algo from
! Category:Sorting, fixing it to work with real if
! it uses integer instead.
call sort(ac)
l = size(a,1)
if ( mod(l, 2) == 0 ) then
median = (ac(l/2+1) + ac(l/2))/2.0
else
median = ac(l/2+1)
end if
if ( present(found) ) found = .true.
end if
end function median
end program Median_Test |
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
| #K | K |
am:{(+/x)%#x}
gm:{(*/x)^(%#x)}
hm:{(#x)%+/%:'x}
{(am x;gm x;hm x)} 1+!10
5.5 4.528729 3.414172
|
http://rosettacode.org/wiki/Balanced_ternary | Balanced ternary | Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1.
Examples
Decimal 11 = 32 + 31 − 30, thus it can be written as "++−"
Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0"
Task
Implement balanced ternary representation of integers with the following:
Support arbitrarily large integers, both positive and negative;
Provide ways to convert to and from text strings, using digits '+', '-' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5).
Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type is balanced ternary). If your native integers can't support arbitrary length, overflows during conversion must be indicated.
Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do not convert to native integers first.
Make your implementation efficient, with a reasonable definition of "efficient" (and with a reasonable definition of "reasonable").
Test case With balanced ternaries a from string "+-0++0+", b from native integer -436, c "+-++-":
write out a, b and c in decimal notation;
calculate a × (b − c), write out the result in both ternary and decimal notations.
Note: The pages generalised floating point addition and generalised floating point multiplication have code implementing arbitrary precision floating point balanced ternary.
| #Raku | Raku | class BT {
has @.coeff;
my %co2bt = '-1' => '-', '0' => '0', '1' => '+';
my %bt2co = %co2bt.invert;
multi method new (Str $s) {
self.bless(coeff => %bt2co{$s.flip.comb});
}
multi method new (Int $i where $i >= 0) {
self.bless(coeff => carry $i.base(3).comb.reverse);
}
multi method new (Int $i where $i < 0) {
self.new(-$i).neg;
}
method Str () { %co2bt{@!coeff}.join.flip }
method Int () { [+] @!coeff Z* (1,3,9...*) }
multi method neg () {
self.new: coeff => carry self.coeff X* -1;
}
}
sub carry (*@digits is copy) {
loop (my $i = 0; $i < @digits; $i++) {
while @digits[$i] < -1 { @digits[$i] += 3; @digits[$i+1]--; }
while @digits[$i] > 1 { @digits[$i] -= 3; @digits[$i+1]++; }
}
pop @digits while @digits and not @digits[*-1];
@digits;
}
multi prefix:<-> (BT $x) { $x.neg }
multi infix:<+> (BT $x, BT $y) {
my ($b,$a) = sort +*.coeff, ($x, $y);
BT.new: coeff => carry ($a.coeff Z+ |$b.coeff, |(0 xx $a.coeff - $b.coeff));
}
multi infix:<-> (BT $x, BT $y) { $x + $y.neg }
multi infix:<*> (BT $x, BT $y) {
my @x = $x.coeff;
my @y = $y.coeff;
my @z = 0 xx @x+@y-1;
my @safe;
for @x -> $xd {
@z = @z Z+ |(@y X* $xd), |(0 xx @z-@y);
@safe.push: @z.shift;
}
BT.new: coeff => carry @safe, @z;
}
my $a = BT.new: "+-0++0+";
my $b = BT.new: -436;
my $c = BT.new: "+-++-";
my $x = $a * ( $b - $c );
say 'a == ', $a.Int;
say 'b == ', $b.Int;
say 'c == ', $c.Int;
say "a × (b − c) == ", ~$x, ' == ', $x.Int; |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #Run_BASIC | Run BASIC | for n = 1 to 1000000
if n^2 MOD 1000000 = 269696 then exit for
next
PRINT "The smallest number whose square ends in 269696 is "; n
PRINT "Its square is "; n^2 |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #Rust | Rust | fn main() {
let mut current = 0;
while (current * current) % 1_000_000 != 269_696 {
current += 1;
}
println!(
"The smallest number whose square ends in 269696 is {}",
current
);
} |
http://rosettacode.org/wiki/Approximate_equality | Approximate equality | Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the
difference in floating point calculations between different language implementations becomes significant.
For example, a difference between 32 bit and 64 bit floating point calculations may appear by
about the 8th significant digit in base 10 arithmetic.
Task
Create a function which returns true if two floating point numbers are approximately equal.
The function should allow for differences in the magnitude of numbers, so that, for example,
100000000000000.01 may be approximately equal to 100000000000000.011,
even though 100.01 is not approximately equal to 100.011.
If the language has such a feature in its standard library, this may be used instead of a custom function.
Show the function results with comparisons on the following pairs of values:
100000000000000.01, 100000000000000.011 (note: should return true)
100.01, 100.011 (note: should return false)
10000000000000.001 / 10000.0, 1000000000.0000001000
0.001, 0.0010000001
0.000000000000000000000101, 0.0
sqrt(2) * sqrt(2), 2.0
-sqrt(2) * sqrt(2), -2.0
3.14159265358979323846, 3.14159265358979324
Answers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.
| #R | R | approxEq <- function(...) isTRUE(all.equal(...))
tests <- rbind(c(100000000000000.01, 100000000000000.011),
c(100.01, 100.011),
c(10000000000000.001 / 10000.0, 1000000000.0000001000),
c(0.001, 0.0010000001),
c(0.000000000000000000000101, 0.0),
c(sqrt(2) * sqrt(2), 2.0),
c(-sqrt(2) * sqrt(2), -2.0),
c(3.14159265358979323846, 3.14159265358979324))
results <- mapply(approxEq, tests[, 1], tests[, 2])
#All that remains is to print out our results in a presentable way:
printableTests <- format(tests, scientific = FALSE)
print(data.frame(x = printableTests[, 1], y = printableTests[, 2], Equal = results, row.names = paste0("Test ", 1:8, ": "))) |
http://rosettacode.org/wiki/Approximate_equality | Approximate equality | Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the
difference in floating point calculations between different language implementations becomes significant.
For example, a difference between 32 bit and 64 bit floating point calculations may appear by
about the 8th significant digit in base 10 arithmetic.
Task
Create a function which returns true if two floating point numbers are approximately equal.
The function should allow for differences in the magnitude of numbers, so that, for example,
100000000000000.01 may be approximately equal to 100000000000000.011,
even though 100.01 is not approximately equal to 100.011.
If the language has such a feature in its standard library, this may be used instead of a custom function.
Show the function results with comparisons on the following pairs of values:
100000000000000.01, 100000000000000.011 (note: should return true)
100.01, 100.011 (note: should return false)
10000000000000.001 / 10000.0, 1000000000.0000001000
0.001, 0.0010000001
0.000000000000000000000101, 0.0
sqrt(2) * sqrt(2), 2.0
-sqrt(2) * sqrt(2), -2.0
3.14159265358979323846, 3.14159265358979324
Answers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.
| #Racket | Racket | #lang racket
(define (≈ a b [tolerance 1e-9])
(<= (abs (/ (- a b) (max a b))) tolerance))
(define all-tests
`(([100000000000000.01 100000000000000.011]
[100.01 100.011]
[,(/ 10000000000000.001 10000.0) 1000000000.0000001000]
[0.001 0.0010000001]
[0.000000000000000000000101 0.0]
[,(* (sqrt 2) (sqrt 2)) 2.0]
[,(* (- (sqrt 2)) (sqrt 2)) -2.0]
[100000000000000003.0 100000000000000004.0]
[3.14159265358979323846 3.14159265358979324])
([#e100000000000000.01 #e100000000000000.011]
[#e100.01 #e100.011]
[,(/ #e10000000000000.001 #e10000.0) #e1000000000.0000001000]
[#e0.001 #e0.0010000001]
[#e0.000000000000000000000101 #e0.0]
[,(* (sqrt 2) (sqrt 2)) #e2.0]
[,(* (- (sqrt 2)) (sqrt 2)) #e-2.0]
[100000000000000003 100000000000000004]
[#e3.14159265358979323846 #e3.14159265358979324])))
(define (format-num x)
(~a (~r x #:precision 30) #:min-width 50 #:align 'right))
(for ([tests (in-list all-tests)] [name '("inexact" "exact")])
(printf "~a:\n" name)
(for ([test (in-list tests)])
(match-define (list a b) test)
(printf "~a ~a: ~a\n" (format-num a) (format-num b) (≈ a b)))
(newline)) |
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
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | matching?:
swap 0
for c in chars:
if = c "]":
++
elseif = c "[":
if not dup:
drop
return false
--
not
!. matching? ""
!. matching? "[]"
!. matching? "[][]"
!. matching? "[[][]]"
!. matching? "]["
!. matching? "][]["
!. matching? "[]][[]" |
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.
| #Free_Pascal | Free Pascal | {$mode objFPC}
{$longStrings on}
{$modeSwitch classicProcVars+}
uses
cTypes,
// for system call wrappers
unix;
const
passwdPath = '/tmp/passwd';
resourceString
advisoryLockFailed = 'Error: could not obtain advisory lock';
type
GECOS = object
fullname: string;
office: string;
extension: string;
homephone: string;
email: string;
function asString: string;
end;
entry = object
account: string;
password: string;
UID: cUInt;
GID: cUInt;
comment: GECOS;
directory: string;
shell: string;
function asString: string;
end;
function GECOS.asString: string;
const
separator = ',';
begin
with self do
begin
writeStr(result, fullname, separator, office, separator, extension,
separator, homephone, separator, email);
end;
end;
function entry.asString: string;
const
separator = ':';
begin
with self do
begin
writeStr(result, account, separator, password, separator, UID:1,
separator, GID:1, separator, comment.asString, separator, directory,
separator, shell);
end;
end;
procedure writeEntry(var f: text; const value: entry);
begin
writeLn(f, value.asString);
end;
procedure appendEntry(var f: text; const value: entry);
begin
// (re-)open for writing and immediately seek to EOF
append(f);
writeEntry(f, value);
end;
// === MAIN ==============================================================
var
passwd: text;
procedure releaseLock;
begin
// equivalent to `exitCode := exitCode + …`
inc(exitCode, fpFLock(passwd, lock_un));
end;
var
user: entry;
line: string;
begin
assign(passwd, passwdPath);
// open for reading
reset(passwd);
if fpFLock(passwd, lock_ex or lock_NB) <> 0 then
begin
writeLn(stdErr, advisoryLockFailed);
halt(1);
end;
addExitProc(releaseLock);
// reopen for _over_writing: immediately sets file size to 0
rewrite(passwd);
user.account := 'jsmith';
user.password := 'x';
user.UID := 1001;
user.GID := 1000;
user.comment.fullname := 'Joe Smith';
user.comment.office := 'Room 1007';
user.comment.extension := '(234)555-8917';
user.comment.homephone := '(234)555-0077';
user.comment.email := '[email protected]';
user.directory := '/home/jsmith';
user.shell := '/bin/bash';
appendEntry(passwd, user);
with user do
begin
account := 'jdoe';
password := 'x';
UID := 1002;
GID := 1000;
with comment do
begin
fullname := 'Jane Doe';
office := 'Room 1004';
extension := '(234)555-8914';
homephone := '(234)555-0044';
email := '[email protected]';
end;
directory := '/home/jdoe';
shell := '/bin/bash';
end;
appendEntry(passwd, user);
// Close the file, ...
close(passwd);
with user, user.comment do
begin
account := 'xyz';
UID := 1003;
fullname := 'X Yz';
office := 'Room 1003';
extension := '(234)555-8913';
homephone := '(234)555-0033';
email := '[email protected]';
directory := '/home/xyz';
end;
// ... then reopen the file for append.
appendEntry(passwd, user);
// open the file and demonstrate the new record has indeed written to the end
reset(passwd);
while not EOF(passwd) do
begin
readLn(passwd, line);
writeLn(line);
end;
end. |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #ATS | ATS | (*------------------------------------------------------------------*)
#define ATS_DYNLOADFLAG 0
#include "share/atspre_staload.hats"
(*------------------------------------------------------------------*)
(* Interface *)
(* You can put the interface in a .sats file. You will have to remove
the word "extern". *)
typedef alist_t (key_t : t@ype+,
data_t : t@ype+,
size : int) =
list (@(key_t, data_t), size)
typedef alist_t (key_t : t@ype+,
data_t : t@ype+) =
[size : int]
alist_t (key_t, data_t, size)
extern prfun
lemma_alist_t_param :
{size : int} {key_t : t@ype} {data_t : t@ype}
alist_t (key_t, data_t, size) -<prf> [0 <= size] void
extern fun {key_t : t@ype} (* Implement key equality with this. *)
alist_t$key_eq : (key_t, key_t) -<> bool
(* alist_t_nil: create an empty association list. *)
extern fun
alist_t_nil :
{key_t : t@ype} {data_t : t@ype}
() -<> alist_t (key_t, data_t, 0)
(* alist_t_set: add an association, deleting old associations with an
equal key. *)
extern fun {key_t : t@ype}
{data_t : t@ype}
alist_t_set {size : int}
(alst : alist_t (key_t, data_t, size),
key : key_t,
data : data_t) :<>
[sz : int | 1 <= sz]
alist_t (key_t, data_t, sz)
(* alist_t_get: find an association and return its data, if
present. *)
extern fun {key_t : t@ype}
{data_t : t@ype}
alist_t_get {size : int}
(alst : alist_t (key_t, data_t, size),
key : key_t) :<>
Option data_t
(* alist_t_delete: delete all associations with key. *)
extern fun {key_t : t@ype}
{data_t : t@ype}
alist_t_delete {size : int}
(alst : alist_t (key_t, data_t, size),
key : key_t ) :<>
[sz : int | 0 <= sz]
alist_t (key_t, data_t, sz)
(* alist_t_make_pairs_generator: make a closure that returns
the association pairs, one by one. This is a form of iterator.
Analogous generators can be made for the keys or data values
alone. *)
extern fun {key_t : t@ype}
{data_t : t@ype}
alist_t_make_pairs_generator
{size : int}
(alst : alist_t (key_t, data_t, size)) :<!wrt>
() -<cloref,!refwrt> Option @(key_t, data_t)
(*------------------------------------------------------------------*)
(* Implementation *)
#define NIL list_nil ()
#define :: list_cons
primplement
lemma_alist_t_param alst =
lemma_list_param alst
implement
alist_t_nil () =
NIL
implement {key_t} {data_t}
alist_t_set (alst, key, data) =
@(key, data) :: alist_t_delete (alst, key)
implement {key_t} {data_t}
alist_t_get (alst, key) =
let
fun
loop {n : nat}
.<n>. (* <-- proof of termination *)
(lst : alist_t (key_t, data_t, n)) :<>
Option data_t =
case+ lst of
| NIL => None ()
| head :: tail =>
if alist_t$key_eq (key, head.0) then
Some (head.1)
else
loop tail
prval _ = lemma_alist_t_param alst
in
loop alst
end
implement {key_t} {data_t}
alist_t_delete (alst, key) =
let
fun
delete {n : nat}
.<n>. (* <-- proof of termination *)
(lst : alist_t (key_t, data_t, n)) :<>
[m : nat] alist_t (key_t, data_t, m) =
(* This implementation is *not* tail recursive, but has the
minor advantage of preserving the order of entries without
doing a lot of work. *)
case+ lst of
| NIL => lst
| head :: tail =>
if alist_t$key_eq (key, head.0) then
delete tail
else
head :: delete tail
prval _ = lemma_alist_t_param alst
in
delete alst
end
implement {key_t} {data_t}
alist_t_make_pairs_generator alst =
let
typedef alist_t = [sz : int] alist_t (key_t, data_t, sz)
val alst_ref = ref alst
(* Cast the ref to a pointer so it can be enclosed in the
closure. *)
val alst_ptr = $UNSAFE.castvwtp0{ptr} alst_ref
in
lam () =>
let
val alst_ref = $UNSAFE.castvwtp0{ref alist_t} alst_ptr
in
case+ !alst_ref of
| NIL => None ()
| head :: tail =>
begin
!alst_ref := tail;
(* For a keys generator, change the following line to
"Some (head.0)"; for a data values generator, change
it to "Some (head.1)". *)
Some head
end
end
end
(*------------------------------------------------------------------*)
(* Demonstration program *)
implement
alist_t$key_eq<string> (s, t) =
s = t
typedef s2i_alist_t = alist_t (string, int)
fn
s2i_alist_t_set (map : s2i_alist_t,
key : string,
data : int) :<> s2i_alist_t =
alist_t_set<string><int> (map, key, data)
fn
s2i_alist_t_set_ref (map : &s2i_alist_t >> _,
key : string,
data : int) :<!wrt> void =
(* Update a reference to a persistent alist. *)
map := s2i_alist_t_set (map, key, data)
fn
s2i_alist_t_get (map : s2i_alist_t,
key : string) :<> Option int =
alist_t_get<string><int> (map, key)
extern fun {} (* {} = a template without template parameters *)
s2i_alist_t_get_dflt$dflt :<> () -> int
fn {} (* {} = a template without template parameters *)
s2i_alist_t_get_dflt (map : s2i_alist_t,
key : string) : int =
case+ s2i_alist_t_get (map, key) of
| Some x => x
| None () => s2i_alist_t_get_dflt$dflt<> ()
overload [] with s2i_alist_t_set_ref
overload [] with s2i_alist_t_get_dflt
implement
main0 () =
let
implement s2i_alist_t_get_dflt$dflt<> () = 0
var map = alist_t_nil ()
var gen : () -<cloref1> @(string, int)
var pair : Option @(string, int)
in
map["one"] := 1;
map["two"] := 2;
map["three"] := 3;
println! ("map[\"one\"] = ", map["one"]);
println! ("map[\"two\"] = ", map["two"]);
println! ("map[\"three\"] = ", map["three"]);
println! ("map[\"four\"] = ", map["four"]);
gen := alist_t_make_pairs_generator<string><int> map;
for (pair := gen (); option_is_some pair; pair := gen ())
println! (pair)
end
(*------------------------------------------------------------------*) |
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
| #CLU | CLU | % Count factors
factors = proc (n: int) returns (int)
if n<2 then return(1) end
count: int := 2
for i: int in int$from_to(2, n/2) do
if n//i = 0 then count := count + 1 end
end
return(count)
end factors
% Generate antiprimes
antiprimes = iter () yields (int)
max: int := 0
n: int := 1
while true do
f: int := factors(n)
if f > max then
yield(n)
max := f
end
n := n + 1
end
end antiprimes
% Show the first 20 antiprimes
start_up = proc ()
max = 20
po: stream := stream$primary_output()
count: int := 0
for i: int in antiprimes() do
stream$puts(po, int$unparse(i) || " ")
count := count + 1
if count = max then break end
end
end start_up |
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
| #COBOL | COBOL |
******************************************************************
* COBOL solution to Anti-primes challange
* The program was run on OpenCobolIDE
******************************************************************
IDENTIFICATION DIVISION.
PROGRAM-ID. ANGLE-PRIMES.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
77 ANTI-PRIMES-CTR PIC 9(3) VALUE 0.
77 FACTORS-CTR PIC 9(3) VALUE 0.
77 WS-INTEGER PIC 9(5) VALUE 1.
77 WS-MAX PIC 9(5) VALUE 0.
77 WS-I PIc 9(5) VALUE 0.
77 WS-LIMIT PIC 9(5) VALUE 1.
77 WS-REMAINDER PIC 9(5).
01 OUT-HDR PIC X(23) VALUE 'SEQ ANTI-PRIME FACTORS'.
01 OUT-LINE.
05 OUT-SEQ PIC 9(3).
05 FILLER PIC X(3) VALUE SPACES.
05 OUT-ANTI PIC ZZZZ9.
05 FILLER PIC X(4) VALUE SPACES.
05 OUT-FACTORS PIC ZZZZ9.
PROCEDURE DIVISION.
000-MAIN.
DISPLAY OUT-HDR.
PERFORM 100-GET-ANTI-PRIMES
VARYING WS-INTEGER FROM 1 By 1
UNTIL ANTI-PRIMES-CTR >= 20.
STOP RUN.
100-GET-ANTI-PRIMES.
SET FACTORS-CTR TO 0.
COMPUTE WS-LIMIT = 1 + WS-INTEGER ** .5.
PERFORM 200-COUNT-FACTORS
VARYING WS-I FROM 1 BY 1
UNTIL WS-I >= WS-LIMIT.
IF FACTORS-CTR > WS-MAX
ADD 1 TO ANTI-PRIMES-CTR
COMPUTE WS-MAX = FACTORS-CTR
MOVE ANTI-PRIMES-CTR TO OUT-SEQ
MOVE WS-INTEGER TO OUT-ANTI
MOVE FACTORS-CTR TO OUT-FACTORS
DISPLAY OUT-LINE
END-IF.
200-COUNT-FACTORS.
COMPUTE WS-REMAINDER =
FUNCTION MOD(WS-INTEGER WS-I).
IF WS-REMAINDER = ZERO
ADD 1 TO FACTORS-CTR
IF WS-INTEGER NOT = WS-I ** 2
ADD 1 TO FACTORS-CTR
END-IF
END-IF.
******************************************************************
* OUTPUT:
******************************************************************
* SEQ ANTI-PRIME FACTORS
* 001 1 1
* 002 2 2
* 003 4 3
* 004 6 4
* 005 12 6
* 006 24 8
* 007 36 9
* 008 48 10
* 009 60 12
* 010 120 16
* 011 180 18
* 012 240 20
* 013 360 24
* 014 720 30
* 015 840 32
* 016 1260 36
* 017 1680 40
* 018 2520 48
* 019 5040 60
* 020 7560 64
******************************************************************
|
http://rosettacode.org/wiki/Atomic_updates | Atomic updates |
Task
Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to:
get the current value of any bucket
remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the transferred amount to ensure the values remain non-negative
In order to exercise this data type, create one set of buckets, and start three concurrent tasks:
As often as possible, pick two buckets and make their values closer to equal.
As often as possible, pick two buckets and arbitrarily redistribute their values.
At whatever rate is convenient, display (by any means) the total value and, optionally, the individual values of each bucket.
The display task need not be explicit; use of e.g. a debugger or trace tool is acceptable provided it is simple to set up to provide the display.
This task is intended as an exercise in atomic operations. The sum of the bucket values must be preserved even if the two tasks attempt to perform transfers simultaneously, and a straightforward solution is to ensure that at any time, only one transfer is actually occurring — that the transfer operation is atomic.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | transfer[bucks_, src_, dest_, n_] :=
ReplacePart[
bucks, {src -> Max[bucks[[src]] - n, 0],
dest -> bucks[[dest]] + Min[bucks[[src]], n]}];
DistributeDefinitions[transfer];
SetSharedVariable[bucks, comp];
bucks = RandomInteger[10, 20];
comp = True;
Print["Original sum: " <> IntegerString[Plus @@ bucks]];
Print[Dynamic["Current sum: " <> IntegerString[Plus @@ bucks]]];
WaitAll[{ParallelSubmit[
While[True, While[! comp, Null]; comp = False;
Module[{a = RandomInteger[{1, 20}], b = RandomInteger[{1, 20}]},
bucks = transfer[bucks, Max[a, b], Min[a, b],
Floor[Abs[bucks[[a]] - bucks[[b]]]/2]]]; comp = True]],
ParallelSubmit[
While[True, While[! comp, Null]; comp = False;
Module[{src = RandomInteger[{1, 20}],
dest = RandomInteger[{1, 20}]},
bucks = transfer[bucks, src, dest,
RandomInteger[{1, bucks[[src]]}]]]; comp = True]]}]; |
http://rosettacode.org/wiki/Atomic_updates | Atomic updates |
Task
Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to:
get the current value of any bucket
remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the transferred amount to ensure the values remain non-negative
In order to exercise this data type, create one set of buckets, and start three concurrent tasks:
As often as possible, pick two buckets and make their values closer to equal.
As often as possible, pick two buckets and arbitrarily redistribute their values.
At whatever rate is convenient, display (by any means) the total value and, optionally, the individual values of each bucket.
The display task need not be explicit; use of e.g. a debugger or trace tool is acceptable provided it is simple to set up to provide the display.
This task is intended as an exercise in atomic operations. The sum of the bucket values must be preserved even if the two tasks attempt to perform transfers simultaneously, and a straightforward solution is to ensure that at any time, only one transfer is actually occurring — that the transfer operation is atomic.
| #Nim | Nim | import locks
import math
import os
import random
const N = 10 # Number of buckets.
const MaxInit = 99 # Maximum initial value for buckets.
var buckets: array[1..N, Natural] # Array of buckets.
var bucketLocks: array[1..N, Lock] # Array of bucket locks.
var randomLock: Lock # Lock to protect the random number generator.
var terminate: array[3, Channel[bool]] # Used to ask threads to terminate.
#---------------------------------------------------------------------------------------------------
proc getTwoIndexes(): tuple[a, b: int] =
## Get two indexes from the random number generator.
result.a = rand(1..N)
result.b = rand(2..N)
if result.b == result.a: result.b = 1
#---------------------------------------------------------------------------------------------------
proc equalize(num: int) {.thread.} =
## Try to equalize two buckets.
var b1, b2: int # Bucket indexes.
while true:
# Select the two buckets to "equalize".
withLock randomLock:
(b1, b2) = getTwoIndexes()
if b1 > b2: swap b1, b2 # We want "b1 < b2" to avoid deadlocks.
# Perform equalization.
withLock bucketLocks[b1]:
withLock bucketLocks[b2]:
let target = (buckets[b1] + buckets[b2]) div 2
let delta = target - buckets[b1]
inc buckets[b1], delta
dec buckets[b2], delta
# Check termination.
let (available, stop) = tryRecv terminate[num]
if available and stop: break
#---------------------------------------------------------------------------------------------------
proc distribute(num: int) {.thread.} =
## Redistribute contents of two buckets.
var b1, b2: int # Bucket indexes.
var factor: float # Ratio used to compute the new value for "b1".
while true:
# Select the two buckets for redistribution and the redistribution factor.
withLock randomLock:
(b1, b2) = getTwoIndexes()
factor = rand(0.0..1.0)
if b1 > b2: swap b1, b2 # We want "b1 < b2" to avoid deadlocks..
# Perform redistribution.
withLock bucketLocks[b1]:
withLock bucketLocks[b2]:
let sum = buckets[b1] + buckets[b2]
let value = (sum.toFloat * factor).toInt
buckets[b1] = value
buckets[b2] = sum - value
# Check termination.
let (available, stop) = tryRecv terminate[num]
if available and stop: break
#---------------------------------------------------------------------------------------------------
proc display(num: int) {.thread.} =
## Display the content of buckets and the sum (which should be constant).
while true:
for i in 1..N: acquire bucketLocks[i]
echo buckets, " Total = ", sum(buckets)
for i in countdown(N, 1): release bucketLocks[i]
os.sleep(1000)
# Check termination.
let (available, stop) = tryRecv terminate[num]
if available and stop: break
#———————————————————————————————————————————————————————————————————————————————————————————————————
randomize()
# Initialize the buckets with a random value.
for bucket in buckets.mitems:
bucket = rand(1..MaxInit)
# Initialize the locks.
randomLock.initLock()
for lock in bucketLocks.mitems:
lock.initLock()
# Open the channels.
for c in terminate.mitems:
c.open()
# Create and launch the threads.
var tequal, tdist, tdisp: Thread[int]
tequal.createThread(equalize, 0)
tdist.createThread(distribute, 1)
tdisp.createThread(display, 2)
sleep(10000)
# Ask the threads to stop.
for c in terminate.mitems:
c.send(true)
joinThreads([tequal, tdist, tdisp])
# Free resources.
randomLock.deinitLock()
for lock in bucketLocks.mitems:
lock.deinitLock()
for c in terminate.mitems:
c.close() |
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.
| #jq | jq | SHELL SET UNSET
sh bash (etc) export JQ_ASSERT=1 unset JQ_ASSERT
fish set -x JQ_ASSERT 1 set -u JQ_ASSERT
csh, tcsh setenv JQ_ASSERT 1 unsetenv JQ_ASSERT
Windows/DOS SET JQ_ASSERT=1 set JQ_ASSERT=
Windows: Start > Control Panel > System > Advanced > Environment Variables
|
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.
| #Julia | Julia | const x = 5
# @assert macro checks the supplied conditional expression, with the expression
# returned in the failed-assertion message
@assert x == 42
# ERROR: LoadError: AssertionError: x == 42
# Julia also has type assertions of the form, x::Type which can be appended to
# variable for type-checking at any point
x::String
# ERROR: LoadError: TypeError: in typeassert, expected String, got Int64
|
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.
| #Kotlin | Kotlin | fun main() {
val a = 42
assert(a == 43)
} |
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.
| #Lasso | Lasso | local(a) = 8
fail_if(
#a != 42,
error_code_runtimeAssertion,
error_msg_runtimeAssertion + ": #a is not 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.
| #C.2B.2B | C++ | #include <iostream> //cout for printing
#include <algorithm> //for_each defined here
//create the function (print the square)
void print_square(int i) {
std::cout << i*i << " ";
}
int main() {
//create the array
int ary[]={1,2,3,4,5};
//stl for_each
std::for_each(ary,ary+5,print_square);
return 0;
}
//prints 1 4 9 16 25 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.