task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Average_loop_length
Average loop length
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence. Task Write a program or a script that estimates, for each N, the average length until the first such repetition. Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one. This problem comes from the end of Donald Knuth's Christmas tree lecture 2011. Example of expected output: N average analytical (error) === ========= ============ ========= 1 1.0000 1.0000 ( 0.00%) 2 1.4992 1.5000 ( 0.05%) 3 1.8784 1.8889 ( 0.56%) 4 2.2316 2.2188 ( 0.58%) 5 2.4982 2.5104 ( 0.49%) 6 2.7897 2.7747 ( 0.54%) 7 3.0153 3.0181 ( 0.09%) 8 3.2429 3.2450 ( 0.07%) 9 3.4536 3.4583 ( 0.14%) 10 3.6649 3.6602 ( 0.13%) 11 3.8091 3.8524 ( 1.12%) 12 3.9986 4.0361 ( 0.93%) 13 4.2074 4.2123 ( 0.12%) 14 4.3711 4.3820 ( 0.25%) 15 4.5275 4.5458 ( 0.40%) 16 4.6755 4.7043 ( 0.61%) 17 4.8877 4.8579 ( 0.61%) 18 4.9951 5.0071 ( 0.24%) 19 5.1312 5.1522 ( 0.41%) 20 5.2699 5.2936 ( 0.45%)
#F.23
F#
open System   let gamma z = let lanczosCoefficients = [76.18009172947146;-86.50532032941677;24.01409824083091;-1.231739572450155;0.1208650973866179e-2;-0.5395239384953e-5] let rec sumCoefficients acc i coefficients = match coefficients with | [] -> acc | h::t -> sumCoefficients (acc + (h/i)) (i+1.0) t let gamma = 5.0 let x = z - 1.0 Math.Pow(x + gamma + 0.5, x + 0.5) * Math.Exp( -(x + gamma + 0.5) ) * Math.Sqrt( 2.0 * Math.PI ) * sumCoefficients 1.000000000190015 (x + 1.0) lanczosCoefficients   let factorial n = gamma ((float n) + 1.)   let expected n = seq {for i in 1 .. n do yield (factorial n) / System.Math.Pow((float n), (float i)) / (factorial (n - i)) } |> Seq.sum   let r = System.Random()   let trial n = let count = ref 0 let x = ref 1 let bits = ref 0 while (!bits &&& !x) = 0 do count := !count + 1 bits := !bits ||| !x x := 1 <<< r.Next(n) !count     let tested n times = (float (Seq.sum (seq { for i in 1 .. times do yield (trial n) }))) / (float times)   let results = seq { for n in 1 .. 20 do let avg = tested n 1000000 let theory = expected n yield n, avg, theory }     [<EntryPoint>] let main argv = printfn " N average analytical (error)" printfn "------------------------------------" results |> Seq.iter (fun (n, avg, theory) -> printfn "%2i  %2.6f  %2.6f  %+2.3f%%" n avg theory ((avg / theory - 1.) * 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
#PowerShell
PowerShell
  #This version allows a user to enter numbers one at a time to figure this into the SMA calculations   $inputs = @() #Create an array to hold all inputs as they are entered. $period1 = 3 #Define the periods you want to utilize $period2 = 5   Write-host "Enter numbers to observe their moving averages." -ForegroundColor Green   function getSMA ($inputs, [int]$period) #Function takes a array of entered values and a period (3 and 5 in this case) { if($inputs.Count -lt $period){$period = $inputs.Count} #Makes sure that if there's less numbers than the designated period (3 in this case), the number of availble values is used as the period instead.   for($count = 0; $count -lt $period; $count++) #Loop sums the latest available values { $result += $inputs[($inputs.Count) - $count - 1] }   return ($result | ForEach-Object -begin {$sum=0 }-process {$sum+=$_} -end {$sum/$period}) #Gets the average for a given period }   while($true) #Infinite loop so the user can keep entering numbers { try{$inputs += [decimal] (Read-Host)}catch{Write-Host "Enter only numbers" -ForegroundColor Red} #Enter the numbers. Error checking to help mitigate bad inputs (non-number values)   "Added " + $inputs[(($inputs.Count) - 1)] + ", sma($period1) = " + (getSMA $inputs $Period1) + ", sma($period2) = " + (getSMA $inputs $period2) }  
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.
#CLU
CLU
sieve = proc (max: int) returns (array[bool]) prime: array[bool] := array[bool]$fill(1,max,true) prime[1] := false for p: int in int$from_to(2, max/2) do if prime[p] then for c: int in int$from_to_by(p*p, max, p) do prime[c] := false end end end return(prime) end sieve   n_factors = proc (n: int, prime: array[bool]) returns (int) count: int := 0 i: int := 2 while i<=n do if prime[i] then while n//i=0 do count := count + 1 n := n/i end end i := i + 1 end return(count) end n_factors   start_up = proc () MAX = 120 po: stream := stream$primary_output() prime: array[bool] := sieve(MAX) col: int := 0 for i: int in int$from_to(2, MAX) do if prime[n_factors(i,prime)] then stream$putright(po, int$unparse(i), 4) col := col + 1 if col//15 = 0 then stream$putl(po, "") end end end end start_up
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.
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. ATTRACTIVE-NUMBERS.   DATA DIVISION. WORKING-STORAGE SECTION. 77 MAXIMUM PIC 999 VALUE 120. 01 SIEVE-DATA VALUE SPACES. 03 MARKER PIC X OCCURS 120 TIMES. 88 PRIME VALUE SPACE. 03 SIEVE-MAX PIC 999. 03 COMPOSITE PIC 999. 03 CANDIDATE PIC 999.   01 FACTORIZE-DATA. 03 FACTOR-NUM PIC 999. 03 FACTORS PIC 999. 03 FACTOR PIC 999. 03 QUOTIENT PIC 999V999. 03 FILLER REDEFINES QUOTIENT. 05 FILLER PIC 999. 05 DECIMAL PIC 999.   01 OUTPUT-FORMAT. 03 OUT-NUM PIC ZZZ9. 03 OUT-LINE PIC X(72) VALUE SPACES. 03 COL-PTR PIC 99 VALUE 1.   PROCEDURE DIVISION. BEGIN. PERFORM SIEVE. PERFORM CHECK-ATTRACTIVE VARYING CANDIDATE FROM 2 BY 1 UNTIL CANDIDATE IS GREATER THAN MAXIMUM. PERFORM WRITE-LINE. STOP RUN.   CHECK-ATTRACTIVE. MOVE CANDIDATE TO FACTOR-NUM. PERFORM FACTORIZE. IF PRIME(FACTORS), PERFORM ADD-TO-OUTPUT.   ADD-TO-OUTPUT. MOVE CANDIDATE TO OUT-NUM. STRING OUT-NUM DELIMITED BY SIZE INTO OUT-LINE WITH POINTER COL-PTR. IF COL-PTR IS EQUAL TO 73, PERFORM WRITE-LINE.   WRITE-LINE. DISPLAY OUT-LINE. MOVE SPACES TO OUT-LINE. MOVE 1 TO COL-PTR.   FACTORIZE SECTION. BEGIN. MOVE ZERO TO FACTORS. PERFORM DIVIDE-PRIME VARYING FACTOR FROM 2 BY 1 UNTIL FACTOR IS GREATER THAN MAXIMUM. GO TO DONE.   DIVIDE-PRIME. IF PRIME(FACTOR), DIVIDE FACTOR-NUM BY FACTOR GIVING QUOTIENT, IF DECIMAL IS EQUAL TO ZERO, ADD 1 TO FACTORS, MOVE QUOTIENT TO FACTOR-NUM, GO TO DIVIDE-PRIME. DONE. EXIT.   SIEVE SECTION. BEGIN. MOVE 'X' TO MARKER(1). DIVIDE MAXIMUM BY 2 GIVING SIEVE-MAX. PERFORM SET-COMPOSITES THRU SET-COMPOSITES-LOOP VARYING CANDIDATE FROM 2 BY 1 UNTIL CANDIDATE IS GREATER THAN SIEVE-MAX. GO TO DONE.   SET-COMPOSITES. MULTIPLY CANDIDATE BY 2 GIVING COMPOSITE. SET-COMPOSITES-LOOP. IF COMPOSITE IS NOT GREATER THAN MAXIMUM, MOVE 'X' TO MARKER(COMPOSITE), ADD CANDIDATE TO COMPOSITE, GO TO SET-COMPOSITES-LOOP. DONE. EXIT.
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
#Haskell
Haskell
import Data.Complex (cis, phase) import Data.List.Split (splitOn) import Text.Printf (printf)   timeToRadians :: String -> Float timeToRadians time = let hours:minutes:seconds:_ = splitOn ":" time s = fromIntegral (read seconds :: Int) m = fromIntegral (read minutes :: Int) h = fromIntegral (read hours :: Int) in (2*pi)*(h+ (m + s/60.0 )/60.0 )/24.0   radiansToTime :: Float -> String radiansToTime r = let tau = pi*2 (_,fDay) = properFraction (r / tau) :: (Int, Float) fDayPositive = if fDay < 0 then 1.0+fDay else fDay (hours, fHours) = properFraction $ 24.0 * fDayPositive (minutes, fMinutes) = properFraction $ 60.0 * fHours seconds = 60.0 * fMinutes in printf "%0d" (hours::Int) ++ ":" ++ printf "%0d" (minutes::Int) ++ ":" ++ printf "%0.0f" (seconds::Float)   meanAngle :: [Float] -> Float meanAngle = phase . sum . map cis   main :: IO () main = putStrLn $ radiansToTime $ meanAngle $ map timeToRadians ["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.
#J
J
insert=: {{ X=.1 {::2{.x,x NB. middle element of x (don't fail on empty x) Y=.1 {::2{.y,y NB. middle element of y (don't fail on empty y) select.#y case.0 do.x NB. y is an empty node case.1 do. NB. y is a leaf node select.*Y-X case._1 do.a:,y;<x case. 0 do.y case. 1 do.x;y;a: end. case.3 do. NB. y is a parent node select.*Y-X case._1 do.balance (}:y),<x insert 2{::y case. 0 do.y case. 1 do.balance (x insert 0{::y);}.y end. end. }}   delete=: {{ select.#y case.0 do.y case.1 do.y-.x case.3 do. select.*(1{::y)-x case._1 do.balance (}:y),<x delete 2{::y case. 0 do.balance (0{::y) insert 2{::y case. 1 do.balance (x delete 0{::y);}.y end. end. }}   lookup=: {{ select.#y case.0 do.y case.1 do.if.x=y do.y else.'' end. case.3 do. select.*(1{::y)-x case._1 do.x lookup 2{::y case. 0 do.y case. 1 do.x lookup 0{::y end. end. }}   clean=: {{ 's0 x s2'=. #every y if.*/0=s0,s2 do. 1{:: y NB. degenerate to leaf else. y end. }}   balance=: {{ if. 2>#y do. y return.end. NB. leaf or empty 's0 x s2'=. ,#every y if. */0=s0,s2 do. 1{:: y return.end. NB. degenerate to leaf 'l0 x l2'=. L.every y if. 2>|l2-l0 do. y return.end. NB. adequately balanced if. l2>l0 do. 'l20 x l22'=. L.every 2{::y if. l22 >: l20 do. rotLeft y else. rotRightLeft y end. else. 'l00 x l02'=. L.every 0{::y if. l00 >: l02 do. rotRight y else. rotLeftRight y end. end. }}   rotLeft=: {{ 't0 t1 t2'=. y 't20 t21 t22'=. t2 (clean t0;t1;<t20);t21;<t22 }}   rotRight=: {{ 't0 t1 t2'=. y 't00 t01 t02'=. t0 t00;t01;<clean t02;t1;<t2 }}   rotRightLeft=: {{ 't0 t1 t2'=. y rotLeft t0;t1;<rotRight t2 }}   rotLeftRight=: {{ 't0 t1 t2'=. y rotRight (rotLeft t0);t1;<t2 }}
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
#FreeBASIC
FreeBASIC
  ' FB 1.05.0 Win64   Const PI As Double = 3.1415926535897932   Function MeanAngle(angles() As Double) As Double Dim As Integer length = Ubound(angles) - Lbound(angles) + 1 Dim As Double sinSum = 0.0 Dim As Double cosSum = 0.0 For i As Integer = LBound(angles) To UBound(angles) sinSum += Sin(angles(i) * PI / 180.0) cosSum += Cos(angles(i) * PI / 180.0) Next Return Atan2(sinSum / length, cosSum / length) * 180.0 / PI End Function   Dim As Double angles1(1 To 2) = {350, 10} Dim As Double angles2(1 To 4) = {90, 180, 270, 360} Dim As Double angles3(1 To 3) = {10, 20, 30}   Print Using "Mean for angles 1 is : ####.## degrees"; MeanAngle(angles1()) Print Using "Mean for angles 2 is : ####.## degrees"; MeanAngle(angles2()) Print Using "Mean for angles 3 is : ####.## degrees"; MeanAngle(angles3()) Print Print "Press any key to quit the program" Sleep  
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
#C.2B.2B
C++
#include <algorithm>   // inputs must be random-access iterators of doubles // Note: this function modifies the input range template <typename Iterator> double median(Iterator begin, Iterator end) { // this is middle for odd-length, and "upper-middle" for even length Iterator middle = begin + (end - begin) / 2;   // This function runs in O(n) on average, according to the standard std::nth_element(begin, middle, end);   if ((end - begin) % 2 != 0) { // odd length return *middle; } else { // even length // the "lower middle" is the max of the lower half Iterator lower_middle = std::max_element(begin, middle); return (*middle + *lower_middle) / 2.0; } }   #include <iostream>   int main() { double a[] = {4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2}; double b[] = {4.1, 7.2, 1.7, 9.3, 4.4, 3.2};   std::cout << median(a+0, a + sizeof(a)/sizeof(a[0])) << std::endl; // 4.4 std::cout << median(b+0, b + sizeof(b)/sizeof(b[0])) << std::endl; // 4.25   return 0; }
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
#FunL
FunL
import lists.zip   def mean( s, 0 ) = product( s )^(1/s.length()) mean( s, p ) = (1/s.length() sum( x^p | x <- s ))^(1/p)   def monotone( [_], _ ) = true monotone( a1:a2:as, p ) = p( a1, a2 ) and monotone( a2:as, p )   means = [mean( 1..10, m ) | m <- [1, 0, -1]]   for (m, l) <- zip( means, ['Arithmetic', 'Geometric', 'Harmonic'] ) println( "$l: $m" + (if m is Rational then " or ${m.doubleValue()}" else '') )   println( monotone(means, (>=)) )
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.
#Julia
Julia
struct BalancedTernary <: Signed digits::Vector{Int8} end BalancedTernary() = zero(BalancedTernary) BalancedTernary(n) = convert(BalancedTernary, n)   const sgn2chr = Dict{Int8,Char}(-1 => '-', 0 => '0', +1 => '+') Base.show(io::IO, bt::BalancedTernary) = print(io, join(sgn2chr[x] for x in reverse(bt.digits))) Base.copy(bt::BalancedTernary) = BalancedTernary(copy(bt.digits)) Base.zero(::Type{BalancedTernary}) = BalancedTernary(Int8[0]) Base.iszero(bt::BalancedTernary) = bt.digits == Int8[0] Base.convert(::Type{T}, bt::BalancedTernary) where T<:Number = sum(3 ^ T(ex - 1) * s for (ex, s) in enumerate(bt.digits)) function Base.convert(::Type{BalancedTernary}, n::Signed) r = BalancedTernary(Int8[]) if iszero(n) push!(r.digits, 0) end while n != 0 if mod(n, 3) == 0 push!(r.digits, 0) n = fld(n, 3) elseif mod(n, 3) == 1 push!(r.digits, 1) n = fld(n, 3) else push!(r.digits, -1) n = fld(n + 1, 3) end end return r end const chr2sgn = Dict{Char,Int8}('-' => -1, '0' => 0, '+' => 1) function Base.convert(::Type{BalancedTernary}, s::AbstractString) return BalancedTernary(getindex.(chr2sgn, collect(reverse(s)))) end   macro bt_str(s) convert(BalancedTernary, s) end   const table = NTuple{2,Int8}[(0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)] function _add(a::Vector{Int8}, b::Vector{Int8}, c::Int8=Int8(0)) if isempty(a) || isempty(b) if c == 0 return isempty(a) ? b : a end return _add([c], isempty(a) ? b : a) else d, c = table[4 + (isempty(a) ? 0 : a[1]) + (isempty(b) ? 0 : b[1]) + c] r = _add(a[2:end], b[2:end], c) if !isempty(r) || d != 0 return unshift!(r, d) else return r end end end function Base.:+(a::BalancedTernary, b::BalancedTernary) v = _add(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end Base.:-(bt::BalancedTernary) = BalancedTernary(-bt.digits) Base.:-(a::BalancedTernary, b::BalancedTernary) = a + (-b) function _mul(a::Vector{Int8}, b::Vector{Int8}) if isempty(a) || isempty(b) return Int8[] else if a[1] == -1 x = (-BalancedTernary(b)).digits elseif a[1] == 0 x = Int8[] elseif a[1] == 1 x = b end y = append!(Int8[0], _mul(a[2:end], b)) return _add(x, y) end end function Base.:*(a::BalancedTernary, b::BalancedTernary) v = _mul(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end   a = bt"+-0++0+" println("a: $(Int(a)), $a") b = BalancedTernary(-436) println("b: $(Int(b)), $b") c = BalancedTernary("+-++-") println("c: $(Int(c)), $c") r = a * (b - c) println("a * (b - c): $(Int(r)), $r")   @assert Int(r) == Int(a) * (Int(b) - Int(c))
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.
#Phix
Phix
with javascript_semantics for i=2 to 99736 by 2 do if remainder(i*i,1000000)=269696 then ?i exit end if end for
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.
#C
C
#include <math.h> #include <stdbool.h> #include <stdio.h>   bool approxEquals(double value, double other, double epsilon) { return fabs(value - other) < epsilon; }   void test(double a, double b) { double epsilon = 1e-18; printf("%f, %f => %d\n", a, b, approxEquals(a, b, epsilon)); }   int main() { test(100000000000000.01, 100000000000000.011); test(100.01, 100.011); test(10000000000000.001 / 10000.0, 1000000000.0000001000); test(0.001, 0.0010000001); test(0.000000000000000000000101, 0.0); test(sqrt(2.0) * sqrt(2.0), 2.0); test(-sqrt(2.0) * sqrt(2.0), -2.0); test(3.14159265358979323846, 3.14159265358979324); return 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.
#C.23
C#
using System;   public static class Program { public static void Main() { Test(100000000000000.01, 100000000000000.011); Test(100.01, 100.011); Test(10000000000000.001 / 10000.0, 1000000000.0000001000); Test(0.001, 0.0010000001); Test(0.000000000000000000000101, 0.0); Test(Math.Sqrt(2) * Math.Sqrt(2), 2.0); Test(-Math.Sqrt(2) * Math.Sqrt(2), -2.0); Test(3.14159265358979323846, 3.14159265358979324);   void Test(double a, double b) { const double epsilon = 1e-18; WriteLine($"{a}, {b} => {a.ApproxEquals(b, epsilon)}"); } }   public static bool ApproxEquals(this double value, double other, double epsilon) => Math.Abs(value - other) < epsilon; }
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
#Brat
Brat
string.prototype.balanced? = { brackets = [] balanced = true   my.dice.each_while { c | true? c == "[" { brackets << c } { true? c == "]" { last = brackets.pop false? last == "[" { balanced = false } } }   balanced }   true? brackets.empty? { balanced } { false } }   generate_brackets = { n | (n.of("[") + n.of("]")).shuffle.join }   1.to 10 { n | test = generate_brackets n   true? test.balanced? { p "#{test} is balanced" } { p "#{test} is not balanced" } }
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.
#C.23
C#
- Changed to using object locks and Montor.Enter rather than Mutexes. This allows use of the cleaner "lock" statement, and also has lower runtime overhead for in process locks - The previous implementation tracked a "swapped" state - which seems a harder way to tackle the problem. You need to acquire the locks in the correct order, not swap i and j
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.
#C.2B.2B
C++
#include <algorithm> #include <array> #include <chrono> #include <iomanip> #include <iostream> #include <mutex> #include <random> #include <thread>   using namespace std;   constexpr int bucket_count = 15;   void equalizer(array<int, bucket_count>& buckets, array<mutex, bucket_count>& bucket_mutex) { random_device rd; mt19937 gen(rd()); uniform_int_distribution<> dist_bucket(0, bucket_count - 1);   while (true) { int from = dist_bucket(gen); int to = dist_bucket(gen); if (from != to) { lock_guard<mutex> lock_first(bucket_mutex[min(from, to)]); lock_guard<mutex> lock_second(bucket_mutex[max(from, to)]); int diff = buckets[from] - buckets[to]; int amount = abs(diff / 2); if (diff < 0) { swap(from, to); } buckets[from] -= amount; buckets[to] += amount; } } }   void randomizer(array<int, bucket_count>& buckets, array<mutex, bucket_count>& bucket_mutex) { random_device rd; mt19937 gen(rd()); uniform_int_distribution<> dist_bucket(0, bucket_count - 1);   while (true) { int from = dist_bucket(gen); int to = dist_bucket(gen); if (from != to) { lock_guard<mutex> lock_first(bucket_mutex[min(from, to)]); lock_guard<mutex> lock_second(bucket_mutex[max(from, to)]); uniform_int_distribution<> dist_amount(0, buckets[from]); int amount = dist_amount(gen); buckets[from] -= amount; buckets[to] += amount; } } }   void print_buckets(const array<int, bucket_count>& buckets) { int total = 0; for (const int& bucket : buckets) { total += bucket; cout << setw(3) << bucket << ' '; } cout << "= " << setw(3) << total << endl; }   int main() { random_device rd; mt19937 gen(rd()); uniform_int_distribution<> dist(0, 99);   array<int, bucket_count> buckets; array<mutex, bucket_count> bucket_mutex; for (int& bucket : buckets) { bucket = dist(gen); } print_buckets(buckets);   thread t_eq(equalizer, ref(buckets), ref(bucket_mutex)); thread t_rd(randomizer, ref(buckets), ref(bucket_mutex));   while (true) { this_thread::sleep_for(chrono::seconds(1)); for (mutex& mutex : bucket_mutex) { mutex.lock(); } print_buckets(buckets); for (mutex& mutex : bucket_mutex) { mutex.unlock(); } } return 0; }
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.
#Axe
Axe
A=42??Returnʳ
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.
#BaCon
BaCon
' Assertions answer = assertion(42) PRINT "The ultimate answer is indeed ", answer   PRINT "Now, expect a failure, unless NDEBUG defined at compile time" answer = assertion(41) PRINT answer END   ' Ensure the given number is the ultimate answer FUNCTION assertion(NUMBER i)   ' BaCon can easily be intimately integrated with C USEH #include <assert.h> END USEH   ' If the given expression is not true, abort the program USEC assert(i == 42); END USEC   RETURN i END FUNCTION
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.
#BASIC256
BASIC256
  subroutine assert (condition, message) if not condition then print "ASSERTION FAIED: ";message: throwerror 1 end subroutine   call assert(1+1=2, "but I don't expect this assertion to fail"): rem Does not throw an error rem call assert(1+1=3, "and rightly so"): rem Throws an error  
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
#J
J
mode=: ~. #~ ( = >./ )@( #/.~ )
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
#Java
Java
import java.util.*;   public class Mode { public static <T> List<T> mode(List<? extends T> coll) { Map<T, Integer> seen = new HashMap<T, Integer>(); int max = 0; List<T> maxElems = new ArrayList<T>(); for (T value : coll) { if (seen.containsKey(value)) seen.put(value, seen.get(value) + 1); else seen.put(value, 1); if (seen.get(value) > max) { max = seen.get(value); maxElems.clear(); maxElems.add(value); } else if (seen.get(value) == max) { maxElems.add(value); } } return maxElems; }   public static void main(String[] args) { System.out.println(mode(Arrays.asList(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17))); // prints [6] System.out.println(mode(Arrays.asList(1, 1, 2, 4, 4))); // prints [1, 4] } }
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#8th
8th
  {"one": 1, "two": "bad"} ( swap . space . cr ) m:each  
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
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Containers.Indefinite_Ordered_Maps;   procedure Test_Iteration is package String_Maps is new Ada.Containers.Indefinite_Ordered_Maps (String, Integer); use String_Maps; A  : Map; Index : Cursor; begin A.Insert ("hello", 1); A.Insert ("world", 2); A.Insert ("!", 3); Index := A.First; while Index /= No_Element loop Put_Line (Key (Index) & Integer'Image (Element (Index))); Index := Next (Index); end loop; end Test_Iteration;
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]
#Ada
Ada
with Ada.Text_IO;   procedure Apply_Filter is   generic type Num is digits <>; type Num_Array is array (Natural range <>) of Num; A : Num_Array; B : Num_Array; package Direct_Form_II_Transposed is pragma Assert (A'First = 0 and B'First = 0); pragma Assert (A'Last = B'Last); pragma Assert (A (0) = 1.000);   function Filter (X : in Num) return Num; end Direct_Form_II_Transposed;   package body Direct_Form_II_Transposed is W : Num_Array (A'Range) := (others => 0.0);   function Filter (X : in Num) return Num is Y : constant Num := X * B (0) + W (0); begin -- Calculate delay line for next sample for I in 1 .. W'Last loop W (I - 1) := X * B (I) - Y * A (I) + W (I); end loop; return Y; end Filter;   end Direct_Form_II_Transposed;   type Coeff_Array is array (Natural range <>) of Float;   package Butterworth is new Direct_Form_II_Transposed (Float, Coeff_Array, A => (1.000000000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17), B => (0.16666667, 0.50000000, 0.50000000, 0.16666667));   subtype Signal_Array is Coeff_Array;   X_Signal : constant Signal_Array := (-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);   package Float_IO is new Ada.Text_IO.Float_IO (Float); Y : Float; begin for Sample of X_Signal loop Y := Butterworth.Filter (Sample); Float_IO.Put (Y, Exp => 0, Aft => 6); Ada.Text_IO.New_Line; end loop; end Apply_Filter;
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
#Arturo
Arturo
arr: [1 2 3 4 5 6 7]   print average arr
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
#Astro
Astro
mean([1, 2, 3]) mean(1..10) mean([])  
http://rosettacode.org/wiki/Associative_array/Merging
Associative array/Merging
Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be: Key Value "name" "Rocket Skates" "price" 15.25 "color" "red" "year" 1974
#Dart
Dart
  main() { var base = { 'name': 'Rocket Skates', 'price': 12.75, 'color': 'yellow' };   var newData = { 'price': 15.25, 'color': 'red', 'year': 1974 };   var updated = Map.from( base ) // create new Map from base ..addAll( newData ); // use cascade operator to add all new data   assert( base.toString() == '{name: Rocket Skates, price: 12.75, color: yellow}' ); assert( updated.toString() == '{name: Rocket Skates, price: 15.25, color: red, year: 1974}');     }  
http://rosettacode.org/wiki/Associative_array/Merging
Associative array/Merging
Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be: Key Value "name" "Rocket Skates" "price" 15.25 "color" "red" "year" 1974
#Delphi
Delphi
  program Associative_arrayMerging;   {$APPTYPE CONSOLE}   uses System.Generics.Collections;   type TData = TDictionary<string, Variant>;   var baseData, updateData, mergedData: TData; entry: string;   begin baseData := TData.Create(); baseData.Add('name', 'Rocket Skates'); baseData.Add('price', 12.75); baseData.Add('color', 'yellow');   updateData := TData.Create(); updateData.Add('price', 15.25); updateData.Add('color', 'red'); updateData.Add('year', 1974);   mergedData := TData.Create(); for entry in baseData.Keys do mergedData.AddOrSetValue(entry, baseData[entry]);   for entry in updateData.Keys do mergedData.AddOrSetValue(entry, updateData[entry]);   for entry in mergedData.Keys do Writeln(entry, ' ', mergedData[entry]);   mergedData.Free; updateData.Free; baseData.Free;   Readln; 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%)
#Factor
Factor
USING: formatting fry io kernel locals math math.factorials math.functions math.ranges random sequences ;   : (analytical) ( m n -- x ) [ drop factorial ] [ ^ /f ] [ - factorial / ] 2tri ;   : analytical ( n -- x ) dup [1,b] [ (analytical) ] with map-sum ;   : loop-length ( n -- x ) [ 0 0 1 [ 2dup bitand zero? ] ] dip '[ [ 1 + ] 2dip bitor 1 _ random shift ] while 2drop ;   :: average-loop-length ( n #tests -- x ) 0 #tests [ n loop-length + ] times #tests / ;   : stats ( n -- avg exp ) [ 1,000,000 average-loop-length ] [ analytical ] bi ;   : .line ( n -- ) dup stats 2dup / 1 - 100 * "%2d %8.4f %8.4f %6.3f%%\n" printf ;   " n\tavg\texp.\tdiff\n-------------------------------" print 20 [1,b] [ .line ] each
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%)
#FreeBASIC
FreeBASIC
Const max_N = 20, max_ciclos = 1000000   Function Factorial(Byval N As Integer) As Double Dim As Double d: d = 1 If N = 0 Then Factorial = 1: Exit Function While (N > 1) d *= N N -= 1 Wend Factorial = d End Function   Function Analytical(N As Integer) As Double Dim As Double i, sum = 0 For i = 1 To N sum += Factorial(N) / N^i / Factorial(N-i) Next i Return sum End Function   Function Average(N As Integer, ciclos As Double) As Double Dim As Integer i, x, bits, sum = 0 For i = 0 To ciclos - 1 x = 1 : bits = 0 While (bits And x) = 0 sum += 1 bits Or= x x = 1 Shl (Rnd * (N - 1)) Wend Next i Return sum / ciclos End Function   Randomize Timer Print " N promedio analitico (error)" Print "--- ---------- ----------- ----------" For N As Integer = 1 To max_N Dim As Double avg = Average(N, max_ciclos) Dim As Double ana = Analytical(N) Dim As Double diff = abs(avg-ana) / ana * 100 Print Using " ## #####.###0 #####.###0 ###.#0%"; N; avg; ana; diff Next N Sleep  
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
#PureBasic
PureBasic
Procedure.d SMA(Number, Period=0) Static P Static NewList L() Protected Sum=0 If Period<>0 P=Period EndIf LastElement(L()) AddElement(L()) L()=Number While ListSize(L())>P FirstElement(L()) DeleteElement(L(),1) Wend ForEach L() sum+L() Next ProcedureReturn sum/ListSize(L()) EndProcedure
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.
#Comal
Comal
0010 FUNC factors#(n#) CLOSED 0020 count#:=0 0030 WHILE n# MOD 2=0 DO n#:=n# DIV 2;count#:+1 0040 fac#:=3 0050 WHILE fac#<=n# DO 0060 WHILE n# MOD fac#=0 DO n#:=n# DIV fac#;count#:+1 0070 fac#:+2 0080 ENDWHILE 0090 RETURN count# 0100 ENDFUNC factors# 0110 // 0120 ZONE 4 0130 seen#:=0 0140 FOR i#:=2 TO 120 DO 0150 IF factors#(factors#(i#))=1 THEN 0160 PRINT i#, 0170 seen#:+1 0180 IF seen# MOD 18=0 THEN PRINT 0190 ENDIF 0200 ENDFOR i# 0210 PRINT 0220 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.
#Common_Lisp
Common Lisp
  (defun attractivep (n) (primep (length (factors n))) )   ; For primality testing we can use different methods, but since we have to define factors that's what we'll use (defun primep (n) (= (length (factors n)) 1) )   (defun factors (n) "Return a list of factors of N." (when (> n 1) (loop with max-d = (isqrt n) for d = 2 then (if (evenp d) (+ d 1) (+ d 2)) do (cond ((> d max-d) (return (list n))) ; n is prime ((zerop (rem n d)) (return (cons d (factors (truncate n d)))))))))  
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
#Icon_and_Unicon
Icon and Unicon
procedure main(A) every put(B := [], ct2a(!A)) write(ca2t(meanAngle(B))) end   procedure ct2a(t) t ? {s := ((1(move(2),move(1))*60 + 1(move(2),move(1)))*60 + move(2))} return (360.0/86400.0) * s end   procedure ca2t(a) while a < 0 do a +:= 360.0 t := integer((86400.0/360.0)*a + 0.5) s := left(1(.t % 60, t /:= 60),2,"0") s := left(1(.t % 60, t /:= 60),2,"0")||":"||s s := left(t,2,"0")||":"||s return s end   procedure meanAngle(A) every (sumSines := 0.0) +:= sin(dtor(!A)) every (sumCosines := 0.0) +:= cos(dtor(!A)) return rtod(atan(sumSines/*A,sumCosines/*A)) 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
#J
J
require 'types/datetime' parseTimes=: ([: _&".;._2 ,&':');._2 secsFromTime=: 24 60 60 #. ] NB. convert from time to seconds rft=: 2r86400p1 * secsFromTime NB. convert from time to radians meanTime=: 'hh:mm:ss' fmtTime [: secsFromTime [: avgAngleR&.rft parseTimes
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.
#Java
Java
public class AVLtree {   private Node root;   private static class Node { private int key; private int balance; private int height; private Node left; private Node right; private Node parent;   Node(int key, Node parent) { this.key = key; this.parent = parent; } }   public boolean insert(int key) { if (root == null) { root = new Node(key, null); return true; }   Node n = root; while (true) { if (n.key == key) return false;   Node parent = n;   boolean goLeft = n.key > key; n = goLeft ? n.left : n.right;   if (n == null) { if (goLeft) { parent.left = new Node(key, parent); } else { parent.right = new Node(key, parent); } rebalance(parent); break; } } return true; }   private void delete(Node node) { if (node.left == null && node.right == null) { if (node.parent == null) { root = null; } else { Node parent = node.parent; if (parent.left == node) { parent.left = null; } else { parent.right = null; } rebalance(parent); } return; }   if (node.left != null) { Node child = node.left; while (child.right != null) child = child.right; node.key = child.key; delete(child); } else { Node child = node.right; while (child.left != null) child = child.left; node.key = child.key; delete(child); } }   public void delete(int delKey) { if (root == null) return;   Node child = root; while (child != null) { Node node = child; child = delKey >= node.key ? node.right : node.left; if (delKey == node.key) { delete(node); return; } } }   private void rebalance(Node n) { setBalance(n);   if (n.balance == -2) { if (height(n.left.left) >= height(n.left.right)) n = rotateRight(n); else n = rotateLeftThenRight(n);   } else if (n.balance == 2) { if (height(n.right.right) >= height(n.right.left)) n = rotateLeft(n); else n = rotateRightThenLeft(n); }   if (n.parent != null) { rebalance(n.parent); } else { root = n; } }   private Node rotateLeft(Node a) {   Node b = 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; } }   setBalance(a, b);   return b; }   private Node rotateRight(Node a) {   Node b = 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; } }   setBalance(a, b);   return b; }   private Node rotateLeftThenRight(Node n) { n.left = rotateLeft(n.left); return rotateRight(n); }   private Node rotateRightThenLeft(Node n) { n.right = rotateRight(n.right); return rotateLeft(n); }   private int height(Node n) { if (n == null) return -1; return n.height; }   private void setBalance(Node... nodes) { for (Node n : nodes) { reheight(n); n.balance = height(n.right) - height(n.left); } }   public void printBalance() { printBalance(root); }   private void printBalance(Node n) { if (n != null) { printBalance(n.left); System.out.printf("%s ", n.balance); printBalance(n.right); } }   private void reheight(Node node) { if (node != null) { node.height = 1 + Math.max(height(node.left), height(node.right)); } }   public static void main(String[] args) { AVLtree tree = new AVLtree();   System.out.println("Inserting values 1 to 10"); for (int i = 1; i < 10; i++) tree.insert(i);   System.out.print("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
#Go
Go
package main   import ( "fmt" "math" "math/cmplx" )   func deg2rad(d float64) float64 { return d * math.Pi / 180 } func rad2deg(r float64) float64 { return r * 180 / math.Pi }   func mean_angle(deg []float64) float64 { sum := 0i for _, x := range deg { sum += cmplx.Rect(1, deg2rad(x)) } return rad2deg(cmplx.Phase(sum)) }   func main() { for _, angles := range [][]float64{ {350, 10}, {90, 180, 270, 360}, {10, 20, 30}, } { fmt.Printf("The mean angle of %v is: %f degrees\n", angles, mean_angle(angles)) } }
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
#Clojure
Clojure
(defn median [ns] (let [ns (sort ns) cnt (count ns) mid (bit-shift-right cnt 1)] (if (odd? cnt) (nth ns mid) (/ (+ (nth ns mid) (nth ns (dec mid))) 2))))
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches 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
#COBOL
COBOL
FUNCTION MEDIAN(some-table (ALL))
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
#Futhark
Futhark
  fun arithmetic_mean(as: [n]f64): f64 = reduce (+) 0.0 (map (/f64(n)) as)   fun geometric_mean(as: [n]f64): f64 = reduce (*) 1.0 (map (**(1.0/f64(n))) as)   fun harmonic_mean(as: [n]f64): f64 = f64(n) / reduce (+) 0.0 (map (1.0/) as)   fun main(as: [n]f64): (f64,f64,f64) = (arithmetic_mean as, geometric_mean as, harmonic_mean as)  
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.
#Kotlin
Kotlin
// version 1.1.3   import java.math.BigInteger   val bigZero = BigInteger.ZERO val bigOne = BigInteger.ONE val bigThree = BigInteger.valueOf(3L)   data class BTernary(private var value: String) : Comparable<BTernary> {   init { require(value.all { it in "0+-" }) value = value.trimStart('0') }   constructor(v: Int) : this(BigInteger.valueOf(v.toLong()))   constructor(v: BigInteger) : this("") { value = toBT(v) }   private fun toBT(v: BigInteger): String { if (v < bigZero) return flip(toBT(-v)) if (v == bigZero) return "" val rem = mod3(v) return when (rem) { bigZero -> toBT(v / bigThree) + "0" bigOne -> toBT(v / bigThree) + "+" else -> toBT((v + bigOne) / bigThree) + "-" } }   private fun flip(s: String): String { val sb = StringBuilder() for (c in s) { sb.append(when (c) { '+' -> "-" '-' -> "+" else -> "0" }) } return sb.toString() }   private fun mod3(v: BigInteger): BigInteger { if (v > bigZero) return v % bigThree return ((v % bigThree) + bigThree) % bigThree }   fun toBigInteger(): BigInteger { val len = value.length var sum = bigZero var pow = bigOne for (i in 0 until len) { val c = value[len - i - 1] val dig = when (c) { '+' -> bigOne '-' -> -bigOne else -> bigZero } if (dig != bigZero) sum += dig * pow pow *= bigThree } return sum }   private fun addDigits(a: Char, b: Char, carry: Char): String { val sum1 = addDigits(a, b) val sum2 = addDigits(sum1.last(), carry) return when { sum1.length == 1 -> sum2 sum2.length == 1 -> sum1.take(1) + sum2 else -> sum1.take(1) } }   private fun addDigits(a: Char, b: Char): String = when { a == '0' -> b.toString() b == '0' -> a.toString() a == '+' -> if (b == '+') "+-" else "0" else -> if (b == '+') "0" else "-+" }   operator fun plus(other: BTernary): BTernary { var a = this.value var b = other.value val longer = if (a.length > b.length) a else b var shorter = if (a.length > b.length) b else a while (shorter.length < longer.length) shorter = "0" + shorter a = longer b = shorter var carry = '0' var sum = "" for (i in 0 until a.length) { val place = a.length - i - 1 val digisum = addDigits(a[place], b[place], carry) carry = if (digisum.length != 1) digisum[0] else '0' sum = digisum.takeLast(1) + sum } sum = carry.toString() + sum return BTernary(sum) }   operator fun unaryMinus() = BTernary(flip(this.value))   operator fun minus(other: BTernary) = this + (-other)   operator fun times(other: BTernary): BTernary { var that = other val one = BTernary(1) val zero = BTernary(0) var mul = zero var flipFlag = false if (that < zero) { that = -that flipFlag = true } var i = one while (i <= that) { mul += this i += one } if (flipFlag) mul = -mul return mul }   override operator fun compareTo(other: BTernary) = this.toBigInteger().compareTo(other.toBigInteger())   override fun toString() = value }   fun main(args: Array<String>) { val a = BTernary("+-0++0+") val b = BTernary(-436) val c = BTernary("+-++-") println("a = ${a.toBigInteger()}") println("b = ${b.toBigInteger()}") println("c = ${c.toBigInteger()}") val bResult = a * (b - c) val iResult = bResult.toBigInteger() println("a * (b - c) = $bResult = $iResult") }
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.
#PHP
PHP
<?php   for ( $i = 1 ; // Initial positive integer to check ($i * $i) % 1000000 !== 269696 ; // While i*i does not end with the digits 269,696 $i++ // ... go to next integer );   echo $i, ' * ', $i, ' = ', ($i * $i), PHP_EOL; // Print the result
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.
#C.2B.2B
C++
#include <iomanip> #include <iostream> #include <cmath>   bool approxEquals(double a, double b, double e) { return fabs(a - b) < e; }   void test(double a, double b) { constexpr double epsilon = 1e-18; std::cout << std::setprecision(21) << a; std::cout << ", "; std::cout << std::setprecision(21) << b; std::cout << " => "; std::cout << approxEquals(a, b, epsilon) << '\n'; }   int main() { test(100000000000000.01, 100000000000000.011); test(100.01, 100.011); test(10000000000000.001 / 10000.0, 1000000000.0000001000); test(0.001, 0.0010000001); test(0.000000000000000000000101, 0.0); test(sqrt(2.0) * sqrt(2.0), 2.0); test(-sqrt(2.0) * sqrt(2.0), -2.0); test(3.14159265358979323846, 3.14159265358979324); return 0; }
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
#C
C
#include<stdio.h> #include<stdlib.h> #include<string.h>   int isBal(const char*s,int l){ signed c=0; while(l--) if(s[l]==']') ++c; else if(s[l]=='[') if(--c<0) break; return !c; }   void shuffle(char*s,int h){ int x,t,i=h; while(i--){ t=s[x=rand()%h]; s[x]=s[i]; s[i]=t; } }   void genSeq(char*s,int n){ if(n){ memset(s,'[',n); memset(s+n,']',n); shuffle(s,n*2); } s[n*2]=0; }   void doSeq(int n){ char s[64]; const char *o="False"; genSeq(s,n); if(isBal(s,n*2)) o="True"; printf("'%s': %s\n",s,o); }   int main(){ int n=0; while(n<9) doSeq(n++); return 0; }
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#11l
11l
V dict = [‘key1’ = 1, ‘key2’ = 2] V value2 = dict[‘key2’]
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.
#Clojure
Clojure
(defn xfer [m from to amt] (let [{f-bal from t-bal to} m f-bal (- f-bal amt) t-bal (+ t-bal amt)] (if (or (neg? f-bal) (neg? t-bal)) (throw (IllegalArgumentException. "Call results in negative balance.")) (assoc m from f-bal to t-bal))))
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.
#Common_Lisp
Common Lisp
(ql:quickload '(:alexandria :stmx :bordeaux-threads))   (defpackage :atomic-updates (:use :cl))   (in-package :atomic-updates)   (defvar *buckets* nil) (defvar *running* nil)   (defun distribute (ratio a b) "Atomically redistribute the values of buckets A and B by RATIO." (stmx:atomic (let* ((sum (+ (stmx:$ a) (stmx:$ b))) (a2 (truncate (* ratio sum)))) (setf (stmx:$ a) a2) (setf (stmx:$ b) (- sum a2)))))   (defun runner (ratio-func) "Continously distribute to two different elements in *BUCKETS* with the value returned from RATIO-FUNC." (loop while *running* do (let ((a (alexandria:random-elt *buckets*)) (b (alexandria:random-elt *buckets*))) (unless (eq a b) (distribute (funcall ratio-func) a b)))))   (defun print-buckets () "Atomically get the bucket values and print out their metrics." (let ((buckets (stmx:atomic (map 'vector 'stmx:$ *buckets*)))) (format t "Buckets: ~a~%Sum: ~a~%" buckets (reduce '+ buckets))))   (defun scenario () (setf *buckets* (coerce (loop repeat 20 collect (stmx:tvar 10)) 'vector)) (setf *running* t) (bt:make-thread (lambda () (runner (constantly 0.5)))) (bt:make-thread (lambda () (runner (lambda () (random 1.0))))))
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.
#BBC_BASIC
BBC BASIC
PROCassert(a% = 42) END   DEF PROCassert(bool%) IF NOT bool% THEN ERROR 100, "Assertion failed" ENDPROC
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.
#BQN
BQN
 ! 2=3 # Failed Error: Assertion error at ! 2=3 # Failed ^ "hello" ! 2=3 # Failed Error: hello at "hello" ! 2=3 # Failed
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.
#Brat
Brat
squish import :assert :assertions   assert_equal 42 42 assert_equal 13 42 #Raises an exception
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
#JavaScript
JavaScript
function mode(ary) { var counter = {}; var mode = []; var max = 0; for (var i in ary) { if (!(ary[i] in counter)) counter[ary[i]] = 0; counter[ary[i]]++;   if (counter[ary[i]] == max) mode.push(ary[i]); else if (counter[ary[i]] > max) { max = counter[ary[i]]; mode = [ary[i]]; } } return mode; }   mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]); // [6] mode([1, 2, 4, 4, 1]); // [1,4]
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Aime
Aime
record r; text s;   r_put(r, "A", 33); # an integer value r_put(r, "C", 2.5); # a real value r_put(r, "B", "associative"); # a string value   if (r_first(r, s)) { do { o_form("key ~, value ~ (~)\n", s, r[s], r_type(r, s)); } while (rsk_greater(r, s, s)); }
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
#ALGOL_68
ALGOL 68
# associative array handling using hashing #   # the modes allowed as associative array element values - change to suit # MODE AAVALUE = STRING; # the modes allowed as associative array element keys - change to suit # MODE AAKEY = STRING; # nil element value # REF AAVALUE nil value = NIL;   # an element of an associative array # MODE AAELEMENT = STRUCT( AAKEY key, REF AAVALUE value ); # a list of associative array elements - the element values with a # # particular hash value are stored in an AAELEMENTLIST # MODE AAELEMENTLIST = STRUCT( AAELEMENT element, REF AAELEMENTLIST next ); # nil element list reference # REF AAELEMENTLIST nil element list = NIL; # nil element reference # REF AAELEMENT nil element = NIL;   # the hash modulus for the associative arrays # INT hash modulus = 256;   # generates a hash value from an AAKEY - change to suit # OP HASH = ( STRING key )INT: BEGIN INT result := ABS ( UPB key - LWB key ) MOD hash modulus; FOR char pos FROM LWB key TO UPB key DO result PLUSAB ( ABS key[ char pos ] - ABS " " ); result MODAB hash modulus OD; result END; # HASH #   # a mode representing an associative array # MODE AARRAY = STRUCT( [ 0 : hash modulus - 1 ]REF AAELEMENTLIST elements , INT curr hash , REF AAELEMENTLIST curr position );   # initialises an associative array so all the hash chains are empty # OP INIT = ( REF AARRAY array )REF AARRAY: BEGIN FOR hash value FROM 0 TO hash modulus - 1 DO ( elements OF array )[ hash value ] := nil element list OD; array END; # INIT #   # gets a reference to the value corresponding to a particular key in an # # associative array - the element is created if it doesn't exist # PRIO // = 1; OP // = ( REF AARRAY array, AAKEY key )REF AAVALUE: BEGIN REF AAVALUE result; INT hash value = HASH key; # get the hash chain for the key # REF AAELEMENTLIST element := ( elements OF array )[ hash value ]; # find the element in the list, if it is there # BOOL found element := FALSE; WHILE ( element ISNT nil element list ) AND NOT found element DO found element := ( key OF element OF element = key ); IF found element THEN result := value OF element OF element ELSE element := next OF element FI OD; IF NOT found element THEN # the element is not in the list # # - add it to the front of the hash chain # ( elements OF array )[ hash value ] := HEAP AAELEMENTLIST := ( HEAP AAELEMENT := ( key , HEAP AAVALUE := "" ) , ( elements OF array )[ hash value ] ); result := value OF element OF ( elements OF array )[ hash value ] FI; result END; # // #   # returns TRUE if array contains key, FALSE otherwise # PRIO CONTAINSKEY = 1; OP CONTAINSKEY = ( REF AARRAY array, AAKEY key )BOOL: BEGIN # get the hash chain for the key # REF AAELEMENTLIST element := ( elements OF array )[ HASH key ]; # find the element in the list, if it is there # BOOL found element := FALSE; WHILE ( element ISNT nil element list ) AND NOT found element DO found element := ( key OF element OF element = key ); IF NOT found element THEN element := next OF element FI OD; found element END; # CONTAINSKEY #   # gets the first element (key, value) from the array # OP FIRST = ( REF AARRAY array )REF AAELEMENT: BEGIN curr hash OF array := LWB ( elements OF array ) - 1; curr position OF array := nil element list; NEXT array END; # FIRST #   # gets the next element (key, value) from the array # OP NEXT = ( REF AARRAY array )REF AAELEMENT: BEGIN WHILE ( curr position OF array IS nil element list ) AND curr hash OF array < UPB ( elements OF array ) DO # reached the end of the current element list - try the next # curr hash OF array +:= 1; curr position OF array := ( elements OF array )[ curr hash OF array ] OD; IF curr hash OF array > UPB ( elements OF array ) THEN # no more elements # nil element ELIF curr position OF array IS nil element list THEN # reached the end of the table # nil element ELSE # have another element # REF AAELEMENTLIST found element = curr position OF array; curr position OF array := next OF curr position OF array; element OF found element FI END; # NEXT #   # test the associative array # BEGIN # create an array and add some values # REF AARRAY a1 := INIT LOC AARRAY; a1 // "k1" := "k1 value"; a1 // "z2" := "z2 value"; a1 // "k1" := "new k1 value"; a1 // "k2" := "k2 value"; a1 // "2j" := "2j value"; # iterate over the values # REF AAELEMENT e := FIRST a1; WHILE e ISNT nil element DO print( ( " (" + key OF e + ")[" + value OF e + "]", newline ) ); e := NEXT a1 OD 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]
#ALGOL_68
ALGOL 68
BEGIN # apply a digital filter # PROC filter = ( []REAL a, b, signal, REF[]REAL result )VOID: BEGIN FOR i FROM LWB result TO UPB result DO result[ i ] := 0 OD; FOR i FROM LWB signal TO UPB signal DO REAL tmp := 0; FOR j FROM LWB b TO UPB b DO IF i >= j THEN tmp +:= b[ j ] * signal[ LWB signal + ( i - j ) ] FI OD; FOR j FROM LWB a TO UPB a DO IF i >= j THEN tmp -:= a[ j ] * result[ LWB result + ( i - j ) ] FI OD; result[ i ] := tmp / a[ LWB a ] OD END # filter # ; [ 4 ]REAL a := []REAL( 1, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17 ); [ 4 ]REAL b := []REAL( 0.16666667, 0.5, 0.5, 0.16666667 ); [ 20 ]REAL signal := []REAL( -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 ); [ 20 ]REAL result; filter( a, b, signal, result ); FOR i FROM LWB result TO UPB result DO print( ( " ", fixed( result[ i ], -9, 6 ) ) ); IF i MOD 5 /= 0 THEN print( ( ", " ) ) ELSE print( ( newline ) ) FI OD 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
#AutoHotkey
AutoHotkey
i = 10 Loop, % i { Random, v, -3.141592, 3.141592 list .= v "`n" sum += v } MsgBox, % i ? list "`nmean: " sum/i:0
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#AWK
AWK
cat mean.awk #!/usr/local/bin/gawk -f   # User defined function function mean(v, i,n,sum) { for (i in v) { n++ sum += v[i] } if (n>0) { return(sum/n) } else { return("zero-length input !") } }   BEGIN { # fill a vector with random numbers for(i=0; i < 10; i++) { vett[i] = rand()*10 } print mean(vett) print mean(nothing) }  
http://rosettacode.org/wiki/Associative_array/Merging
Associative array/Merging
Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be: Key Value "name" "Rocket Skates" "price" 15.25 "color" "red" "year" 1974
#Elixir
Elixir
base = %{name: "Rocket Skates", price: 12.75, color: "yellow"} update = %{price: 15.25, color: "red", year: 1974} result = Map.merge(base, update) IO.inspect(result)
http://rosettacode.org/wiki/Associative_array/Merging
Associative array/Merging
Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be: Key Value "name" "Rocket Skates" "price" 15.25 "color" "red" "year" 1974
#F.23
F#
  type N = |Price of float|Name of string|Year of int|Colour of string let n=Map<string,N>[("name",Name("Rocket Skates"));("price",Price(12.75));("colour",Colour("yellow"))] let g=Map<string,N>[("price",Price(15.25));("colour",Colour("red"));("year",Year(1974))] let ng=(Map.toList n)@(Map.toList g)|>Map.ofList printfn "%A" ng  
http://rosettacode.org/wiki/Associative_array/Merging
Associative array/Merging
Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be: Key Value "name" "Rocket Skates" "price" 15.25 "color" "red" "year" 1974
#Factor
Factor
USING: assocs prettyprint ;   { { "name" "Rocket Skates" } { "price" 12.75 } { "color" "yellow" } } { { "price" 15.25 } { "color" "red" } { "year" 1974 } } assoc-union .
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%)
#FutureBasic
FutureBasic
  _nmax = 20 _times = 1000000   local fn Average( n as long, times as long ) as double long i, x double b, c = 0   for i = 0 to times x = 1 : b = 0 while ( b and x ) == 0 c++ b = b || x x = 1 << ( rnd(n) - 1 ) wend next end fn = c / times   local fn Analyltic( n as long ) as double double nn = (double)n double term = 1.0 double sum = 1.0 long i   for i = nn - 1 to i >= 1 step -1 term = term * i / nn sum = sum + term next end fn = sum   local fn DoIt long n double average, theory, difference   window 1 printf @"\nSamples tested: %ld\n", _times print " N Average Analytical (error)" print "=== ========= ============ =========" for n = 1 to _nmax average = fn Average( n, _times ) theory = fn Analyltic( n ) difference = ( average / theory - 1) * 100 printf @"%3d  %9.4f  %9.4f  %10.4f%%", n, average, theory, difference next end fn   randomize fn DoIt   HandleEvents  
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%)
#Go
Go
package main   import ( "fmt" "math" "math/rand" )   const nmax = 20   func main() { fmt.Println(" N average analytical (error)") fmt.Println("=== ========= ============ =========") for n := 1; n <= nmax; n++ { a := avg(n) b := ana(n) fmt.Printf("%3d  %9.4f  %12.4f (%6.2f%%)\n", n, a, b, math.Abs(a-b)/b*100) } }   func avg(n int) float64 { const tests = 1e4 sum := 0 for t := 0; t < tests; t++ { var v [nmax]bool for x := 0; !v[x]; x = rand.Intn(n) { v[x] = true sum++ } } return float64(sum) / tests }   func ana(n int) float64 { nn := float64(n) term := 1. sum := 1. for i := nn - 1; i >= 1; i-- { term *= i / nn sum += term } return sum }
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
#Python
Python
from collections import deque   def simplemovingaverage(period): assert period == int(period) and period > 0, "Period must be an integer >0"   summ = n = 0.0 values = deque([0.0] * period) # old value queue   def sma(x): nonlocal summ, n   values.append(x) summ += x - values.popleft() n = min(n+1, period) return summ / n   return sma
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.
#Cowgol
Cowgol
include "cowgol.coh"; const MAXIMUM := 120;   typedef N is int(0, MAXIMUM + 1); var prime: uint8[MAXIMUM + 1];   sub Sieve() is MemSet(&prime[0], 1, @bytesof prime); prime[0] := 0; prime[1] := 0;   var cand: N := 2; while cand <= MAXIMUM >> 1 loop if prime[cand] != 0 then var comp := cand + cand; while comp <= MAXIMUM loop prime[comp] := 0; comp := comp + cand; end loop; end if; cand := cand + 1; end loop; end sub;   sub Factors(n: N): (count: N) is count := 0; var p: N := 2; while p <= MAXIMUM loop if prime[p] != 0 then while n % p == 0 loop count := count + 1; n := n / p; end loop; end if; p := p + 1; end loop; end sub;   sub Padding(n: N) is if n < 10 then print(" "); elseif n < 100 then print(" "); else print(" "); end if; end sub;   var cand: N := 2; var col: uint8 := 0; Sieve(); while cand <= MAXIMUM loop if prime[Factors(cand)] != 0 then Padding(cand); print_i32(cand as uint32); col := col + 1; if col % 18 == 0 then print_nl(); end if; end if; cand := cand + 1; end loop; print_nl();
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.
#D
D
import std.stdio;   enum MAX = 120;   bool isPrime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; int d = 5; while (d * d <= n) { if (n % d == 0) return false; d += 2; if (n % d == 0) return false; d += 4; } return true; }   int primeFactorCount(int n) { if (n == 1) return 0; if (isPrime(n)) return 1; int count; int 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; } } }   void main() { writeln("The attractive numbers up to and including ", MAX, " are:"); int i = 1; int count; while (i <= MAX) { int n = primeFactorCount(i); if (isPrime(n)) { writef("%4d", i); if (++count % 20 == 0) writeln; } ++i; } writeln; }
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
#Java
Java
public class MeanTimeOfDay {   static double meanAngle(double[] angles) { int len = angles.length; double sinSum = 0.0; for (int i = 0; i < len; i++) { sinSum += Math.sin(angles[i] * Math.PI / 180.0); }   double cosSum = 0.0; for (int i = 0; i < len; i++) { cosSum += Math.cos(angles[i] * Math.PI / 180.0); }   return Math.atan2(sinSum / len, cosSum / len) * 180.0 / Math.PI; }   /* time string assumed to be in format "hh:mm:ss" */ static int timeToSecs(String t) { int hours = Integer.parseInt(t.substring(0, 2)); int mins = Integer.parseInt(t.substring(3, 5)); int secs = Integer.parseInt(t.substring(6, 8)); return 3600 * hours + 60 * mins + secs; }   /* 1 second of time = 360/(24 * 3600) = 1/240th degree */ static double timeToDegrees(String t) { return timeToSecs(t) / 240.0; }   static String degreesToTime(double d) { if (d < 0.0) d += 360.0; int secs = (int)(d * 240.0); int hours = secs / 3600; int mins = secs % 3600; secs = mins % 60; mins /= 60; return String.format("%2d:%2d:%2d", hours, mins, secs); }   public static void main(String[] args) { String[] tm = {"23:00:17", "23:40:20", "00:12:45", "00:17:19"}; double[] angles = new double[4]; for (int i = 0; i < 4; i++) angles[i] = timeToDegrees(tm[i]); double mean = meanAngle(angles); System.out.println("Average time is : " + degreesToTime(mean)); } }
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.
#JavaScript
JavaScript
function tree(less, val, more) { return { depth: 1+Math.max(less.depth, more.depth), less: less, val: val, more: more, }; }   function node(val) { return tree({depth: 0}, val, {depth: 0}); }   function insert(x,y) { if (0 == y.depth) return x; if (0 == x.depth) return y; if (1 == x.depth && 1 == y.depth) { switch (Math.sign(y.val)-x.val) { case -1: return tree(y, x.val, {depth: 0}); case 0: return y; case 1: return tree(x, y.val, {depth: 0}); } } switch (Math.sign(y.val-x.val)) { case -1: return balance(insert(x.less, y), x.val, x.more); case 0: return balance(insert(x.less, y.less), x.val, insert(x.more, y.more)); case 1: return balance(x.less. x.val, insert(x.more, y)); } }   function balance(less,val,more) { if (2 > Math.abs(less.depth-more.depth)) return tree(less,val,more); if (more.depth > less.depth) { if (more.more.depth >= more.less.depth) { // 'more' was heavy return moreHeavy(less, val, more); } else { return moreHeavy(less,val,lessHeavy(more.less, more.val, more.more)); } } else { if(less.less.depth >= less.more.depth) { return lessHeavy(less, val, more); } else { return lessHeavy(moreHeavy(less.less, less.val, less.more), val, more); } } }   function moreHeavy(less,val,more) { return tree(tree(less,val,more.less), more.val, more.more) }   function lessHeavy(less,val,more) { return tree(less.less, less.val, tree(less.more, val, more)); }   function remove(val, y) { switch (y.depth) { case 0: return y; case 1: if (val == y.val) { return y.less; } else { return y; } default: switch (Math.sign(y.val - val)) { case -1: return balance(y.less, y.val, remove(val, y.more)); case 0: return insert(y.less, y.more); case 1: return balance(remove(val, y.less), y.val, y.more) } } }   function lookup(val, y) { switch (y.depth) { case 0: return y; case 1: if (val == y.val) { return y; } else { return {depth: 0}; } default: switch (Math.sign(y.val-val)) { case -1: return lookup(val, y.more); case 0: return y; case 1: return lookup(val, y.less); } } }
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
#Groovy
Groovy
import static java.lang.Math.* def meanAngle = { atan2( it.sum { sin(it * PI / 180) } / it.size(), it.sum { cos(it * PI / 180) } / it.size()) * 180 / PI }
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
#Haskell
Haskell
import Data.Complex (cis, phase)   meanAngle :: RealFloat c => [c] -> c meanAngle = (/ pi) . (* 180) . phase . sum . map (cis . (/ 180) . (* pi))   main :: IO () main = mapM_ (\angles -> putStrLn $ "The mean angle of " ++ show angles ++ " is: " ++ show (meanAngle angles) ++ " degrees") [[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
#Common_Lisp
Common Lisp
((defun select-nth (n list predicate) "Select nth element in list, ordered by predicate, modifying list." (do ((pivot (pop list)) (ln 0) (left '()) (rn 0) (right '())) ((endp list) (cond ((< n ln) (select-nth n left predicate)) ((eql n ln) pivot) ((< n (+ ln rn 1)) (select-nth (- n ln 1) right predicate)) (t (error "n out of range.")))) (if (funcall predicate (first list) pivot) (psetf list (cdr list) (cdr list) left left list ln (1+ ln)) (psetf list (cdr list) (cdr list) right right list rn (1+ rn)))))   (defun median (list predicate) (select-nth (floor (length list) 2) list predicate))
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
#GAP
GAP
# The first two work with rationals or with floats # (but bear in mind that support of floating point is very poor in GAP) mean := v -> Sum(v) / Length(v); harmean := v -> Length(v) / Sum(v, Inverse); geomean := v -> EXP_FLOAT(Sum(v, LOG_FLOAT) / Length(v));   mean([1 .. 10]); # 11/2 harmean([1 .. 10]); # 25200/7381   v := List([1..10], FLOAT_INT);; mean(v); # 5.5 harmean(v); # 3.41417 geomean(v); # 4.52873
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.
#Liberty_BASIC
Liberty BASIC
  global tt$ tt$="-0+" '-1 0 1; +2 -> 1 2 3, instr   '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.   a$="+-0++0+" a=deci(a$) print "a",a, a$   b=-436 b$=ternary$(b) print "b",b, b$   c$="+-++-" c=deci(c$) print "c",c, c$   'calculate in ternary   res$=multTernary$(a$, subTernary$(b$, c$)) print "a * (b - c)", res$ print "In decimal:",deci(res$)   print "Check:" print "a * (b - c)", a * (b - c) end   function deci(s$) pow = 1 for i = len(s$) to 1 step -1 c$ = mid$(s$,i,1) 'select case c$ ' case "+":sign= 1 ' case "-":sign=-1 ' case "0":sign= 0 'end select sign = instr(tt$,c$)-2 deci = deci+pow*sign pow = pow*3 next end function   function ternary$(n) while abs(n)>3^k/2 k=k+1 wend k=k-1   pow = 3^k for i = k to 0 step -1 sign = (n>0) - (n<0) sign = sign * (abs(n)>pow/2) ternary$ = ternary$+mid$(tt$,sign+2,1) n = n - sign*pow pow = pow/3 next if ternary$ = "" then ternary$ ="0" end function   function multTernary$(a$, b$)   c$ = "" t$ = "" shift$ = "" for i = len(a$) to 1 step -1   select case mid$(a$,i,1) case "+": t$ = b$ case "0": t$ = "0" case "-": t$ = negate$(b$) end select   c$ = addTernary$(c$, t$+shift$)   shift$ = shift$ +"0" 'print d, t$, c$ next multTernary$ = c$ end function   function subTernary$(a$, b$) subTernary$ = addTernary$(a$, negate$(b$)) end function   function negate$(s$) negate$="" for i = 1 to len(s$) 'print mid$(s$,i,1), instr(tt$, mid$(s$,i,1)), 4-instr(tt$, mid$(s$,i,1)) negate$=negate$+mid$(tt$, 4-instr(tt$, mid$(s$,i,1)), 1) next end function   function addTernary$(a$, b$) 'add a$ + b$, for now only positive l = max(len(a$), len(b$)) a$=pad$(a$,l) b$=pad$(b$,l) c$ = "" 'result carry = 0 for i = l to 1 step -1 a = instr(tt$,mid$(a$,i,1))-2 b = instr(tt$,mid$(b$,i,1))-2 '-1 0 1 c = a+b+carry   select case case abs(c)<2 carry = 0 case c>0 carry =1: c=c-3 case c<0 carry =-1: c=c+3 end select   'print a, b, c c$ = mid$(tt$,c+2,1)+c$ next if carry<>0 then c$ = mid$(tt$,carry+2,1) +c$ 'print c$ 'have to trim leading 0's i=0 while mid$(c$,i+1,1)="0" i=i+1 wend c$=mid$(c$,i+1) if c$="" then c$="0" addTernary$ = c$ end function   function pad$(a$,n) 'pad from right with 0 to length n pad$ = a$ while len(pad$)<n pad$ = "0"+pad$ wend end function  
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.
#Picat
Picat
main => N = 1, while (N**2 mod 1000000 != 269696) N := N + 1 end, println(N).
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.
#PicoLisp
PicoLisp
: (for N 99736 # Iterate N from 1 to 99736 (T (= 269696 (% (* N N) 1000000)) N) ) # Stop if remainder is 269696 -> 25264
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.
#Common_Lisp
Common Lisp
  (defun approx-equal (float1 float2 &optional (threshold 0.000001)) "Determine whether float1 and float2 are equal; THRESHOLD is the maximum allowable difference between normalized significands of floats with the same exponent. The significands are scaled appropriately before comparison for floats with different exponents." (multiple-value-bind (sig1 exp1 sign1) (decode-float float1) (multiple-value-bind (sig2 exp2 sign2) (decode-float float2) (let ((cmp1 (float-sign sign1 (scale-float sig1 (floor (- exp1 exp2) 2)))) (cmp2 (float-sign sign2 (scale-float sig2 (floor (- exp2 exp1) 2))))) (< (abs (- cmp1 cmp2)) threshold)))))  
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.
#D
D
import std.math; import std.stdio;   auto approxEquals = (double a, double b, double epsilon) => abs(a - b) < epsilon;   void main() { void test(double a, double b) { double epsilon = 1e-18; writefln("%.18f, %.18f => %s", a, b, a.approxEquals(b, epsilon)); }   test(100000000000000.01, 100000000000000.011); test(100.01, 100.011); test(10000000000000.001 / 10000.0, 1000000000.0000001000); test(0.001, 0.0010000001); test(0.000000000000000000000101, 0.0); test(sqrt(2.0) * sqrt(2.0), 2.0); test(-sqrt(2.0) * sqrt(2.0), -2.0); test(3.14159265358979323846, 3.14159265358979324); }
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
#C.23
C#
using System; using System.Linq;   class Program { static bool IsBalanced(string text, char open = '[', char close = ']') { var level = 0; foreach (var character in text) { if (character == close) { if (level == 0) { return false; } level--; } if (character == open) { level++; } } return level == 0; }   static string RandomBrackets(int count, char open = '[', char close = ']') { var random = new Random(); return string.Join(string.Empty, (new string(open, count) + new string(close, count)).OrderBy(c => random.Next())); }   static void Main() { for (var count = 0; count < 9; count++) { var text = RandomBrackets(count); Console.WriteLine("\"{0}\" is {1}balanced.", text, IsBalanced(text) ? string.Empty : "not "); } } }
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
#8th
8th
  { "one" : 1, "two" : "bad" }  
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.
#D
D
import std.stdio: writeln; import std.conv: text; import std.random: uniform, Xorshift; import std.algorithm: min, max; import std.parallelism: task; import core.thread: Thread; import core.sync.mutex: Mutex; import core.time: seconds;   __gshared uint transfersCount;   final class Buckets(size_t nBuckets) if (nBuckets > 0) { alias TBucketValue = uint;   // The trailing padding avoids cache line contention // when run with two or more cores. align(128) private static struct Bucket { TBucketValue value; Mutex mtx; alias value this; }   private Bucket[nBuckets] buckets; private bool running;   public this() { this.running = true; foreach (ref b; buckets) b = Bucket(uniform(0, 100), new Mutex); }   public TBucketValue opIndex(in size_t index) const pure nothrow { return buckets[index]; }   public void transfer(in size_t from, in size_t to, in TBucketValue amount) { immutable low = min(from, to); immutable high = max(from, to); buckets[low].mtx.lock(); buckets[high].mtx.lock();   scope(exit) { buckets[low].mtx.unlock(); buckets[high].mtx.unlock(); }   immutable realAmount = min(buckets[from].value, amount); buckets[from] -= realAmount; buckets[to ] += realAmount; transfersCount++; }   @property size_t length() const pure nothrow { return this.buckets.length; }   void toString(in void delegate(const(char)[]) sink) { TBucketValue total = 0; foreach (ref b; buckets) { b.mtx.lock(); total += b; }   scope(exit) foreach (ref b; buckets) b.mtx.unlock();   sink(text(buckets)); sink(" "); sink(text(total)); } }   void randomize(size_t N)(Buckets!N data) { auto rng = Xorshift(1);   while (data.running) { immutable i = uniform(0, data.length, rng); immutable j = uniform(0, data.length, rng); immutable amount = uniform!"[]"(0, 20, rng); data.transfer(i, j, amount); } }   void equalize(size_t N)(Buckets!N data) { auto rng = Xorshift(1);   while (data.running) { immutable i = uniform(0, data.length, rng); immutable j = uniform(0, data.length, rng); immutable a = data[i]; immutable b = data[j]; if (a > b) data.transfer(i, j, (a - b) / 2); else data.transfer(j, i, (b - a) / 2); } }   void display(size_t N)(Buckets!N data) { foreach (immutable _; 0 .. 10) { writeln(transfersCount, " ", data); transfersCount = 0; Thread.sleep(1.seconds); } data.running = false; }   void main() { writeln("N. transfers, buckets, buckets sum:"); auto data = new Buckets!20(); task!randomize(data).executeInNewThread(); task!equalize(data).executeInNewThread(); task!display(data).executeInNewThread(); }
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.
#C
C
#include <assert.h>   int main(){ int a; /* ...input or change a here */ assert(a == 42); /* aborts program when a is not 42, unless the NDEBUG macro was defined */   return 0; }
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.
#C.23_and_Visual_Basic_.NET
C# and Visual Basic .NET
using System.Diagnostics; // Debug and Trace are in this namespace.   static class Program { static void Main() { int a = 0;   Console.WriteLine("Before");   // Always hit. Trace.Assert(a == 42, "Trace assertion failed");   Console.WriteLine("After Trace.Assert");   // Only hit in debug builds. Debug.Assert(a == 42, "Debug assertion failed");   Console.WriteLine("After Debug.Assert"); } }
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.
#11l
11l
V array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] V arrsq = array.map(i -> i * i) print(arrsq)
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
#jq
jq
# modes/0 produces an array of [value, count] # in increasing order of count: def modes: sort | reduce .[] as $i ([]; # state variable is an array of [value, count] if length == 0 then [ [$i, 1] ] elif .[-1][0] == $i then setpath([-1,1]; .[-1][1] + 1) else . + [[$i,1]] end ) | sort_by( .[1] );   # mode/0 outputs a stream of the modal values; # if the input array is empty, the output stream is also empty. def mode: if length == 0 then empty else modes as $modes | $modes[-1][1] as $count | $modes[] | select( .[1] == $count) | .[0] end;
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
#Julia
Julia
function modes(values) dict = Dict() # Values => Number of repetitions modesArray = typeof(values[1])[] # Array of the modes so far max = 0 # Max of repetitions so far   for v in values # Add one to the dict[v] entry (create one if none) if v in keys(dict) dict[v] += 1 else dict[v] = 1 end   # Update modesArray if the number of repetitions # of v reaches or surpasses the max value if dict[v] >= max if dict[v] > max empty!(modesArray) max += 1 end append!(modesArray, [v]) end end   return modesArray end   println(modes([1,3,6,6,6,6,7,7,12,12,17])) println(modes((1,1,2,4,4)))
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#App_Inventor
App Inventor
; create a dictionary d: #[ name: "john" surname: "doe" age: 34 ]   ; Iterate over key/value pairs loop d [key,value][ print ["key =" key ", value =" value] ]   print "----"   ; Iterate over keys loop keys d [k][ print ["key =" k] ]   print "----"   ; Iterate over values loop values d [v][ print ["value =" v] ]
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Arturo
Arturo
; create a dictionary d: #[ name: "john" surname: "doe" age: 34 ]   ; Iterate over key/value pairs loop d [key,value][ print ["key =" key ", value =" value] ]   print "----"   ; Iterate over keys loop keys d [k][ print ["key =" k] ]   print "----"   ; Iterate over values loop values d [v][ print ["value =" v] ]
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]
#AppleScript
AppleScript
on min(a, b) if (b < a) then return b return a end min   on DF2TFilter(a, b, sig) set aCount to (count a) set bCount to (count b) set sigCount to (count sig) set rst to {}   repeat with i from 1 to sigCount set tmp to 0 set iPlus1 to i + 1 repeat with j from 1 to min(i, bCount) set tmp to tmp + (item j of b) * (item (iPlus1 - j) of sig) end repeat repeat with j from 2 to min(i, aCount) set tmp to tmp - (item j of a) * (item (iPlus1 - j) of rst) end repeat set end of rst to tmp / (beginning of a) end repeat   return rst end DF2TFilter   local acoef, bcoef, signal set acoef to {1.0, -2.77555756E-16, 0.333333333, -1.85037171E-17} set bcoef to {0.16666667, 0.5, 0.5, 0.16666667} set signal to {-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.025930339848, 0.490105989562, 0.549391221511, 0.9047198589} DF2TFilter(acoef, bcoef, signal)
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
#Babel
Babel
(3 24 18 427 483 49 14 4294 2 41) dup len <- sum ! -> / itod <<
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
#BASIC
BASIC
mean = 0 sum = 0; FOR i = LBOUND(nums) TO UBOUND(nums) sum = sum + nums(i); NEXT i size = UBOUND(nums) - LBOUND(nums) + 1 PRINT "The mean is: "; IF size <> 0 THEN PRINT (sum / size) ELSE PRINT 0 END IF
http://rosettacode.org/wiki/Associative_array/Merging
Associative array/Merging
Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be: Key Value "name" "Rocket Skates" "price" 15.25 "color" "red" "year" 1974
#Go
Go
package main   import "fmt"   type assoc map[string]interface{}   func merge(base, update assoc) assoc { result := make(assoc) for k, v := range base { result[k] = v } for k, v := range update { result[k] = v } return result }   func main() { base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"} update := assoc{"price": 15.25, "color": "red", "year": 1974} result := merge(base, update) fmt.Println(result) }
http://rosettacode.org/wiki/Associative_array/Merging
Associative array/Merging
Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be: Key Value "name" "Rocket Skates" "price" 15.25 "color" "red" "year" 1974
#Haskell
Haskell
data Item = Item { name :: Maybe String , price :: Maybe Float , color :: Maybe String , year :: Maybe Int } deriving (Show)   itemFromMerge :: Item -> Item -> Item itemFromMerge (Item n p c y) (Item n1 p1 c1 y1) = Item (maybe n pure n1) (maybe p pure p1) (maybe c pure c1) (maybe y pure y1)   main :: IO () main = print $ itemFromMerge (Item (Just "Rocket Skates") (Just 12.75) (Just "yellow") Nothing) (Item Nothing (Just 15.25) (Just "red") (Just 1974))
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%)
#Haskell
Haskell
import System.Random import qualified Data.Set as S import Text.Printf   findRep :: (Random a, Integral a, RandomGen b) => a -> b -> (a, b) findRep n gen = findRep' (S.singleton 1) 1 gen where findRep' seen len gen' | S.member fx seen = (len, gen'') | otherwise = findRep' (S.insert fx seen) (len + 1) gen'' where (fx, gen'') = randomR (1, n) gen'   statistical :: (Integral a, Random b, Integral b, RandomGen c, Fractional d) => a -> b -> c -> (d, c) statistical samples size gen = let (total, gen') = sar samples gen 0 in ((fromIntegral total) / (fromIntegral samples), gen') where sar 0 gen' acc = (acc, gen') sar samples' gen' acc = let (len, gen'') = findRep size gen' in sar (samples' - 1) gen'' (acc + len)   factorial :: (Integral a) => a -> a factorial n = foldl (*) 1 [1..n]   analytical :: (Integral a, Fractional b) => a -> b analytical n = sum [fromIntegral num / fromIntegral (factorial (n - i)) / fromIntegral (n ^ i) | i <- [1..n]] where num = factorial n   test :: (Integral a, Random b, Integral b, PrintfArg b, RandomGen c) => a -> [b] -> c -> IO c test _ [] gen = return gen test samples (x:xs) gen = do let (st, gen') = statistical samples x gen an = analytical x err = abs (st - an) / st * 100.0 str = printf "%3d  %9.4f  %12.4f (%6.2f%%)\n" x (st :: Float) (an :: Float) (err :: Float) putStr str test samples xs gen'   main :: IO () main = do putStrLn " N average analytical (error)" putStrLn "=== ========= ============ =========" let samples = 10000 :: Integer range = [1..20] :: [Integer] _ <- test samples range $ mkStdGen 0 return ()
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%)
#J
J
(~.@, {&0 0@{:)^:_] 0 0 (~.@, {&0 0@{:)^:_] 1 1 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
#Quackery
Quackery
[ $ "bigrat.qky" loadfile ] now!   [ over size - space swap of join ] is pad ( $ n --> $ )   [ ' [ stack [ ] ] copy nested ' [ tuck take swap join dup size ] join swap join ' [ > if [ 1 split nip ] tuck swap put 0 over witheach + swap size dip n->v n->v v/ ] join copy ] is make-sma ( n --> [ ) ( behaviour of [ is: n --> n/d )   [ stack ] is sma-3 ( --> s ) 3 make-sma sma-3 put   [ stack ] is sma-5 ( --> s ) 5 make-sma sma-5 put   say "n sma-3 sma-5" cr cr ' [ 1 2 3 4 5 5 4 3 2 1 ] witheach [ dup echo sp dup sma-3 share do 7 point$ 10 pad echo$ sp sma-5 share do 7 point$ 10 pad echo$ cr ]  
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.
#Delphi
Delphi
/* Sieve of Eratosthenes */ proc nonrec sieve([*] bool prime) void: word p, c, max; max := (dim(prime,1)-1)>>1; prime[0] := false; prime[1] := false; for p from 2 upto max do prime[p] := true od; for p from 2 upto max>>1 do if prime[p] then for c from p*2 by p upto max do prime[c] := false od fi od corp   /* Count the prime factors of a number */ proc nonrec n_factors(word n; [*] bool prime) word: word count, fac; fac := 2; count := 0; while fac <= n do if prime[fac] then while n % fac = 0 do count := count + 1; n := n / fac od fi; fac := fac + 1 od; count corp   /* Find attractive numbers <= 120 */ proc nonrec main() void: word MAX = 120; [MAX+1] bool prime; unsigned MAX i; byte col; sieve(prime); col := 0; for i from 2 upto MAX do if prime[n_factors(i, prime)] then write(i:4); col := col + 1; if col % 18 = 0 then writeln() fi fi od corp
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.
#Draco
Draco
/* Sieve of Eratosthenes */ proc nonrec sieve([*] bool prime) void: word p, c, max; max := (dim(prime,1)-1)>>1; prime[0] := false; prime[1] := false; for p from 2 upto max do prime[p] := true od; for p from 2 upto max>>1 do if prime[p] then for c from p*2 by p upto max do prime[c] := false od fi od corp   /* Count the prime factors of a number */ proc nonrec n_factors(word n; [*] bool prime) word: word count, fac; fac := 2; count := 0; while fac <= n do if prime[fac] then while n % fac = 0 do count := count + 1; n := n / fac od fi; fac := fac + 1 od; count corp   /* Find attractive numbers <= 120 */ proc nonrec main() void: word MAX = 120; [MAX+1] bool prime; unsigned MAX i; byte col; sieve(prime); col := 0; for i from 2 upto MAX do if prime[n_factors(i, prime)] then write(i:4); col := col + 1; if col % 18 = 0 then writeln() fi fi od corp
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
#JavaScript
JavaScript
var args = process.argv.slice(2);   function time_to_seconds( hms ) { var parts = hms.split(':'); var h = parseInt(parts[0]); var m = parseInt(parts[1]); var s = parseInt(parts[2]); if ( h < 12 ) { h += 24; } var seconds = parseInt(parts[0]) * 60 * 60 + parseInt(parts[1]) * 60 + parseInt(parts[2]); return seconds; } function seconds_to_time( s ) { var h = Math.floor( s/(60 * 60) ); if ( h < 10 ) { h = '0' + h; } s = s % (60 * 60);   var m = Math.floor( s/60 ); if ( m < 10 ) { m = '0' + m; } s = s % 60 if ( s < 10 ) { s = '0' + s; } return h + ':' + m + ':' + s; }   var sum = 0, count = 0, idx; for (idx in args) { var seconds = time_to_seconds( args[idx] ); sum += seconds; count++; }   var seconds = Math.floor( sum / count ) console.log( 'Mean time is ', seconds_to_time(seconds));  
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.
#Julia
Julia
module AVLTrees   import Base.print export AVLNode, AVLTree, insert, deletekey, deletevalue, findnodebykey, findnodebyvalue, allnodes   @enum Direction LEFT RIGHT avlhash(x) = Int32(hash(x) & 0xfffffff) const MIDHASH = Int32(div(0xfffffff, 2))   mutable struct AVLNode{T} value::T key::Int32 balance::Int32 left::Union{AVLNode, Nothing} right::Union{AVLNode, Nothing} parent::Union{AVLNode, Nothing} end AVLNode(v::T, b, l, r, p) where T <: Real = AVLNode(v, avlhash(v), Int32(b), l, r, p) AVLNode(v::T, h, b::Int64, l, r, p) where T <: Real = AVLNode(v, h, Int32(b), l, r, p) AVLNode(v::T) where T <: Real = AVLNode(v, avlhash(v), Int32(0), nothing, nothing, nothing)   AVLTree(typ::Type) = AVLNode(typ(0), MIDHASH, Int32(0), nothing, nothing, nothing) const MaybeAVL = Union{AVLNode, Nothing}   height(node::MaybeAVL) = (node == nothing) ? 0 : 1 + max(height(node.right), height(node.left))   function insert(node, value) if node == nothing node = AVLNode(value) return true end key, n, parent::MaybeAVL = avlhash(value), node, nothing while true if n.key == key return false end parent = n ngreater = n.key > key n = ngreater ? n.left : n.right if n == nothing if ngreater parent.left = AVLNode(value, key, 0, nothing, nothing, parent) else parent.right = AVLNode(value, key, 0, nothing, nothing, parent) end rebalance(parent) break end end return true end   function deletekey(node, delkey) node == nothing && return nothing n, parent = MaybeAVL(node), MaybeAVL(node) delnode, child = MaybeAVL(nothing), MaybeAVL(node) while child != nothing parent, n = n, child child = delkey >= n.key ? n.right : n.left if delkey == n.key delnode = n end end if delnode != nothing delnode.key = n.key delnode.value = n.value child = (n.left != nothing) ? n.left : n.right if node.key == delkey root = child else if parent.left == n parent.left = child else parent.right = child end rebalance(parent) end end end   deletevalue(node, val) = deletekey(node, avlhash(val))   function rebalance(node::MaybeAVL) node == nothing && return nothing setbalance(node) if node.balance < -1 if height(node.left.left) >= height(node.left.right) node = rotate(node, RIGHT) else node = rotatetwice(node, LEFT, RIGHT) end elseif node.balance > 1 if node.right != nothing && height(node.right.right) >= height(node.right.left) node = rotate(node, LEFT) else node = rotatetwice(node, RIGHT, LEFT) end end if node != nothing && node.parent != nothing rebalance(node.parent) end end   function rotate(a, direction) (a == nothing || a.parent == nothing) && return nothing b = direction == LEFT ? a.right : a.left b == nothing && return b.parent = a.parent if direction == LEFT a.right = b.left else a.left = b.right end if a.right != nothing a.right.parent = a end if direction == LEFT b.left = a else b.right = a end a.parent = b if b.parent != nothing if b.parent.right == a b.parent.right = b else b.parent.left = b end end setbalance([a, b]) return b end   function rotatetwice(n, dir1, dir2) n.left = rotate(n.left, dir1) rotate(n, dir2) end   setbalance(n::AVLNode) = begin n.balance = height(n.right) - height(n.left) end setbalance(n::Nothing) = 0 setbalance(nodes::Vector) = for n in nodes setbalance(n) end   function findnodebykey(node, key) result::MaybeAVL = node == nothing ? nothing : node.key == key ? node : node.left != nothing && (n = findbykey(n, key) != nothing) ? n : node.right != nothing ? findbykey(node.right, key) : nothing return result end findnodebyvalue(node, val) = findnodebykey(node, avlhash(v))   function allnodes(node) result = AVLNode[] if node != nothing append!(result, allnodes(node.left)) if node.key != MIDHASH push!(result, node) end append!(result, node.right) end return result end   function Base.print(io::IO, n::MaybeAVL) if n != nothing n.left != nothing && print(io, n.left) print(io, n.key == MIDHASH ? "<ROOT> " : "<$(n.key):$(n.value):$(n.balance)> ") n.right != nothing && print(io, n.right) end end   end # module   using .AVLTrees   const tree = AVLTree(Int)   println("Inserting 10 values.") foreach(x -> insert(tree, x), rand(collect(1:80), 10)) println("Printing tree after insertion: ") println(tree)  
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
#Icon_and_Unicon
Icon and Unicon
procedure main(A) write("Mean angle is ",meanAngle(A)) end   procedure meanAngle(A) every (sumSines := 0.0) +:= sin(dtor(!A)) every (sumCosines := 0.0) +:= cos(dtor(!A)) return rtod(atan(sumSines/*A,sumCosines/*A)) end
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
#IDL
IDL
function mean_angle, phi z = total(exp(complex(0,phi*!dtor))) return, atan(imaginary(z),real_part(z))*!radeg 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
#Crystal
Crystal
def median(ary) srtd = ary.sort alen = srtd.size 0.5*(srtd[(alen-1)//2] + srtd[alen//2]) end   a = [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2] puts median a   a = [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2, 5.0] puts median a   a = [5.0] puts median a