task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#CoffeeScript
CoffeeScript
  map = (arr, f) -> (f(e) for e in arr) arr = [1, 2, 3, 4, 5] f = (x) -> x * x console.log map arr, f # prints [1, 4, 9, 16, 25]  
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
#PARI.2FGP
PARI/GP
mode(v)={ my(count=1,r=1,b=v[1]); v=vecsort(v); for(i=2,#v, if(v[i]==v[i-1], count++ , if(count>r, r=count; b=v[i-1] ); count=1 ) ); if(count>r,v[#v],b) };
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked 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
#Dyalect
Dyalect
var t = (x: 1, y: 2, z: 3)   for x in t.Keys() { print("\(x)=\(t[x])") }
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked 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
#E
E
def map := [ "a" => 1, "b" => 2, "c" => 3, ]   for key => value in map { println(`$key $value`) }   for value in map { # ignore keys println(`. $value`) }   for key => _ in map { # ignore values println(`$key .`) }   for key in map.domain() { # iterate over the set whose values are the keys println(`$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]
#Phix
Phix
with javascript_semantics function direct_form_II_transposed_filter(sequence a, b, signal) sequence result = repeat(0,length(signal)) for i=1 to length(signal) do atom tmp = 0 for j=1 to min(i,length(b)) do tmp += b[j]*signal[i-j+1] end for for j=2 to min(i,length(a)) do tmp -= a[j]*result[i-j+1] end for result[i] = tmp/a[1] end for return result end function constant 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} pp(direct_form_II_transposed_filter(acoef, bcoef, signal),{pp_FltFmt,"%9.6f",pp_Maxlen,110})
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
#Elixir
Elixir
defmodule Average do def mean(list), do: Enum.sum(list) / length(list) end
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#Emacs_Lisp
Emacs Lisp
(defun mean (lst) (/ (float (apply '+ lst)) (length lst))) (mean '(1 2 3 4))
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%)
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i";   const integer: TESTS is 1000000;   const func float: factorial (in integer: number) is func result var float: factorial is 1.0; local var integer: i is 0; begin for i range 2 to number do factorial *:= flt(i); end for; end func;   const func float: analytical (in integer: number) is func result var float: sum is 0.0; local var integer: i is 0; begin for i range 1 to number do sum +:= factorial(number) / factorial(number - i) / flt(number)**i; end for; end func;   const func float: experimental (in integer: number) is func result var float: experimental is 0.0; local var integer: run is 0; var set of integer: seen is EMPTY_SET; var integer: current is 1; var integer: count is 0; begin for run range 1 to TESTS do current := 1; seen := EMPTY_SET; while current not in seen do incr(count); incl(seen, current); current := rand(1, number); end while; end for; experimental := flt(count) / flt(TESTS); end func;   const proc: main is func local var integer: number is 0; var float: analytical is 0.0; var float: experimental is 0.0; var float: err is 0.0; begin writeln(" N avg calc  %diff"); for number range 1 to 20 do analytical := analytical(number); experimental := experimental(number); err := abs(experimental - analytical) / analytical * 100.0; writeln(number lpad 2 <& experimental digits 4 lpad 7 <& analytical digits 4 lpad 7 <& err digits 3 lpad 7); end for; end func;
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%)
#Sidef
Sidef
func find_loop(n) { var seen = Hash() loop { with (irand(1, n)) { |r| seen.has(r) ? (return seen.len) : (seen{r} = true) } } }   print " N empiric theoric (error)\n"; print "=== ========= ============ =========\n";   define MAX = 20 define TRIALS = 1000   for n in (1..MAX) { var empiric = (1..TRIALS -> sum { find_loop(n) } / TRIALS) var theoric = (1..n -> sum {|k| prod(n - k + 1 .. n) * k**2 / n**(k+1) })   printf("%3d  %9.4f  %12.4f (%5.2f%%)\n", n, empiric, theoric, 100*(empiric-theoric)/theoric) }
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
#TI-83_BASIC
TI-83 BASIC
:1->C :While 1 :Prompt I :C->dim(L1) :I->L1(C) :Disp mean(L1) :1+C->C :End
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.
#Nanoquery
Nanoquery
MAX = 120   def is_prime(n) d = 5 if (n < 2) return false end if (n % 2) = 0 return n = 2 end if (n % 3) = 0 return n = 3 end   while (d * d) <= n if n % d = 0 return false end d += 2 if n % d = 0 return false end d += 4 end   return true end   def count_prime_factors(n) count = 0; f = 2 if n = 1 return 0 end if is_prime(n) return 1 end   while true if (n % f) = 0 count += 1 n /= f if n = 1 return count end if is_prime(n) f = n end else if f >= 3 f += 2 else f = 3 end end end   i = 0; n = 0; count = 0 println format("The attractive numbers up to and including %d are:\n", MAX) for i in range(1, MAX) n = count_prime_factors(i) if is_prime(n) print format("%4d", i) count += 1 if (count % 20) = 0 println end end end println
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.
#NewLisp
NewLisp
  (define (prime? n) (= (length (factor n)) 1)) (define (attractive? n) (prime? (length (factor n)))) ; (filter attractive? (sequence 2 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
#Python
Python
from cmath import rect, phase from math import radians, degrees     def mean_angle(deg): return degrees(phase(sum(rect(1, radians(d)) for d in deg)/len(deg)))   def mean_time(times): t = (time.split(':') for time in times) seconds = ((float(s) + int(m) * 60 + int(h) * 3600) for h, m, s in t) day = 24 * 60 * 60 to_angles = [s * 360. / day for s in seconds] mean_as_angle = mean_angle(to_angles) mean_seconds = mean_as_angle * day / 360. if mean_seconds < 0: mean_seconds += day h, m = divmod(mean_seconds, 3600) m, s = divmod(m, 60) return '%02i:%02i:%02i' % (h, m, s)     if __name__ == '__main__': print( mean_time(["23:00:17", "23:40:20", "00:12:45", "00: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.
#Tcl
Tcl
package require TclOO   namespace eval AVL { # Class for the overall tree; manages real public API oo::class create Tree { variable root nil class constructor {{nodeClass AVL::Node}} { set class [oo::class create Node [list superclass $nodeClass]]   # Create a nil instance to act as a leaf sentinel set nil [my NewNode ""] set root [$nil ref]   # Make nil be special oo::objdefine $nil { method height {} {return 0} method key {} {error "no key possible"} method value {} {error "no value possible"} method destroy {} { # Do nothing (doesn't prohibit destruction entirely) } method print {indent increment} { # Do nothing } } }   # How to actually manufacture a new node method NewNode {key} { if {![info exists nil]} {set nil ""} $class new $key $nil [list [namespace current]::my NewNode] }   # Create a new node in the tree and return it method insert {key} { set node [my NewNode $key] if {$root eq $nil} { set root $node } else { $root insert $node } return $node }   # Find the node for a particular key method lookup {key} { for {set node $root} {$node ne $nil} {} { if {[$node key] == $key} { return $node } elseif {[$node key] > $key} { set node [$node left] } else { set node [$node right] } } error "no such node" }   # Print a tree out, one node per line method print {{indent 0} {increment 1}} { $root print $indent $increment return } }   # Class of an individual node; may be subclassed oo::class create Node { variable key value left right 0 refcount newNode constructor {n nil instanceFactory} { set newNode $instanceFactory set 0 [expr {$nil eq "" ? [self] : $nil}] set key $n set value {} set left [set right $0] set refcount 0 } method ref {} { incr refcount return [self] } method destroy {} { if {[incr refcount -1] < 1} next } method New {key value} { set n [{*}$newNode $key] $n setValue $value return $n }   # Getters method key {} {return $key} method value {} {return $value} method left {} {return $left} method right {args} {return $right}   # Setters method setValue {newValue} { set value $newValue } method setLeft {node} { # Non-trivial because of reference management $node ref $left destroy set left $node return } method setRight {node} { # Non-trivial because of reference management $node ref $right destroy set right $node return }   # Print a node and its descendents method print {indent increment} { puts [format "%s%s => %s" [string repeat " " $indent] $key $value] incr indent $increment $left print $indent $increment $right print $indent $increment }   method height {} { return [expr {max([$left height], [$right height]) + 1}] } method balanceFactor {} { expr {[$left height] - [$right height]} }   method insert {node} { # Simple insertion if {$key > [$node key]} { if {$left eq $0} { my setLeft $node } else { $left insert $node } } else { if {$right eq $0} { my setRight $node } else { $right insert $node } }   # Rebalance this node if {[my balanceFactor] > 1} { if {[$left balanceFactor] < 0} { $left rotateLeft } my rotateRight } elseif {[my balanceFactor] < -1} { if {[$right balanceFactor] > 0} { $right rotateRight } my rotateLeft } }   # AVL Rotations method rotateLeft {} { set new [my New $key $value] set key [$right key] set value [$right value] $new setLeft $left $new setRight [$right left] my setLeft $new my setRight [$right right] }   method rotateRight {} { set new [my New $key $value] set key [$left key] set value [$left value] $new setLeft [$left right] $new setRight $right my setLeft [$left left] my setRight $new } } }
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
#Processing
Processing
void setup() { println(meanAngle(350, 10)); println(meanAngle(90, 180, 270, 360)); println(meanAngle(10, 20, 30)); }   float meanAngle(float... angles) { float sum1 = 0, sum2 = 0; for (int i = 0; i < angles.length; i++) { sum1 += sin(radians(angles[i])) / angles.length; sum2 += cos(radians(angles[i])) / angles.length; } return degrees(atan2(sum1, sum2)); }
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
#PureBasic
PureBasic
NewList angle.d()   Macro AE(x) AddElement(angle()) : angle()=x EndMacro   Procedure.d atan3(y.d,x.d) If x<=0.0 : ProcedureReturn Sign(y)*#PI/2 : EndIf If x>0.0  : ProcedureReturn ATan(y/x)  : EndIf If y>0.0  : ProcedureReturn ATan(y/x)+#PI : EndIf ProcedureReturn ATan(y/x)-#PI EndProcedure   Procedure.d mAngle(List angle.d()) Define.d sumS,sumC ForEach angle() sumS+Sin(Radian(angle())) : sumC+Cos(Radian(angle())) Next ProcedureReturn Degree(atan3(sumS,sumC)) EndProcedure   AE(350.0) : AE(10.0) Debug StrD(mAngle(angle()),6) : ClearList(angle())   AE(90.0) : AE(180.0) : AE(270.0) : AE(360.0) Debug StrD(mAngle(angle()),6) : ClearList(angle())   AE(10.0) : AE(20.0) : AE(30.0) Debug StrD(mAngle(angle()),6) : ClearList(angle())  
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
#Haskell
Haskell
import Data.List (partition)   nth :: Ord t => [t] -> Int -> t nth (x:xs) n | k == n = x | k > n = nth ys n | otherwise = nth zs $ n - k - 1 where (ys, zs) = partition (< x) xs k = length ys   medianMay :: (Fractional a, Ord a) => [a] -> Maybe a medianMay xs | n < 1 = Nothing | even n = Just ((nth xs (div n 2) + nth xs (div n 2 - 1)) / 2.0) | otherwise = Just (nth xs (div n 2)) where n = length xs   main :: IO () main = mapM_ (printMay . medianMay) [[], [7], [5, 3, 4], [5, 4, 2, 3], [3, 4, 1, -8.4, 7.2, 4, 1, 1.2]] where printMay = maybe (putStrLn "(not defined)") print
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of 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
#Logo
Logo
to compute_means :count local "sum make "sum 0 local "product make "product 1 local "reciprocal_sum make "reciprocal_sum 0   repeat :count [ make "sum sum :sum repcount make "product product :product repcount make "reciprocal_sum sum :reciprocal_sum (quotient repcount) ]   output (sentence (quotient :sum :count) (power :product (quotient :count)) (quotient :count :reciprocal_sum)) end   make "means compute_means 10 print sentence [Arithmetic mean is] item 1 :means print sentence [Geometric mean is] item 2 :means print sentence [Harmonic mean is] item 3 :means bye
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.
#Scala
Scala
  object TernaryBit { val P = TernaryBit(+1) val M = TernaryBit(-1) val Z = TernaryBit( 0)   implicit def asChar(t: TernaryBit): Char = t.charValue implicit def valueOf(c: Char): TernaryBit = { c match { case '0' => 0 case '+' => 1 case '-' => -1 case nc => throw new IllegalArgumentException("Illegal ternary symbol " + nc) } } implicit def asInt(t: TernaryBit): Int = t.intValue implicit def valueOf(i: Int): TernaryBit = TernaryBit(i) }   case class TernaryBit(val intValue: Int) {   def inverse: TernaryBit = TernaryBit(-intValue)   def charValue = intValue match { case 0 => '0' case 1 => '+' case -1 => '-' } }   class Ternary(val bits: List[TernaryBit]) {   def + (b: Ternary) = { val sumBits: List[Int] = bits.map(_.intValue).zipAll(b.bits.map(_.intValue), 0, 0).map(p => p._1 + p._2)   // normalize val iv: Tuple2[List[Int], Int] = (List(), 0) val (revBits, carry) = sumBits.foldLeft(iv)((accu: Tuple2[List[Int], Int], e: Int) => { val s = e + accu._2 (((s + 1 + 3 * 100) % 3 - 1) :: accu._1 , (s + 1 + 3 * 100) / 3 - 100) })   new Ternary(( TernaryBit(carry) :: revBits.map(TernaryBit(_))).reverse ) }   def - (b: Ternary) = {this + (-b)} def <<<(a: Int): Ternary = { List.fill(a)(TernaryBit.Z) ++ bits} def >>>(a: Int): Ternary = { bits.drop(a) } def unary_- = { bits.map(_.inverse) }   def ** (b: TernaryBit): Ternary = { b match { case TernaryBit.P => this case TernaryBit.M => - this case TernaryBit.Z => 0 } }   def * (mul: Ternary): Ternary = { // might be done more efficiently - perform normalize only once mul.bits.reverse.foldLeft(new Ternary(Nil))((a: Ternary, b: TernaryBit) => (a <<< 1) + (this ** b)) }   def intValue = bits.foldRight(0)((c, a) => a*3 + c.intValue)   override def toString = new String(bits.reverse.map(_.charValue).toArray) }   object Ternary {   implicit def asString(t: Ternary): String = t.toString() implicit def valueOf(s: String): Ternary = new Ternary(s.toList.reverse.map(TernaryBit.valueOf(_)))   implicit def asBits(t: Ternary): List[TernaryBit] = t.bits implicit def valueOf(l: List[TernaryBit]): Ternary = new Ternary(l)   implicit def asInt(t: Ternary): BigInt = t.intValue // XXX not tail recursive implicit def valueOf(i: BigInt): Ternary = { if (i < 0) -valueOf(-i) else if (i == 0) new Ternary(List()) else if (i % 3 == 0) TernaryBit.Z :: valueOf(i / 3) else if (i % 3 == 1) TernaryBit.P :: valueOf(i / 3) else /*(i % 3 == 2)*/ TernaryBit.M :: valueOf((i + 1) / 3) } implicit def intToTernary(i: Int): Ternary = valueOf(i) }  
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.
#SenseTalk
SenseTalk
  (* Answer Charles Babbage's question: What is the smallest positive integer whose square ends in the digits 269,696? *)   put 1 into int   repeat forever if int squared ends with "269696" then put "The smallest positive integer whose square ends in the digits 269696 is" && int exit all -- don't keep repeating forever! end if   add 1 to int end repeat    
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.
#SequenceL
SequenceL
main() := babbage(0);   babbage(current) := current when current * current mod 1000000 = 269696 else babbage(current + 1);
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.
#Smalltalk
Smalltalk
{ #(100000000000000.01 100000000000000.011) . #(100.01 100.011) . {10000000000000.001 / 10000.0 . 1000000000.0000001000} . #(0.001 0.0010000001) . #(0.000000000000000000000101 0.0) . { 2 sqrt * 2 sqrt . 2.0} . { 2 sqrt negated * 2 sqrt . -2.0} . #(3.14159265358979323846 3.14159265358979324) } pairsDo:[:val1 :val2 | Stdout printCR: e'{val1} =~= {val2} -> {val1 isAlmostEqualTo:val2 nEpsilon:2}' ]
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.
#Swift
Swift
import Foundation   extension FloatingPoint { @inlinable public func isAlmostEqual( to other: Self, tolerance: Self = Self.ulpOfOne.squareRoot() ) -> Bool { // tolerances outside of [.ulpOfOne,1) yield well-defined but useless results, // so this is enforced by an assert rathern than a precondition. assert(tolerance >= .ulpOfOne && tolerance < 1, "tolerance should be in [.ulpOfOne, 1).")   // The simple computation below does not necessarily give sensible // results if one of self or other is infinite; we need to rescale // the computation in that case. guard self.isFinite && other.isFinite else { return rescaledAlmostEqual(to: other, tolerance: tolerance) }   // This should eventually be rewritten to use a scaling facility to be // defined on FloatingPoint suitable for hypot and scaled sums, but the // following is good enough to be useful for now. let scale = max(abs(self), abs(other), .leastNormalMagnitude) return abs(self - other) < scale*tolerance }   @usableFromInline internal func rescaledAlmostEqual(to other: Self, tolerance: Self) -> Bool { // NaN is considered to be not approximately equal to anything, not even // itself. if self.isNaN || other.isNaN { return false } if self.isInfinite { if other.isInfinite { return self == other }   // Self is infinite and other is finite. Replace self with the binade // of the greatestFiniteMagnitude, and reduce the exponent of other by // one to compensate. let scaledSelf = Self(sign: self.sign, exponent: Self.greatestFiniteMagnitude.exponent, significand: 1) let scaledOther = Self(sign: .plus, exponent: -1, significand: other)   // Now both values are finite, so re-run the naive comparison. return scaledSelf.isAlmostEqual(to: scaledOther, tolerance: tolerance) }   // If self is finite and other is infinite, flip order and use scaling // defined above, since this relation is symmetric. return other.rescaledAlmostEqual(to: self, tolerance: tolerance) } }   let testCases = [ (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), (3.14159265358979323846, 3.14159265358979324) ]   for testCase in testCases { print("\(testCase.0), \(testCase.1) => \(testCase.0.isAlmostEqual(to: testCase.1))") }
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.
#Tcl
Tcl
catch {namespace delete test_almost_equal_decimal} ;# Start with a clean namespace   namespace eval test_almost_equal_decimal { package require Tcl 8.5 ;# required by tcllib package require math::decimal ;# from tcllib namespace import ::math::decimal::* ;# for: setVariable, fromstr, and compare   array set yesno {0 Yes -1 No 1 No} ;# For nice output   # More info here: http://speleotrove.com/decimal/dax3274.html # This puts the library into "simplified" mode. Which # rounds the "decimal digits" in the coefficient to the # number of digits that "precision" is set to. setVariable extended 0 setVariable precision 9   set data { {100000000000000.01 100000000000000.011} {100.01 100.011} {[expr {10000000000000.001 / 10000.0}] 1000000000.0000001000} {0.001 0.0010000001} {0.000000000000000000000101 0.0} {[expr { sqrt(2) * sqrt(2)}] 2.0} {[expr {-sqrt(2) * sqrt(2)}] -2.0} {3.14159265358979323846 3.14159265358979324} } set data [subst $data] ;# resolves expressions in the list   foreach {a b} [join $data] { set a_d [fromstr $a] set b_d [fromstr $b]   puts [format "Is %26s ≈ %21s ? %4s." $a $b $yesno([compare $a_d $b_d])] } }  
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
#Erlang
Erlang
  -module( balanced_brackets ). -export( [generate/1, is_balanced/1, task/0] ).   generate( N ) -> [generate_bracket(random:uniform()) || _X <- lists:seq(1, 2*N)].   is_balanced( String ) -> is_balanced_loop( String, 0 ).   task() -> lists:foreach( fun (N) -> String = generate( N ), Result = is_balanced( String ), io:fwrite( "~s is ~s~n", [String, task_balanced(Result)] ) end, lists:seq(0, 5) ).       is_balanced_loop( _String, N ) when N < 0 -> false; is_balanced_loop( [], 0 ) -> true; is_balanced_loop( [], _N ) -> false; is_balanced_loop( [$[ | T], N ) -> is_balanced_loop( T, N + 1 ); is_balanced_loop( [$] | T], N ) -> is_balanced_loop( T, N - 1 ).   generate_bracket( N ) when N =< 0.5 -> $[; generate_bracket( N ) when N > 0.5 -> $].   task_balanced( true ) -> "OK"; task_balanced( false ) -> "NOT OK".  
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.
#Icon_and_Unicon
Icon and Unicon
procedure main() orig := [ "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash", "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jsmith:/bin/bash" ] new := [ "xyz:x:1003:1000:X:Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash" ] fName := !open("mktemp","rp") every (f := open(fName,"w")) | write(f,!orig) | close(f) every (f := open(fName,"a")) | write(f,!new) | close(f) every (f := open(fName,"r")) | write(!f) | 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
#Babel
Babel
  (("foo" 13) ("bar" 42) ("baz" 77)) ls2map !
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
#Elixir
Elixir
defmodule AntiPrimes do def divcount(n) when is_integer(n), do: divcount(n, 1, 0)   def divcount(n, d, count) when d * d > n, do: count def divcount(n, d, count) do divs = case rem(n, d) do 0 -> case n - d * d do 0 -> 1 _ -> 2 end _ -> 0 end divcount(n, d + 1, count + divs) end   def antiprimes(n), do: antiprimes(n, 1, 0, [])   def antiprimes(0, _, _, l), do: Enum.reverse(l) def antiprimes(n, m, max, l) do count = divcount(m) case count > max do true -> antiprimes(n-1, m+1, count, [m|l]) false -> antiprimes(n, m+1, max, l) end end   def main() do :io.format("The first 20 anti-primes are ~w~n", [antiprimes(20)]) end 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
#Erlang
Erlang
divcount(N) -> divcount(N, 1, 0).   divcount(N, D, Count) when D*D > N -> Count; divcount(N, D, Count) -> Divs = case N rem D of 0 -> case N - D*D of 0 -> 1; _ -> 2 end; _ -> 0 end, divcount(N, D + 1, Count + Divs).     antiprimes(N) -> antiprimes(N, 1, 0, []).   antiprimes(0, _, _, L) -> lists:reverse(L); antiprimes(N, M, Max, L) -> Count = divcount(M), case Count > Max of true -> antiprimes(N-1, M+1, Count, [M|L]); false -> antiprimes(N, M+1, Max, L) end.     main(_) -> io:format("The first 20 anti-primes are ~w~n", [antiprimes(20)]).  
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.
#Phix
Phix
without js -- (no threads or critical sections in JavaScript) constant nBuckets = 20 sequence buckets = tagset(nBuckets) -- {1,2,3,..,20} constant bucket_cs = init_cs() -- critical section atom equals = 0, rands = 0 -- operation counts integer terminate = 0 -- control flag procedure mythreads(integer eq) -- if eq then equalise else randomise integer b1,b2,amt while not terminate do b1 = rand(nBuckets) b2 = rand(nBuckets) if b1!=b2 then -- (test not actually needed) enter_cs(bucket_cs) if eq then amt = floor((buckets[b1]-buckets[b2])/2) equals += 1 else amt = rand(buckets[b1]+1)-1 rands += 1 end if buckets[b1] -= amt buckets[b2] += amt leave_cs(bucket_cs) end if end while exit_thread(0) end procedure procedure display() enter_cs(bucket_cs) ?{sum(buckets),equals,rands,buckets} leave_cs(bucket_cs) end procedure display() constant threads = {create_thread(routine_id("mythreads"),{1}), -- equalise create_thread(routine_id("mythreads"),{0})} -- randomise constant ESC = #1B while not find(get_key(),{ESC,'q','Q'}) do sleep(1) display() end while terminate = 1 wait_thread(threads) delete_cs(bucket_cs)
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.
#Modula-3
Modula-3
<*ASSERT a = 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.
#Nanoquery
Nanoquery
a = 5 assert (a = 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.
#Nemerle
Nemerle
assert (foo == 42, $"foo == $foo, not 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.
#NGS
NGS
a = 42   assert(a==42) assert(a, 42) assert(a==42, "Not 42!") assert(a, 42, "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.
#Common_Lisp
Common Lisp
(map nil #'print #(1 2 3 4 5))
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Component_Pascal
Component Pascal
  MODULE Callback; IMPORT StdLog;   TYPE Callback = PROCEDURE (x: INTEGER;OUT doubled: INTEGER); Callback2 = PROCEDURE (x: INTEGER): INTEGER;   PROCEDURE Apply(proc: Callback; VAR x: ARRAY OF INTEGER); VAR i: INTEGER; BEGIN FOR i := 0 TO LEN(x) - 1 DO; proc(x[i],x[i]); END END Apply;   PROCEDURE Apply2(func: Callback2; VAR x: ARRAY OF INTEGER); VAR i: INTEGER; BEGIN FOR i := 0 TO LEN(x) - 1 DO; x[i] := func(x[i]); END END Apply2;   PROCEDURE Double(x: INTEGER; OUT y: INTEGER); BEGIN y := x * x; END Double;   PROCEDURE Double2(x: INTEGER): INTEGER; BEGIN RETURN x * x END Double2;   PROCEDURE Do*; VAR i: INTEGER; ary: ARRAY 10 OF INTEGER;     BEGIN FOR i := 0 TO LEN(ary) - 1 DO ary[i] := i END; Apply(Double,ary); FOR i := 0 TO LEN(ary) - 1 DO StdLog.Int(ary[i]);StdLog.Ln END; StdLog.Ln; Apply2(Double2,ary); FOR i := 0 TO LEN(ary) - 1 DO StdLog.Int(ary[i]);StdLog.Ln END END Do; END Callback.  
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
#Perl
Perl
use strict; use List::Util qw(max);   sub mode { my %c; foreach my $e ( @_ ) { $c{$e}++; } my $best = max(values %c); return grep { $c{$_} == $best } keys %c; }
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
#EchoLisp
EchoLisp
  (lib 'hash) ;; load hash.lib (define H (make-hash)) ;; fill hash table (hash-set H 'Simon 42) (hash-set H 'Albert 666) (hash-set H 'Antoinette 33)   ;; iterate over (key . value ) pairs (for ([kv H]) (writeln kv)) (Simon . 42) (Albert . 666) (Antoinette . 33)   ;; iterate over keys (for ([k (hash-keys H)]) (writeln 'key-> k)) key-> Simon key-> Albert key-> Antoinette   ;; iterate over values (for ([v (hash-values H)]) (writeln 'value-> v)) value-> 42 value-> 666 value-> 33  
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]
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   ( 1.00000000 -2.77555756e-16 3.33333333e-01 -1.85037171e-17 ) var a ( 0.16666667 0.5 0.5 0.16666667 ) var b ( -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 )   len dup 0 swap repeat >ps   for var i 0 >ps b len i min for var j j get rot i j - 1 + get rot * ps> + >ps swap endfor drop a len i min for var j j get ps> tps i j - 1 + get nip rot * - >ps endfor drop ps> a 1 get nip / ps> swap i set >ps endfor drop ps> ?
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]
#Python
Python
#!/bin/python from __future__ import print_function from scipy import signal import matplotlib.pyplot as plt   if __name__=="__main__": 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]   #Create an order 3 lowpass butterworth filter #Generated using b, a = signal.butter(3, 0.5) a = [1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] b = [0.16666667, 0.5, 0.5, 0.16666667]   #Apply the filter to signal filt = signal.lfilter(b, a, sig) print (filt)   plt.plot(sig, 'b') plt.plot(filt, 'r--') plt.show()
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
#Erlang
Erlang
mean([]) -> 0; mean(L) -> lists:sum(L)/erlang:length(L).
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%)
#Simula
Simula
BEGIN   REAL PROCEDURE FACTORIAL(N); INTEGER N; BEGIN REAL RESULT; INTEGER I; RESULT := 1.0; FOR I := 2 STEP 1 UNTIL N DO RESULT := RESULT * I; FACTORIAL := RESULT; END FACTORIAL;   REAL PROCEDURE ANALYTICAL (N); INTEGER N; BEGIN REAL SUM, RN; INTEGER I; RN := N; FOR I := 1 STEP 1 UNTIL N DO BEGIN SUM := SUM + FACTORIAL(N) / FACTORIAL(N - I) / RN ** I; END; ANALYTICAL := SUM; END ANALYTICAL;   REAL PROCEDURE EXPERIMENTAL(N); INTEGER N; BEGIN INTEGER NUM; INTEGER COUNT; INTEGER RUN; FOR RUN := 1 STEP 1 UNTIL TESTS DO BEGIN BOOLEAN ARRAY BITS(1:N); INTEGER I; FOR I := 1 STEP 1 UNTIL N DO BEGIN NUM := RANDINT(1,N,SEED); IF BITS(NUM) THEN GOTO L; BITS(NUM) := TRUE; COUNT := COUNT + 1; END FOR I; L: END FOR RUN; EXPERIMENTAL := COUNT / TESTS; END EXPERIMENTAL;   INTEGER SEED, TESTS; SEED := ININT; TESTS := 1000000; BEGIN REAL A, E, ERR; INTEGER I; OUTTEXT(" N AVG CALC  %DIFF"); OUTIMAGE; FOR I := 1 STEP 1 UNTIL 20 DO BEGIN A := ANALYTICAL(I); E := EXPERIMENTAL(I); ERR := (ABS(E-A)/A)*100.0; OUTINT(I, 2); OUTFIX(E, 4, 7); OUTFIX(A, 4, 10); OUTFIX(ERR, 4, 10); OUTIMAGE; END FOR I; END; END
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%)
#Tcl
Tcl
# Generate a list of the numbers increasing from $a to $b proc range {a b} { for {set result {}} {$a <= $b} {incr a} {lappend result $a} return $result }   # Computing the expected value analytically proc tcl::mathfunc::factorial n {  ::tcl::mathop::* {*}[range 2 $n] } proc Analytical {n} { set sum 0.0 foreach x [range 1 $n] { set sum [expr {$sum + factorial($n) / factorial($n-$x) / double($n)**$x}] } return $sum }   # Determining an approximation to the value experimentally proc Experimental {n numTests} { set count 0 set u0 [lrepeat $n 1] foreach run [range 1 $numTests] { set unseen $u0 for {set i 0} {[lindex $unseen $i]} {incr count} { lset unseen $i 0 set i [expr {int(rand()*$n)}] } } return [expr {$count / double($numTests)}] }   # Tabulate the results in exactly the original format puts " N average analytical (error)" puts "=== ========= ============ =========" foreach n [range 1 20] { set a [Analytical $n] set e [Experimental $n 100000] puts [format "%3d  %9.4f  %12.4f (%6.2f%%)" $n $e $a [expr {abs($e-$a)/$a*100.0}]] }
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
#TI-89_BASIC
TI-89 BASIC
movinavg(list,p) Func Local r, i, z   For i,1,dim(list) max(i-p,0)→z sum(mid(list,z+1,i-z))/(i-z)→r[i] EndFor r EndFunc    
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.
#Nim
Nim
import strformat   const MAX = 120   proc isPrime(n: int): bool = var d = 5 if n < 2: return false if n mod 2 == 0: return n == 2 if n mod 3 == 0: return n == 3 while d * d <= n: if n mod d == 0: return false inc d, 2 if n mod d == 0: return false inc d, 4 return true   proc countPrimeFactors(n_in: int): int = var count = 0 var f = 2 var n = n_in if n == 1: return 0 if isPrime(n): return 1 while true: if n mod f == 0: inc count n = n div f if n == 1: return count if isPrime(n): f = n elif (f >= 3): inc f, 2 else: f = 3   proc main() = var n, count: int = 0 echo fmt"The attractive numbers up to and including {MAX} are:" for i in 1..MAX: n = countPrimeFactors(i) if isPrime(n): write(stdout, fmt"{i:4d}") inc count if count mod 20 == 0: write(stdout, "\n") write(stdout, "\n")   main()  
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.
#Objeck
Objeck
class AttractiveNumber { function : Main(args : String[]) ~ Nil { max := 120; "The attractive numbers up to and including {$max} are:"->PrintLine();   count := 0; for(i := 1; i <= max; i += 1;) { n := CountPrimeFactors(i); if(IsPrime(n)) { " {$i}"->Print(); if(++count % 20 = 0) { ""->PrintLine(); }; }; };   ""->PrintLine(); }   function : IsPrime(n : Int) ~ Bool { if(n < 2) { return false; };   if(n % 2 = 0) { return n = 2; };   if(n % 3 = 0) { return n = 3; };   d := 5; while(d *d <= n) { if(n % d = 0) { return false; }; d += 2;   if(n % d = 0) { return false; }; d += 4; };   return true; }   function : CountPrimeFactors(n : Int) ~ Int { if(n = 1) { return 0; };   if(IsPrime(n)) { return 1; };   count := 0; f := 2; while(true) { if(n % f = 0) { count++; n /= f; if(n = 1) { return count; }; if(IsPrime(n)) { f := n; }; } else if(f >= 3) { f += 2; } else { f := 3; }; };   return -1; } }
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
#Racket
Racket
  #lang racket (define (mean-angle/radians as) (define n (length as)) (atan (* (/ 1 n) (for/sum ([αj as]) (sin αj))) (* (/ 1 n) (for/sum ([αj as]) (cos αj))))) (define (mean-time times) (define secs/day (* 60 60 24)) (define (time->deg time) (/ (for/fold ([sum 0]) ([t (map string->number (string-split time ":"))]) (+ (* 60 sum) t)) secs/day 1/360 (/ 180 pi))) (define secs (modulo (inexact->exact (round (* (mean-angle/radians (map time->deg times)) (/ 180 pi) 1/360 secs/day))) secs/day)) (let loop ([s secs] [ts '()]) (if (zero? s) (string-join ts ":") (let-values ([(q r) (quotient/remainder s 60)]) (loop q (cons (~r r #:min-width 2 #:pad-string "0") ts)))))) (mean-time '("23:00:17" "23:40:20" "00:12:45" "00:17:19"))  
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
#Raku
Raku
sub tod2rad($_) { [+](.comb(/\d+/) Z* 3600,60,1) * tau / 86400 }   sub rad2tod ($r) { my $x = $r * 86400 / tau; (($x xx 3 Z/ 3600,60,1) Z% 24,60,60).fmt('%02d',':'); }   sub phase ($c) { $c.polar[1] }   sub mean-time (@t) { rad2tod phase [+] map { cis tod2rad $_ }, @t }   my @times = ["23:00:17", "23:40:20", "00:12:45", "00:17:19"];   say "{ mean-time(@times) } is the mean time of @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.
#TypeScript
TypeScript
/** A single node in an AVL tree */ class AVLnode <T> { balance: number left: AVLnode<T> right: AVLnode<T>   constructor(public key: T, public parent: AVLnode<T> = null) { this.balance = 0 this.left = null this.right = null } }   /** The balanced AVL tree */ class AVLtree <T> { // public members organized here constructor() { this.root = null }   insert(key: T): boolean { if (this.root === null) { this.root = new AVLnode<T>(key) } else { let n: AVLnode<T> = this.root, parent: AVLnode<T> = null   while (true) { if(n.key === key) { return false }   parent = n   let goLeft: boolean = n.key > key n = goLeft ? n.left : n.right   if (n === null) { if (goLeft) { parent.left = new AVLnode<T>(key, parent) } else { parent.right = new AVLnode<T>(key, parent) }   this.rebalance(parent) break } } }   return true }   deleteKey(delKey: T): void { if (this.root === null) { return }   let n: AVLnode<T> = this.root, parent: AVLnode<T> = this.root, delNode: AVLnode<T> = null, child: AVLnode<T> = this.root   while (child !== null) { parent = n n = child child = delKey >= n.key ? n.right : n.left if (delKey === n.key) { delNode = n } }   if (delNode !== null) { delNode.key = n.key   child = n.left !== null ? n.left : n.right   if (this.root.key === delKey) { this.root = child } else { if (parent.left === n) { parent.left = child } else { parent.right = child }   this.rebalance(parent) } } }   treeBalanceString(n: AVLnode<T> = this.root): string { if (n !== null) { return `${this.treeBalanceString(n.left)} ${n.balance} ${this.treeBalanceString(n.right)}` } return "" }   toString(n: AVLnode<T> = this.root): string { if (n !== null) { return `${this.toString(n.left)} ${n.key} ${this.toString(n.right)}` } return "" }     // private members organized here private root: AVLnode<T>   private rotateLeft(a: AVLnode<T>): AVLnode<T> { let b: AVLnode<T> = a.right b.parent = a.parent a.right = b.left   if (a.right !== null) { a.right.parent = a }   b.left = a a.parent = b   if (b.parent !== null) { if (b.parent.right === a) { b.parent.right = b } else { b.parent.left = b } }   this.setBalance(a) this.setBalance(b)   return b }   private rotateRight(a: AVLnode<T>): AVLnode<T> { let b: AVLnode<T> = a.left b.parent = a.parent a.left = b.right   if (a.left !== null) { a.left.parent = a }   b.right = a a.parent = b   if (b.parent !== null) { if (b.parent.right === a) { b.parent.right = b } else { b.parent.left = b } }   this.setBalance(a) this.setBalance(b)   return b }   private rotateLeftThenRight(n: AVLnode<T>): AVLnode<T> { n.left = this.rotateLeft(n.left) return this.rotateRight(n) }   private rotateRightThenLeft(n: AVLnode<T>): AVLnode<T> { n.right = this.rotateRight(n.right) return this.rotateLeft(n) }   private rebalance(n: AVLnode<T>): void { this.setBalance(n)   if (n.balance === -2) { if(this.height(n.left.left) >= this.height(n.left.right)) { n = this.rotateRight(n) } else { n = this.rotateLeftThenRight(n) } } else if (n.balance === 2) { if(this.height(n.right.right) >= this.height(n.right.left)) { n = this.rotateLeft(n) } else { n = this.rotateRightThenLeft(n) } }   if (n.parent !== null) { this.rebalance(n.parent) } else { this.root = n } }   private height(n: AVLnode<T>): number { if (n === null) { return -1 } return 1 + Math.max(this.height(n.left), this.height(n.right)) }   private setBalance(n: AVLnode<T>): void { n.balance = this.height(n.right) - this.height(n.left) }   public showNodeBalance(n: AVLnode<T>): string { if (n !== null) { return `${this.showNodeBalance(n.left)} ${n.balance} ${this.showNodeBalance(n.right)}` } return "" } }  
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
#Python
Python
>>> from cmath import rect, phase >>> from math import radians, degrees >>> def mean_angle(deg): ... return degrees(phase(sum(rect(1, radians(d)) for d in deg)/len(deg))) ... >>> for angles in [[350, 10], [90, 180, 270, 360], [10, 20, 30]]: ... print('The mean angle of', angles, 'is:', round(mean_angle(angles), 12), 'degrees') ... The mean angle of [350, 10] is: -0.0 degrees The mean angle of [90, 180, 270, 360] is: -90.0 degrees The mean angle of [10, 20, 30] is: 20.0 degrees >>>
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
#R
R
  deg2rad <- function(x) { x * pi/180 }   rad2deg <- function(x) { x * 180/pi }   deg2vec <- function(x) { c(sin(deg2rad(x)), cos(deg2rad(x))) }   vec2deg <- function(x) { res <- rad2deg(atan2(x[1], x[2])) if (res < 0) { 360 + res } else { res } }   mean_vec <- function(x) { y <- lapply(x, deg2vec) Reduce(`+`, y)/length(y) }   mean_deg <- function(x) { vec2deg(mean_vec(x)) }   mean_deg(c(350, 10)) mean_deg(c(90, 180, 270, 360)) mean_deg(c(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
#HicEst
HicEst
REAL :: n=10, vec(n)   vec = RAN(1) SORT(Vector=vec, Sorted=vec) ! in-place Merge-Sort   IF( MOD(n,2) ) THEN ! odd n median = vec( CEILING(n/2) ) ELSE median = ( vec(n/2) + vec(n/2 + 1) ) / 2 ENDIF
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
#Lua
Lua
function fsum(f, a, ...) return a and f(a) + fsum(f, ...) or 0 end function pymean(t, f, finv) return finv(fsum(f, unpack(t)) / #t) end nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}   --arithmetic a = pymean(nums, function(n) return n end, function(n) return n end) --geometric g = pymean(nums, math.log, math.exp) --harmonic h = pymean(nums, function(n) return 1/n end, function(n) return 1/n end) print(a, g, h) assert(a >= g and g >= h)
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.
#Tcl
Tcl
package require Tcl 8.5   proc bt-int b { set n 0 foreach c [split $b ""] { set n [expr {$n * 3}] switch -- $c { + { incr n 1 } - { incr n -1 } } } return $n } proc int-bt n { if {$n == 0} { return "0" } while {$n != 0} { lappend result [lindex {0 + -} [expr {$n % 3}]] set n [expr {$n / 3 + ($n%3 == 2)}] } return [join [lreverse $result] ""] }   proc bt-neg b { string map {+ - - +} $b } proc bt-sub {a b} { bt-add $a [bt-neg $b] } proc bt-add-digits {a b c} { if {$a eq ""} {set a 0} if {$b eq ""} {set b 0} if {$a ne 0} {append a 1} if {$b ne 0} {append b 1} lindex {{0 -1} {+ -1} {- 0} {0 0} {+ 0} {- 1} {0 1}} [expr {$a+$b+$c+3}] } proc bt-add {a b} { set c 0 set result {} foreach ca [lreverse [split $a ""]] cb [lreverse [split $b ""]] { lassign [bt-add-digits $ca $cb $c] d c lappend result $d } if {$c ne "0"} {lappend result [lindex {0 + -} $c]} if {![llength $result]} {return "0"} string trimleft [join [lreverse $result] ""] 0 } proc bt-mul {a b} { if {$a eq "0" || $a eq "" || $b eq "0"} {return "0"} set sub [bt-mul [string range $a 0 end-1] $b]0 switch -- [string index $a end] { 0 { return $sub } + { return [bt-add $sub $b] } - { return [bt-sub $sub $b] } } }
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.
#Shen
Shen
(define babbage N -> N where (= 269696 (shen.mod (* N N) 1000000))) N -> (babbage (+ N 1))   (babbage 1)
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.
#Sidef
Sidef
var n = 0 while (n*n % 1000000 != 269696) { n += 2 } say 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.
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Runtime.CompilerServices   Module Module1   <Extension()> Function ApproxEquals(ByVal value As Double, other As Double, epsilon As Double) Return Math.Abs(value - other) < epsilon End Function   Sub Test(a As Double, b As Double) Dim epsilon = 1.0E-18 Console.WriteLine($"{a}, {b} => {a.ApproxEquals(b, epsilon)}") End Sub   Sub Main() Test(100000000000000.02, 100000000000000.02) Test(100.01, 100.011) Test(10000000000000.002 / 10000.0, 1000000000.0000001) Test(0.001, 0.0010000001) Test(1.01E-22, 0.0) Test(Math.Sqrt(2) * Math.Sqrt(2), 2.0) Test(-Math.Sqrt(2) * Math.Sqrt(2), -2.0) Test(3.1415926535897931, 3.1415926535897931) End Sub   End Module
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.
#Wren
Wren
var tol = 1e-16 var pairs = [ [100000000000000.01, 100000000000000.011], [100.01, 100.011], [10000000000000.001 / 10000.0, 1000000000.0000001000], [0.001, 0.0010000001], [0.000000000000000000000101, 0.0], [2.sqrt * 2.sqrt, 2.0], [-2.sqrt * 2.sqrt, -2.0], [3.14159265358979323846, 3.14159265358979324] ] System.print("Approximate equality of test cases for a tolerance of %(tol):") var i = 0 for (pair in pairs) { i = i + 1 System.print("  %(i) -> %((pair[0] - pair[1]).abs < tol)") }
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
#Euphoria
Euphoria
function check_brackets(sequence s) integer level level = 0 for i = 1 to length(s) do if s[i] = '[' then level += 1 elsif s[i] = ']' then level -= 1 if level < 0 then return 0 end if end if end for return level = 0 end function   function generate_brackets(integer n) integer opened,closed,r sequence s opened = n closed = n s = "" for i = 1 to n*2 do r = rand(opened+closed) if r<=opened then s &= '[' opened -= 1 else s &= ']' closed -= 1 end if end for return s end function   sequence s for i = 1 to 10 do s = generate_brackets(3) puts(1,s) if check_brackets(s) then puts(1," OK\n") else puts(1," NOT OK\n") end if end for
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.
#J
J
require'strings ~system/packages/misc/xenos.ijs' record=: [:|: <@deb;._1@(':',]);._2@do bind '0 :0'   passfields=: <;._1':username:password:gid:uid:gecos:home:shell'   passrec=: LF,~ [: }.@;@ , ':';"0 (passfields i. {. ) { a:,~ {:   R1=: passrec record'' username: jsmith password: x gid: 1001 uid: 1000 gecos: Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected] home: /home/jsmith shell: /bin/bash )   R2=: passrec record'' username: jdoe password: x gid: 1002 uid: 1000 gecos: Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected] home: /home/jdoe shell: /bin/bash )   R3=: passrec record'' username: xyz password: x gid: 1003 uid: 1000 gecos: X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected] home: /home/xyz shell: /bin/bash )   passwd=: <'/tmp/passwd.txt' NB. file needs to be writable on implementation machine   (R1,R2) fwrite passwd R3 fappend passwd   assert 1 e. R3 E. fread passwd
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
#BaCon
BaCon
DECLARE associative ASSOC STRING   associative("abc") = "first three" associative("xyz") = "last three"   PRINT associative("xyz")
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
#F.23
F#
  // Find Antı-Primes. Nigel Galloway: Secember 10th., 2018 let N=200000000000000000000000000I let fI,_=Seq.scan(fun (_,g) e->(e,e*g)) (2I,4I) (primes|>Seq.skip 1|>Seq.map bigint)|>Seq.takeWhile(fun(_,n)->n<N)|>List.ofSeq|>List.unzip let fG g=Seq.unfold(fun ((n,i,e) as z)->Some(z,(n+1,i+1,(e*g)))) (1,2,g)|>Seq.takeWhile(fun(_,_,n)->n<N) let fE n i=n|>Seq.collect(fun(n,e,g)->Seq.map(fun(a,c,b)->(a,c*e,g*b)) (i|>Seq.takeWhile(fun(g,_,_)->g<=n)) |> Seq.takeWhile(fun(_,_,n)->n<N)) let fL,_=Seq.concat(Seq.scan(fun n g->fE n (fG g)) (seq[(2147483647,1,1I)]) fI)|>List.ofSeq|>List.sortBy(fun(_,_,n)->n)|>List.fold(fun ((a,b) as z) (_,n,g)->if n>b then ((n,g)::a,n) else z) ([],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.
#PicoLisp
PicoLisp
(seed (in "/dev/urandom" (rd 8)))   (de *Buckets . 15) # Number of buckets   # E/R model (class +Bucket +Entity) (rel key (+Key +Number)) # Key 1 .. *Buckets (rel val (+Number)) # Value 1 .. 999   # Create new DB file (pool (tmp "buckets.db"))   # Create *Buckets buckets with values between 1 and 999 (for K *Buckets (new T '(+Bucket) 'key K 'val (rand 1 999)) ) (commit)   # Pick a random bucket (de pickBucket () (db 'key '+Bucket (rand 1 *Buckets)) )   # First process (unless (fork) (seed *Pid) # Ensure local random sequence (loop (let (B1 (pickBucket) B2 (pickBucket)) # Pick two buckets 'B1' and 'B2' (dbSync) # Atomic DB operation (let (V1 (; B1 val) V2 (; B2 val)) # Get current values (cond ((> V1 V2) (dec> B1 'val) # Make them closer to equal (inc> B2 'val) ) ((> V2 V1) (dec> B2 'val) (inc> B1 'val) ) ) ) (commit 'upd) # Close transaction (wait 1) ) ) )   # Second process (unless (fork) (seed *Pid) # Ensure local random sequence (loop (let (B1 (pickBucket) B2 (pickBucket)) # Pick two buckets 'B1' and 'B2' (unless (== B1 B2) # Found two different ones? (dbSync) # Atomic DB operation (let (V1 (; B1 val) V2 (; B2 val)) # Get current values (cond ((> V1 V2 0) (inc> B1 'val) # Redistribute them (dec> B2 'val) ) ((> V2 V1 0) (inc> B2 'val) (dec> B1 'val) ) ) ) (commit 'upd) # Close transaction (wait 1) ) ) ) )   # Third process (unless (fork) (loop (let Lst (collect 'key '+Bucket) # Get all buckets (for This Lst # Print current values (printsp (: val)) ) (prinl # and total sum "-- Total: " (sum '((This) (: val)) Lst) ) ) (wait 2000) ) ) # Sleep two seconds   (wait)
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.
#PureBasic
PureBasic
#Buckets=9 #TotalAmount=200 Global Dim Buckets(#Buckets) Global BMutex=CreateMutex() Global Quit=#False   Procedure max(x,y) If x>=y: ProcedureReturn x Else: ProcedureReturn y EndIf EndProcedure   Procedure Move(WantedAmount, From, Dest) Protected RealAmount If from<>Dest LockMutex(BMutex) RealAmount=max(0, Buckets(from)-WantedAmount) Buckets(From)-RealAmount Buckets(Dest)+RealAmount UnlockMutex(BMutex) EndIf ProcedureReturn RealAmount EndProcedure   Procedure Level(A,B) Protected i, j, t If A<>B LockMutex(BMutex) t=Buckets(A)+Buckets(B) i=t/2: j=t-i Buckets(A)=i Buckets(B)=j UnlockMutex(BMutex) EndIf EndProcedure   Procedure DoInvent(Array A(1)) Protected i, sum LockMutex(BMutex) For i=0 To ArraySize(Buckets()) A(i)=Buckets(i) sum+A(i) Next i UnlockMutex(BMutex) ProcedureReturn sum EndProcedure   Procedure MixingThread(arg) Repeat Move(Random(#TotalAmount),Random(#Buckets),Random(#Buckets)) Until Quit EndProcedure   Procedure LevelingThread(arg) Repeat Level(Random(#Buckets),Random(#Buckets)) Until Quit EndProcedure   If OpenWindow(0,0,0,100,150,"Atomic updates",#PB_Window_SystemMenu) Define Thread1=CreateThread(@MixingThread(),0) Define Thread2=CreateThread(@MixingThread(),0) Define i, Event Dim Inventory(#Buckets) ; Set up a small GUI For i=0 To 9 TextGadget(i, 0,i*15,50, 15,"Bucket #"+Str(i)) Next i TextGadget(10,55,135,40,15,"=") AddWindowTimer(0,0,500) Buckets(0)=#TotalAmount Repeat Event=WaitWindowEvent() If Event=#PB_Event_Timer i=DoInvent(Inventory()) SetGadgetText(10,"="+Str(i)) For i=0 To #Buckets SetGadgetText(i, Str(Inventory(i))) Next i EndIf Until Event=#PB_Event_CloseWindow Quit=#True ; Tell threads to shut down WaitThread(Thread1): WaitThread(Thread2) EndIf
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.
#Nim
Nim
var a = 42 assert(a == 42, "Not 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.
#Oberon-2
Oberon-2
  MODULE Assertions; VAR a: INTEGER; BEGIN a := 40; ASSERT(a = 42); END Assertions.  
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.
#Objeck
Objeck
class Test { function : Main(args : String[]) ~ Nil { if(args->Size() = 1) { a := args[0]->ToInt(); Runtime->Assert(a = 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.
#Crystal
Crystal
values = [1, 2, 3]   new_values = values.map do |number| number * 2 end   puts new_values #=> [2, 4, 6]
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.
#D
D
import std.stdio, std.algorithm;   void main() { auto items = [1, 2, 3, 4, 5]; auto m = items.map!(x => x + 5)(); writeln(m); }
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
#Phix
Phix
function mode(sequence s) -- returns a list of the most common values, each of which occurs the same number of times integer nxt = 1, count = 1, maxc = 1 sequence res = {} if length(s)!=0 then s = sort(s) object prev = s[1] for i=2 to length(s) do if s[i]!=prev then s[nxt] = {count,prev} nxt += 1 prev = s[i] count = 1 else count += 1 if count>maxc then maxc = count end if end if end for s[nxt] = {count,prev} res = "" for i=1 to nxt do if s[i][1]=maxc then res = append(res,s[i][2]) end if end for end if return res end function ?mode({1, 2, 5, -5, -9.5, 3.14159}) ?mode({ 1, "blue", 2, 7.5, 5, "green", "red", 5, 2, "blue", "white" }) ?mode({1, 2, 3, 1, 2, 4, 2, 5, 2, 3, 3, 1, 3, 6}) ?mode({.2, .7, .1, .8, .2}) ?mode({"two", 7, 1, 8, "two", 8}) ?mode("Hello there world") ?mode({}) {} = wait_key()
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
#Elena
Elena
import system'collections; import system'routines; import extensions;   public program() { // 1. Create var map := Dictionary.new(); map["key"] := "foox"; map["key"] := "foo"; map["key2"]:= "foo2"; map["key3"]:= "foo3"; map["key4"]:= "foo4";   // Enumerate map.forEach: (keyValue){ console.printLine(keyValue.Key," : ",keyValue.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
#Elixir
Elixir
IO.inspect d = Map.new([foo: 1, bar: 2, baz: 3]) Enum.each(d, fn kv -> IO.inspect kv end) Enum.each(d, fn {k,v} -> IO.puts "#{inspect k} => #{v}" end) Enum.each(Map.keys(d), fn key -> IO.inspect key end) Enum.each(Map.values(d), fn value -> IO.inspect value end)
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]
#Racket
Racket
#lang racket   (define a (vector 1.00000000E0 -2.77555756E-16 3.33333333E-01 -1.85037171E-17)) (define b (vector 0.16666667E0 0.50000000E0 0.50000000E0 0.16666667E0)) (define s (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))   (define (filter-signal-direct-form-ii-transposed coeff1 coeff2 signal) (define signal-size (vector-length signal)) (define filtered-signal (make-vector signal-size 0)) (for ((i signal-size)) (vector-set! filtered-signal i (/ (for/fold ((s (for/fold ((s 0)) ((j (vector-length coeff2)) #:when (>= i j)) (+ s (* (vector-ref coeff2 j) (vector-ref signal (- i j))))))) ((j (vector-length coeff1)) #:when (>= i j)) (- s (* (vector-ref coeff1 j) (vector-ref filtered-signal (- i j))))) (vector-ref coeff1 0)))) filtered-signal)   (filter-signal-direct-form-ii-transposed a b s)
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]
#Raku
Raku
sub TDF-II-filter ( @signal, @a, @b ) { my @out = 0 xx @signal; for ^@signal -> $i { my $this; $this += @b[$_] * @signal[$i-$_] if $i-$_ >= 0 for ^@b; $this -= @a[$_] * @out[$i-$_] if $i-$_ >= 0 for ^@a; @out[$i] = $this / @a[0]; } @out }   my @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 ]; my @a = [ 1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17 ]; my @b = [ 0.16666667, 0.5, 0.5, 0.16666667 ];   say TDF-II-filter(@signal, @a, @b)».fmt("% 0.8f") Z~ flat (', ' xx 4, ",\n") xx *;
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
#Euphoria
Euphoria
function mean(sequence s) atom sum if length(s) = 0 then return 0 else sum = 0 for i = 1 to length(s) do sum += s[i] end for return sum/length(s) end if end function   sequence test test = {1.0, 2.0, 5.0, -5.0, 9.5, 3.14159} ? mean(test)
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
#Excel
Excel
=AVERAGE(A1:A10)
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%)
#Unicon
Unicon
link printf, factors   $define MAX_N 20 $define TIMES 1000000 $define RAND_MAX 2147483647   procedure expected(n) local sum := 0 every i := 1 to n do sum +:= factorial(n) / (n ^ i) / factorial(n - i) return sum end   procedure test(n, times) local i, count := 0, x, bits every i := 0 to times-1 do { x := 1 bits := 0 while iand(bits, x)=0 do { count +:= 1 bits := ior(bits, x) x := ishift(1 , ?n-1) } } return count end   procedure main(void) local n, cnt, avg, theory, diff write(" n\tavg\texp.\tdiff\n", repl("-",29)) every n := 1 to MAX_N do { cnt := test(n, TIMES) avg := real(cnt) / TIMES theory := expected(n) diff := (avg / theory - 1) * 100 printf("%2d %8.4r %8.4r %6.3r%%\n", n, avg, theory, diff) } return 0 end
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%)
#VBA
VBA
Const MAX = 20 Const ITER = 1000000   Function expected(n As Long) As Double Dim sum As Double For i = 1 To n sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i) Next i expected = sum End Function   Function test(n As Long) As Double Dim count As Long Dim x As Long, bits As Long For i = 1 To ITER x = 1 bits = 0 Do While Not bits And x count = count + 1 bits = bits Or x x = 2 ^ (Int(n * Rnd())) Loop Next i test = count / ITER End Function   Public Sub main() Dim n As Long Debug.Print " n avg. exp. (error%)" Debug.Print "== ====== ====== ========" For n = 1 To MAX av = test(n) ex = expected(n) Debug.Print Format(n, "@@"); " "; Format(av, "0.0000"); " "; Debug.Print Format(ex, "0.0000"); " ("; Format(Abs(1 - av / ex), "0.000%"); ")" Next n End Sub
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
#VBA
VBA
Class sma 'to be stored in a class module with name "sma" Private n As Integer 'period Private arr() As Double 'circular list Private index As Integer 'pointer into arr Private oldsma As Double   Public Sub init(size As Integer) n = size ReDim arr(n - 1) index = 0 End Sub   Public Function sma(number As Double) As Double sma = oldsma + (-arr(index) + number) / n oldsma = sma arr(index) = number index = (index + 1) Mod n End Function   Normal module Public Sub main() s = [{1,2,3,4,5,5,4,3,2,1}] Dim sma3 As New sma Dim sma5 As New sma sma3.init 3 sma5.init 5 For i = 1 To UBound(s) Debug.Print i, Format(sma3.sma(CDbl(s(i))), "0.00000"), Debug.Print Format(sma5.sma(CDbl(s(i))), "0.00000") Next i End Sub
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.
#Pascal
Pascal
program AttractiveNumbers; { numbers with count of factors = prime * using modified sieve of erathosthes * by adding the power of the prime to multiples * of the composite number } {$IFDEF FPC} {$MODE DELPHI} {$ELSE} {$APPTYPE CONSOLE} {$ENDIF} uses sysutils;//timing const cTextMany = ' with many factors '; cText2 = ' with only two factors '; cText1 = ' with only one factor '; type tValue = LongWord; tpValue = ^tValue; tPower = array[0..63] of tValue;//2^64   var power : tPower; sieve : array of byte;   function NextPotCnt(p: tValue):tValue; //return the first power <> 0 //power == n to base prim var i : NativeUint; begin result := 0; repeat i := power[result]; Inc(i); IF i < p then BREAK else begin i := 0; power[result] := 0; inc(result); end; until false; power[result] := i; inc(result); end;   procedure InitSieveWith2; //the prime 2, because its the first one, is the one, //which can can be speed up tremendously, by moving var pSieve : pByte; CopyWidth,lmt : NativeInt; Begin pSieve := @sieve[0]; Lmt := High(sieve); sieve[1] := 0; sieve[2] := 1; // aka 2^1 -> one factor CopyWidth := 2;   while CopyWidth*2 <= Lmt do Begin // copy idx 1,2 to 3,4 | 1..4 to 5..8 | 1..8 to 9..16 move(pSieve[1],pSieve[CopyWidth+1],CopyWidth); // 01 -> 0101 -> 01020102-> 0102010301020103 inc(CopyWidth,CopyWidth);//*2 //increment the factor of last element by one. inc(pSieve[CopyWidth]); //idx 12 1234 12345678 //value 01 -> 0102 -> 01020103-> 0102010301020104 end; //copy the rest move(pSieve[1],pSieve[CopyWidth+1],Lmt-CopyWidth);   //mark 0,1 not prime, 255 factors are today not possible 2^255 >> Uint64 sieve[0]:= 255; sieve[1]:= 255; sieve[2]:= 0; // make prime again end;   procedure OutCntTime(T:TDateTime;txt:String;cnt:NativeInt); Begin writeln(cnt:12,txt,T*86400:10:3,' s'); end;   procedure sievefactors; var T0 : TDateTime; pSieve : pByte; i,j,i2,k,lmt,cnt : NativeUInt; Begin InitSieveWith2; pSieve := @sieve[0]; Lmt := High(sieve);   //Divide into 3 section   //first i*i*i<= lmt with time expensive NextPotCnt T0 := now; cnt := 0; //third root of limit calculate only once, no comparison ala while i*i*i<= lmt do k := trunc(exp(ln(Lmt)/3)); For i := 3 to k do if pSieve[i] = 0 then Begin inc(cnt); j := 2*i; fillChar(Power,Sizeof(Power),#0); Power[0] := 1; repeat inc(pSieve[j],NextPotCnt(i)); inc(j,i); until j > lmt; end; OutCntTime(now-T0,cTextMany,cnt); T0 := now;   //second i*i <= lmt cnt := 0; i := k+1; k := trunc(sqrt(Lmt)); For i := i to k do if pSieve[i] = 0 then Begin //first increment all multiples of prime by one inc(cnt); j := 2*i; repeat inc(pSieve[j]); inc(j,i); until j>lmt; //second increment all multiples prime*prime by one i2 := i*i; j := i2; repeat inc(pSieve[j]); inc(j,i2); until j>lmt; end; OutCntTime(now-T0,cText2,cnt); T0 := now;   //third i*i > lmt -> only one new factor cnt := 0; inc(k); For i := k to Lmt shr 1 do if pSieve[i] = 0 then Begin inc(cnt); j := 2*i; repeat inc(pSieve[j]); inc(j,i); until j>lmt; end; OutCntTime(now-T0,cText1,cnt); end;   const smallLmt = 120; //needs 1e10 Byte = 10 Gb maybe someone got 128 Gb :-) nearly linear time BigLimit = 10*1000*1000*1000; var T0,T : TDateTime; i,cnt,lmt : NativeInt; Begin setlength(sieve,smallLmt+1);   sievefactors; cnt := 0; For i := 2 to smallLmt do Begin if sieve[sieve[i]] = 0 then Begin write(i:4); inc(cnt); if cnt>19 then Begin writeln; cnt := 0; end; end; end; writeln; writeln; T0 := now; setlength(sieve,BigLimit+1); T := now; writeln('time allocating  : ',(T-T0) *86400 :8:3,' s'); sievefactors; T := now-T; writeln('time sieving : ',T*86400 :8:3,' s'); T:= now; cnt := 0; i := 0; lmt := 10; repeat repeat inc(i); {IF sieve[sieve[i]] = 0 then inc(cnt); takes double time is not relevant} inc(cnt,ORD(sieve[sieve[i]] = 0)); until i = lmt; writeln(lmt:11,cnt:12); lmt := 10*lmt; until lmt >High(sieve); T := now-T; writeln('time counting : ',T*86400 :8:3,' s'); writeln('time total  : ',(now-T0)*86400 :8:3,' s'); end.
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
#REXX
REXX
/* REXX --------------------------------------------------------------- * 25.06.2014 Walter Pachl * taken from ooRexx using my very aged sin/cos/artan functions *--------------------------------------------------------------------*/ times='23:00:17 23:40:20 00:12:45 00:17:19' sum=0 day=86400 pi=3.14159265358979323846264 x=0 y=0 Do i=1 To words(times) /* loop over times */ time.i=word(times,i) /* pick a time */ alpha.i=t2a(time.i) /* convert to angle (radians) */ /* Say time.i format(alpha.i,6,9) */ x=x+sin(alpha.i) /* accumulate sines */ y=y+cos(alpha.i) /* accumulate cosines */ End ww=arctan(x/y) /* compute average angle */ ss=ww*86400/(2*pi) /* convert to seconds */ If ss<0 Then ss=ss+day /* avoid negative value */ m=ss%60 /* split into hh mm ss */ s=ss-m*60 h=m%60 m=m-h*60 Say f2(h)':'f2(m)':'f2(s) /* show the mean time */ Exit   t2a: Procedure Expose day pi /* convert time to angle */ Parse Arg hh ':' mm ':' ss sec=(hh*60+mm)*60+ss If sec>(day/2) Then sec=sec-day a=2*pi*sec/day Return a   f2: return right(format(arg(1),2,0),2,0)     sin: Procedure Expose pi Parse Arg x prec=digits() Numeric Digits (2*prec) Do While x>pi x=x-pi End Do While x<-pi x=x+pi End o=x u=1 r=x Do i=3 By 2 ra=r o=-o*x*x u=u*i*(i-1) r=r+(o/u) If r=ra Then Leave End Numeric Digits prec Return r+0   cos: Procedure Expose pi Parse Arg x prec=digits() Numeric Digits (2*prec) Numeric Fuzz 3 o=1 u=1 r=1 Do i=1 By 2 ra=r o=-o*x*x u=u*i*(i+1) r=r+(o/u) If r=ra Then Leave End Numeric Digits prec Return r+0   arctan: Procedure Parse Arg x prec=digits() Numeric Digits (2*prec) Numeric Fuzz 3 o=x u=1 r=x k=0 Do i=3 By 2 ra=r o=-o*x*x r=r+(o/i) If r=ra Then Leave k=k+1 If k//1000=0 Then Say i left(r,40) format(abs(o/i),15,5) End Numeric Digits (prec) Return r+0
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.
#Wren
Wren
class Node { construct new(key, parent) { _key = key _parent = parent _balance = 0 _left = null _right = null }   key { _key } parent { _parent } balance { _balance } left { _left } right { _right }   key=(k) { _key = k } parent=(p) { _parent = p } balance=(v) { _balance = v } left=(n) { _left = n } right= (n) { _right = n } }   class AvlTree { construct new() { _root = null }   insert(key) { if (!_root) { _root = Node.new(key, null) } else { var n = _root while (true) { if (n.key == key) return false var parent = n var goLeft = n.key > key n = goLeft ? n.left : n.right if (!n) { if (goLeft) { parent.left = Node.new(key, parent) } else { parent.right = Node.new(key, parent) } rebalance(parent) break } } } return true }   delete(delKey) { if (!_root) return var n = _root var parent = _root var delNode = null var child = _root while (child) { parent = n n = child child = (delKey >= n.key) ? n.right : n.left if (delKey == n.key) delNode = n } if (delNode) { delNode.key = n.key child = n.left ? n.left : n.right if (_root.key == delKey) { _root = child if (_root) _root.parent = null } else { if (parent.left == n) { parent.left = child } else { parent.right = child } if (child) child.parent = parent rebalance(parent) } } }   rebalance(n) { setBalance([n]) var nn = n if (nn.balance == -2) { if (height(nn.left.left) >= height(nn.left.right)) { nn = rotateRight(nn) } else { nn = rotateLeftThenRight(nn) } } else if (nn.balance == 2) { if (height(nn.right.right) >= height(nn.right.left)) { nn = rotateLeft(nn) } else { nn = rotateRightThenLeft(nn) } } if (nn.parent) rebalance(nn.parent) else _root = nn }   rotateLeft(a) { var 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 } } setBalance([a, b]) return b }   rotateRight(a) { var 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 } } setBalance([a, b]) return b }   rotateLeftThenRight(n) { n.left = rotateLeft(n.left) return rotateRight(n) }   rotateRightThenLeft(n) { n.right = rotateRight(n.right) return rotateLeft(n) }   height(n) { if (!n) return -1 return 1 + height(n.left).max(height(n.right)) }   setBalance(nodes) { for (n in nodes) n.balance = height(n.right) - height(n.left) }   printKey() { printKey(_root) System.print() }   printKey(n) { if (n) { printKey(n.left) System.write("%(n.key) ") printKey(n.right) } }   printBalance() { printBalance(_root) System.print() }   printBalance(n) { if (n) { printBalance(n.left) System.write("%(n.balance) ") printBalance(n.right) } } }   var tree = AvlTree.new() System.print("Inserting values 1 to 10") for (i in 1..10) tree.insert(i) System.write("Printing key  : ") tree.printKey() System.write("Printing balance : ") tree.printBalance()
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
#Racket
Racket
  #lang racket   (define (mean-angle αs) (radians->degrees (mean-angle/radians (map degrees->radians αs))))   (define (mean-angle/radians αs) (define n (length αs)) (atan (* (/ 1 n) (for/sum ([α_j αs]) (sin α_j))) (* (/ 1 n) (for/sum ([α_j αs]) (cos α_j)))))   (mean-angle '(350 0 10)) (mean-angle '(90 180 270 360)) (mean-angle '(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
#Raku
Raku
# Of course, you can still use pi and 180. sub deg2rad { $^d * tau / 360 } sub rad2deg { $^r * 360 / tau }   sub phase ($c) { my ($mag,$ang) = $c.polar; return NaN if $mag < 1e-16; $ang; }   sub meanAngle { rad2deg phase [+] map { cis deg2rad $_ }, @^angles }   say meanAngle($_).fmt("%.2f\tis the mean angle of "), $_ 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
#Icon_and_Unicon
Icon and Unicon
procedure main(args) write(median(args)) end   procedure median(A) A := sort(A) n := *A return if n % 2 = 1 then A[n/2+1] else (A[n/2]+A[n/2+1])/2.0 | 0 # 0 if empty list 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
#J
J
require 'stats/base' median 1 9 2 4 3
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
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { sum=lambda -> { Read m as array if len(m)=0 then =0 : exit sum=Array(m, Dimension(m,0)) If len(m)=1 then =sum : exit k=each(m,2,-1) While k { sum+=Array(k) } =sum } mean=lambda sum (a as array) ->{ =sum(a)/len(a) } prod=lambda -> { m=array if len(m)=0 then =0 : exit prod=Array(m, Dimension(m,0)) If len(m)=1 then =prod : exit k=each(m,2,-1) While k { prod*=Array(k) } =prod } geomean=lambda prod (a as array) -> { =prod(a)^(1/len(a)) } harmomean=lambda (a as array) -> { if len(a)=0 then =0 : exit sum=1/Array(a, Dimension(a,0)) If len(a)=1 then =1/sum : exit k=each(a,2,-1) While k { sum+=1/Array(k) } =len(a)/sum } Print sum((1,2,3,4,5))=15 Print prod((1,2,3,4,5))=120 Print mean((1,2,3,4,5))==3 \\ use == to apply rounding before comparison Print geomean((1,2,3,4,5))==2.60517108469735 Print harmomean((1,2,3,4,5))==2.18978102189784 Generator =lambda x=1 ->{=x : x++} dim a(10)<<Generator() Print mean(a())==5.5 Print geomean(a())==4.52872868811677 Print harmomean(a())==3.41417152147412 } CheckIt  
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.
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Text   Module Module1 Sub Main() Dim a As New BalancedTernary("+-0++0+") Console.WriteLine("a: {0} = {1}", a, a.ToLong) Dim b As New BalancedTernary(-436) Console.WriteLine("b: {0} = {1}", b, b.ToLong) Dim c As New BalancedTernary("+-++-") Console.WriteLine("c: {0} = {1}", c, c.ToLong) Dim d = a * (b - c) Console.WriteLine("a * (b - c): {0} = {1}", d, d.ToLong) End Sub   Class BalancedTernary Private Enum BalancedTernaryDigit MINUS = -1 ZERO = 0 PLUS = 1 End Enum   Private ReadOnly value() As BalancedTernaryDigit   ' empty = 0 Public Sub New() ReDim value(-1) End Sub   ' create from string Public Sub New(str As String) ReDim value(str.Length - 1) For i = 1 To str.Length If str(i - 1) = "-" Then value(i - 1) = BalancedTernaryDigit.MINUS ElseIf str(i - 1) = "0" Then value(i - 1) = BalancedTernaryDigit.ZERO ElseIf str(i - 1) = "+" Then value(i - 1) = BalancedTernaryDigit.PLUS Else Throw New ArgumentException("Unknown Digit: " + str(i - 1)) End If Next Array.Reverse(value) End Sub   ' convert integer Public Sub New(l As Long) Dim value As New List(Of BalancedTernaryDigit) Dim sign = Math.Sign(l) l = Math.Abs(l)   While l <> 0 Dim remainder = CType(l Mod 3, Byte) If remainder = 0 OrElse remainder = 1 Then value.Add(remainder) l /= 3 ElseIf remainder = 2 Then value.Add(BalancedTernaryDigit.MINUS) l = (l + 1) / 3 End If End While   Me.value = value.ToArray If sign < 0 Then Invert() End If End Sub   ' copy constructor Public Sub New(origin As BalancedTernary) ReDim value(origin.value.Length - 1) Array.Copy(origin.value, value, origin.value.Length) End Sub   ' only for internal use Private Sub New(value() As BalancedTernaryDigit) Dim endi = value.Length - 1 While endi > 0 AndAlso value(endi) = BalancedTernaryDigit.ZERO endi -= 1 End While ReDim Me.value(endi) Array.Copy(value, Me.value, endi + 1) End Sub   ' invert the values Private Sub Invert() For i = 1 To value.Length value(i - 1) = CType(-CType(value(i - 1), Integer), BalancedTernaryDigit) Next End Sub   ' convert to string Public Overrides Function ToString() As String Dim result As New StringBuilder Dim i = value.Length - 1 While i >= 0 If value(i) = BalancedTernaryDigit.MINUS Then result.Append("-") ElseIf value(i) = BalancedTernaryDigit.ZERO Then result.Append("0") ElseIf value(i) = BalancedTernaryDigit.PLUS Then result.Append("+") End If   i -= 1 End While Return result.ToString End Function   ' convert to long Public Function ToLong() As Long Dim result = 0L For i = 1 To value.Length result += value(i - 1) * Math.Pow(3.0, i - 1) Next Return result End Function   ' unary minus Public Shared Operator -(origin As BalancedTernary) As BalancedTernary Dim result As New BalancedTernary(origin) result.Invert() Return result End Operator   ' addition of digits Private Shared carry = BalancedTernaryDigit.ZERO Private Shared Function Add(a As BalancedTernaryDigit, b As BalancedTernaryDigit) As BalancedTernaryDigit If a <> b Then carry = BalancedTernaryDigit.ZERO Return a + b Else carry = a Return -CType(b, Integer) End If End Function   ' addition of balanced ternary numbers Public Shared Operator +(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim maxLength = Math.Max(a.value.Length, b.value.Length) Dim resultValue(maxLength) As BalancedTernaryDigit For i = 1 To maxLength If i - 1 < a.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), a.value(i - 1)) resultValue(i) = carry Else carry = BalancedTernaryDigit.ZERO End If   If i - 1 < b.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), b.value(i - 1)) resultValue(i) = Add(resultValue(i), carry) End If Next Return New BalancedTernary(resultValue) End Operator   ' subtraction of balanced ternary numbers Public Shared Operator -(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Return a + (-b) End Operator   ' multiplication of balanced ternary numbers Public Shared Operator *(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim longValue = a.value Dim shortValue = b.value Dim result As New BalancedTernary   If a.value.Length < b.value.Length Then longValue = b.value shortValue = a.value End If   For i = 1 To shortValue.Length If shortValue(i - 1) <> BalancedTernaryDigit.ZERO Then Dim temp(i + longValue.Length - 2) As BalancedTernaryDigit For j = 1 To longValue.Length temp(i + j - 2) = CType(shortValue(i - 1) * longValue(j - 1), BalancedTernaryDigit) Next result += New BalancedTernary(temp) End If Next   Return result End Operator End Class   End Module
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.
#Simula
Simula
BEGIN INTEGER PROBE, SQUARE; BOOLEAN DONE;   WHILE NOT DONE DO BEGIN PROBE := PROBE + 1; SQUARE := PROBE * PROBE; IF MOD(SQUARE, 1000000) = 269696 THEN BEGIN   OUTTEXT("THE SMALLEST NUMBER: "); OUTINT(PROBE,0); OUTIMAGE;   OUTTEXT("THE SQUARE : "); OUTINT(SQUARE,0); OUTIMAGE;   DONE := TRUE; END; END;   END
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.
#Smalltalk
Smalltalk
"We use one variable, called n. Let it initially be equal to 1. Then keep increasing it by 1 for only as long as the remainder after dividing by a million is not equal to 269,696; finally, show the value of n." | n | n := 1. [ n squared \\ 1000000 = 269696 ] whileFalse: [ n := n + 1 ]. 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.
#XPL0
XPL0
func ApproxEqual(A, B); \Return 'true' if approximately equal real A, B; real Epsilon; [Epsilon:= abs(A) * 1E-15; return abs(A-B) < Epsilon; ];   real Data; int I; [Format(0, 16); Data:=[ [100000000000000.01, 100000000000000.011], \should return true [100.01, 100.011], \should return false [10000000000000.001 / 10000.0, 1000000000.0000001000], [0.001, 0.0010000001], [0.000000000000000000000101, 0.0], \is undefined [sqrt(2.0) * sqrt(2.0), 2.0], [-1.0 * sqrt(2.0) * sqrt(2.0), -2.0], \-sqrt doesn't compile! [3.14159265358979323846, 3.14159265358979324] ]; for I:= 0 to 7 do [IntOut(0, I+1); Text(0, ". "); RlOut(0, Data(I,0)); ChOut(0, ^ ); RlOut(0, Data(I,1)); Text(0, if ApproxEqual(Data(I,0), Data(I,1)) then " true" else " false"); CrLf(0); ]; ]
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.
#zkl
zkl
testValues:=T( T(100000000000000.01,100000000000000.011), T(100.01, 100.011), T(10000000000000.001 / 10000.0, 1000000000.0000001), T(0.001, 0.0010000001), T(0.00000000000000000101, 0.0), T( (2.0).sqrt()*(2.0).sqrt(), 2.0), T( -(2.0).sqrt()*(2.0).sqrt(), -2.0), T(100000000000000003.0, 100000000000000004.0), T(3.14159265358979323846, 3.14159265358979324) );   tolerance:=-1e-9; // <0 for relative comparison foreach x,y in (testValues){ maybeNot:=( if(x.closeTo(y,tolerance)) " \u2248" else "!\u2248" ); println("% 25.19g %s %- 25.19g  %g".fmt(x,maybeNot,y, (x-y).abs())); }
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
#Excel
Excel
bracketReport =LAMBDA(bracketPair, LAMBDA(s, LET( depths, SCANLCOLS( LAMBDA(depth, charDelta, depth + charDelta ) )(0)( codesFromBrackets(bracketPair)( MID(s, SEQUENCE(1, LEN(s), 1, 1), 1 ) ) ), overClosePosn, IFNA(MATCH(-1, depths, 0), 0),   IF(0 <> overClosePosn, "Overclosed at char " & (overClosePosn - 1), IF(0 <> LASTCOL(depths), "Underclosed by end", "OK" ) ) ) ) )     testRandomBrackets =LAMBDA(bracketPair, LAMBDA(n, LET( sample, CONCAT( bracketFromCode(bracketPair)( RANDARRAY(1, n, -1, 1, TRUE) ) ),   APPENDCOLS(sample)( bracketReport(bracketPair)(sample) ) ) ) )     bracketFromCode =LAMBDA(bracketPairString, LAMBDA(c, IF(0 <> c, IF(0 < c, MID(bracketPairString, 1, 1), MID(bracketPairString, 2, 1) ), "x" ) ) )     codesFromBrackets =LAMBDA(bracketPair, LAMBDA(s, LAMBDA(c, LET( posn, IFERROR( FIND(c, bracketPair), 0 ),   rem, "0 for non-bracket chars, (1, -1) for (open, close)", IF(0 <> posn, IF(1 < posn, -1, 1), 0 ) ) )( MID(s, SEQUENCE(1, LEN(s), 1, 1), 1 ) ) ) )
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.
#Java
Java
import static java.util.Objects.requireNonNull;   import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream;   public class RecordAppender { static class Record { private final String account; private final String password; private final int uid; private final int gid; private final List<String> gecos; private final String directory; private final String shell;   public Record(String account, String password, int uid, int gid, List<String> gecos, String directory, String shell) { this.account = requireNonNull(account); this.password = requireNonNull(password); this.uid = uid; this.gid = gid; this.gecos = requireNonNull(gecos); this.directory = requireNonNull(directory); this.shell = requireNonNull(shell); }   @Override public String toString() { return account + ':' + password + ':' + uid + ':' + gid + ':' + String.join(",", gecos) + ':' + directory + ':' + shell; }   public static Record parse(String text) { String[] tokens = text.split(":"); return new Record( tokens[0], tokens[1], Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3]), Arrays.asList(tokens[4].split(",")), tokens[5], tokens[6]); } }   public static void main(String[] args) throws IOException { List<String> rawData = Arrays.asList( "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash", "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash", "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash" );   List<Record> records = rawData.stream().map(Record::parse).collect(Collectors.toList());   Path tmp = Paths.get("_rosetta", ".passwd"); Files.createDirectories(tmp.getParent()); Files.write(tmp, (Iterable<String>) records.stream().limit(2).map(Record::toString)::iterator);   Files.write(tmp, Collections.singletonList(records.get(2).toString()), StandardOpenOption.APPEND);   try (Stream<String> lines = Files.lines(tmp)) { lines.map(Record::parse).forEach(System.out::println); } } }
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
#BASIC256
BASIC256
global values$, keys$ dim values$[1] dim keys$[1]   call updateKey("a","apple") call updateKey("b","banana") call updateKey("c","cucumber")   gosub show   print "I like to eat a " + getValue$("c") + " on my salad."   call deleteKey("b") call updateKey("c","carrot") call updateKey("e","endive") gosub show   end   show: for t = 0 to countKeys()-1 print getKeyByIndex$(t) + " " + getValueByIndex$(t) next t print return   subroutine updateKey(key$, value$) # update or add an item i=findKey(key$) if i=-1 then i = freeKey() keys$[i] = key$ end if values$[i] = value$ end subroutine   subroutine deleteKey(key$) # delete by clearing the key i=findKey(key$) if i<>-1 then keys$[i] = "" end if end subroutine   function freeKey() # find index of a free element in the array for n = 0 to keys$[?]-1 if keys$[n]="" then return n next n redim keys$[n+1] redim values$[n+1] return n end function   function findKey(key$) # return index or -1 if not found for n = 0 to keys$[?]-1 if key$=keys$[n] then return n next n return -1 end function   function getValue$(key$) # return a value by the key or "" if not existing i=findKey(key$) if i=-1 then return "" end if return values$[i] end function   function countKeys() # return number of items # remember to skip the empty keys (deleted ones) k = 0 for n = 0 to keys$[?] -1 if keys$[n]<>"" then k++ next n return k end function   function getValueByIndex$(i) # get a value by the index # remember to skip the empty keys (deleted ones) k = 0 for n = 0 to keys$[?] -1 if keys$[n]<>"" then if k=i then return values$[k] k++ endif next n return "" end function   function getKeyByIndex$(i) # get a key by the index # remember to skip the empty keys (deleted ones) k = 0 for n = 0 to keys$[?] -1 if keys$[n]<>"" then if k=i then return keys$[k] k++ endif next n return "" end function
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
#Factor
Factor
USING: assocs formatting kernel locals make math math.primes.factors sequences.extras ; IN: rosetta-code.anti-primes   <PRIVATE   : count-divisors ( n -- m ) dup 1 = [ group-factors values [ 1 + ] map-product ] unless ;   : (n-anti-primes) ( md n count -- ?md' n' ?count' ) dup 0 > [| max-div! n count! | n count-divisors :> d d max-div > [ d max-div! n , count 1 - count! ] when max-div n dup 60 >= 20 1 ? + count (n-anti-primes) ] when ;   PRIVATE>   : n-anti-primes ( n -- seq ) [ 0 1 ] dip [ (n-anti-primes) 3drop ] { } make ;   : anti-primes-demo ( -- ) 20 n-anti-primes "First 20 anti-primes:\n%[%d, %]\n" printf ;   MAIN: anti-primes-demo
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
#Forth
Forth
  include ./factors.fs   : max-count ( n1 n2 -- n f ) \ n is max(n1, factor-count n2); if n is new maximum then f = true. \ count-factors 2dup < if nip true else drop false then ;   : .anti-primes ( n -- ) 0 1 rot \ stack: max, candidate, count begin >r dup >r max-count if r> dup . r> 1- else r> r> then swap 1+ swap dup 0= until drop 2drop ;   ." The first 20 anti-primes are: " 20 .anti-primes cr bye  
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.
#Python
Python
from __future__ import with_statement # required for Python 2.5 import threading import random import time   terminate = threading.Event()   class Buckets: def __init__(self, nbuckets): self.nbuckets = nbuckets self.values = [random.randrange(10) for i in range(nbuckets)] self.lock = threading.Lock()   def __getitem__(self, i): return self.values[i]   def transfer(self, src, dst, amount): with self.lock: amount = min(amount, self.values[src]) self.values[src] -= amount self.values[dst] += amount   def snapshot(self): # copy of the current state (synchronized) with self.lock: return self.values[:]   def randomize(buckets): nbuckets = buckets.nbuckets while not terminate.isSet(): src = random.randrange(nbuckets) dst = random.randrange(nbuckets) if dst!=src: amount = random.randrange(20) buckets.transfer(src, dst, amount)   def equalize(buckets): nbuckets = buckets.nbuckets while not terminate.isSet(): src = random.randrange(nbuckets) dst = random.randrange(nbuckets) if dst!=src: amount = (buckets[src] - buckets[dst]) // 2 if amount>=0: buckets.transfer(src, dst, amount) else: buckets.transfer(dst, src, -amount)   def print_state(buckets): snapshot = buckets.snapshot() for value in snapshot: print '%2d' % value, print '=', sum(snapshot)   # create 15 buckets buckets = Buckets(15)   # the randomize thread t1 = threading.Thread(target=randomize, args=[buckets]) t1.start()   # the equalize thread t2 = threading.Thread(target=equalize, args=[buckets]) t2.start()   # main thread, display try: while True: print_state(buckets) time.sleep(1) except KeyboardInterrupt: # ^C to finish terminate.set()   # wait until all worker threads finish t1.join() t2.join()
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.
#Objective-C
Objective-C
NSAssert(a == 42, @"Error message");
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.
#OCaml
OCaml
let a = get_some_value () in assert (a = 42); (* throws Assert_failure when a is not 42 *) (* evaluate stuff to return here when a is 42 *)