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/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.
#Oforth
Oforth
: testInteger(n, m) assert: [ n isInteger ] assert: [ n 42 == ]   System.Out "Assertions are ok, parameters are : " << n << ", " << m << cr ;
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.
#Delphi
Delphi
  // Declare the callback function procedure callback(const AInt:Integer); begin WriteLn(AInt); end;   const // Declare a static array myArray:Array[0..4] of Integer=(1,4,6,8,7); var // Declare interator variable i:Integer; begin // Iterate the array and apply callback for i:=0 to length(myArray)-1 do callback(myArray[i]); 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
#PHP
PHP
<?php function mode($arr) { $count = array_count_values($arr); $best = max($count); return array_keys($count, $best); }   print_r(mode(array(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17))); print_r(mode(array(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
#Erlang
Erlang
  -module(assoc). -compile([export_all]).   test_create() -> D = dict:new(), D1 = dict:store(foo,1,D), D2 = dict:store(bar,2,D1), print_vals(D2).   print_vals(D) -> lists:foreach(fun (K) -> io:format("~p: ~b~n",[K,dict:fetch(K,D)]) end, dict:fetch_keys(D)).  
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]
#REXX
REXX
/*REXX pgm filters a signal with a order3 lowpass Butterworth, direct form II transposed*/ @a= '1 -2.77555756e-16 3.33333333e-1 -1.85037171e-17' /*filter coefficients*/ @b= 0.16666667 0.5 0.5 0.16666667 /* " " */ @s= '-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 ' $.=0; N=words(@s); w=length(n); numeric digits 24 /* [↑] signal vector*/ do i=1 for N; #=0 /*process each of the vector elements. */ do j=1 for words(@b); if i-j >= 0 then #= # + word(@b, j) * word(@s, i-j+1); end do k=1 for words(@a); _= i -k +1; if i-k >= 0 then #= # - word(@a, k) * $._; end $.i= # / word(@a ,1); call tell end /*i*/ /* [↑] only show using ½ the dec. digs*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ tell: numeric digits digits()%2; say right(i, w) " " left('', $.i>=0)$.i /1; return
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]
#Ruby
Ruby
def filter(a,b,signal) result = Array.new(signal.length(), 0.0) for i in 0..signal.length()-1 do tmp = 0.0 for j in 0 .. b.length()-1 do if i - j < 0 then next end tmp += b[j] * signal[i - j] end for j in 1 .. a.length()-1 do if i - j < 0 then next end tmp -= a[j] * result[i - j] end tmp /= a[0] result[i] = tmp end return result end   def main a = [1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] b = [0.16666667, 0.5, 0.5, 0.16666667] signal = [ -0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589 ]   result = filter(a,b,signal) for i in 0 .. result.length() - 1 do print "%11.8f" % [result[i]] if (i + 1) % 5 == 0 then print "\n" else print ", " end end end   main()
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#F.23
F#
let avg (a:float) (v:float) n = a + (1. / ((float n) + 1.)) * (v - a)   let mean_series list = let a, _ = List.fold_left (fun (a, n) h -> avg a (float h) n, n + 1) (0., 0) list in a
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
#Factor
Factor
USING: math math.statistics ;   : arithmetic-mean ( seq -- n ) [ 0 ] [ mean ] if-empty ;
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%)
#VBScript
VBScript
  Const MAX = 20 Const ITER = 100000   Function expected(n) Dim sum ni=n For i = 1 To n sum = sum + fact(n) / ni / fact(n-i) ni=ni*n Next expected = sum End Function   Function test(n ) Dim coun,x,bits For i = 1 To ITER x = 1 bits = 0 Do While Not bits And x count = count + 1 bits = bits Or x x =shift(Int(n * Rnd())) Loop Next test = count / ITER End Function   'VBScript formats numbers but does'nt align them! function rf(v,n,s) rf=right(string(n,s)& v,n):end function   'some precalculations to speed things up... dim fact(20),shift(20) fact(0)=1:shift(0)=1 for i=1 to 20 fact(i)=i*fact(i-1) shift(i)=2*shift(i-1) next   Dim n Wscript.echo "For " & ITER &" iterations" Wscript.Echo " n avg. exp. (error%)" Wscript.Echo "== ====== ====== ==========" For n = 1 To MAX av = test(n) ex = expected(n) Wscript.Echo rf(n,2," ")& " "& rf(formatnumber(av, 4),7," ") & " "& _ rf(formatnumber(ex,4),6," ")& " ("& rf(Formatpercent(1 - av / ex,4),8," ") & ")" Next  
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%)
#Vlang
Vlang
import rand import math   const nmax = 20   fn main() { println(" N average analytical (error)") println("=== ========= ============ =========") for n := 1; n <= nmax; n++ { a := avg(n) b := ana(n) println("${n:3} ${a:9.4f} ${b:12.4f} (${math.abs(a-b)/b*100:6.2f}%)" ) } }   fn avg(n int) f64 { tests := int(1e4) mut sum := 0 for _ in 0..tests { mut v := [nmax]bool{} for x := 0; !v[x]; { v[x] = true sum++ x = rand.intn(n) or {0} } } return f64(sum) / tests }   fn ana(n int) f64 { nn := f64(n) mut term := 1.0 mut sum := 1.0 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
#VBScript
VBScript
data = "1,2,3,4,5,5,4,3,2,1" token = Split(data,",") stream = "" WScript.StdOut.WriteLine "Number" & vbTab & "SMA3" & vbTab & "SMA5" For j = LBound(token) To UBound(token) If Len(stream) = 0 Then stream = token(j) Else stream = stream & "," & token(j) End If WScript.StdOut.WriteLine token(j) & vbTab & Round(SMA(stream,3),2) & vbTab & Round(SMA(stream,5),2) Next   Function SMA(s,p) If Len(s) = 0 Then SMA = 0 Exit Function End If d = Split(s,",") sum = 0 If UBound(d) + 1 >= p Then c = 0 For i = UBound(d) To LBound(d) Step -1 sum = sum + Int(d(i)) c = c + 1 If c = p Then Exit For End If Next SMA = sum / p Else For i = UBound(d) To LBound(d) Step -1 sum = sum + Int(d(i)) Next SMA = sum / (UBound(d) + 1) End If End Function
http://rosettacode.org/wiki/Attractive_numbers
Attractive numbers
A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show sequence items up to   120. Reference   The OEIS entry:   A063989: Numbers with a prime number of prime divisors.
#Perl
Perl
use ntheory <is_prime factor>;   is_prime +factor $_ and print "$_ " for 1..120;
http://rosettacode.org/wiki/Attractive_numbers
Attractive numbers
A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show sequence items up to   120. Reference   The OEIS entry:   A063989: Numbers with a prime number of prime divisors.
#Phix
Phix
function attractive(integer lim) sequence s = {} for i=1 to lim do integer n = length(prime_factors(i,true)) if is_prime(n) then s &= i end if end for return s end function sequence s = attractive(120) printf(1,"There are %d attractive numbers up to and including %d:\n",{length(s),120}) pp(s,{pp_IntCh,false}) for i=3 to 6 do atom t0 = time() integer p = power(10,i), l = length(attractive(p)) string e = elapsed(time()-t0) printf(1,"There are %,d attractive numbers up to %,d (%s)\n",{l,p,e}) end for
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
#Ruby
Ruby
def time2deg(t) raise "invalid time" unless m = t.match(/^(\d\d):(\d\d):(\d\d)$/) hh,mm,ss = m[1..3].map {|e| e.to_i} raise "invalid time" unless (0..23).include? hh and (0..59).include? mm and (0..59).include? ss (hh*3600 + mm*60 + ss) * 360 / 86400.0 end   def deg2time(d) sec = (d % 360) * 86400 / 360.0 "%02d:%02d:%02d" % [sec/3600, (sec%3600)/60, sec%60] end   def mean_time(times) deg2time(mean_angle(times.map {|t| time2deg t})) end   puts mean_time ["23:00:17", "23:40:20", "00:12:45", "00:17:19"]
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
#REXX
REXX
Note that the second set of angles: 90 180 270 360 is the same as: 90 180 -90 0 and: -270 -180 -90 -360 and other combinations.
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
#Ring
Ring
  # Project : Averages/Mean angle   load "stdlib.ring" decimals(6) pi = 3.1415926535897 angles = [350,10] see meanangle(angles, len(angles)) + nl angles = [90,180,270,360] see meanangle(angles, len(angles)) + nl angles = [10,20,30] see meanangle(angles, len(angles)) + nl   func meanangle(angles, n) sumsin = 0 sumcos = 0 for i = 1 to n sumsin = sumsin + sin(angles[i]*pi/180) sumcos = sumcos + cos(angles[i]*pi/180) next return 180/pi*atan3(sumsin, sumcos)   func atan3(y,x) if x <= 0 return sign(y)*pi/2 ok if x>0 return atan(y/x) else if y>0 return atan(y/x)+pi else return atan(y/x)-pi ok ok  
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
#Ruby
Ruby
require 'complex' # Superfluous in Ruby >= 2.0; complex is added to core.   def deg2rad(d) d * Math::PI / 180 end   def rad2deg(r) r * 180 / Math::PI end   def mean_angle(deg) rad2deg((deg.inject(0) {|z, d| z + Complex.polar(1, deg2rad(d))} / deg.length).arg) end   [[350, 10], [90, 180, 270, 360], [10, 20, 30]].each {|angles| puts "The mean angle of %p is: %f degrees" % [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
#Java
Java
// Note: this function modifies the input list public static double median(List<Double> list) { Collections.sort(list); return (list.get(list.size() / 2) + list.get((list.size() - 1) / 2)) / 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
#JavaScript
JavaScript
function median(ary) { if (ary.length == 0) return null; ary.sort(function (a,b){return a - b}) var mid = Math.floor(ary.length / 2); if ((ary.length % 2) == 1) // length is odd return ary[mid]; else return (ary[mid - 1] + ary[mid]) / 2; }   median([]); // null median([5,3,4]); // 4 median([5,4,2,3]); // 3.5 median([3,4,1,-8.4,7.2,4,1,1.2]); // 2.1
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
#Maple
Maple
x := [ seq( 1 .. 10 ) ]; Means := proc( x ) uses Statistics; return Mean( x ), GeometricMean( x ), HarmonicMean( x ); end proc: Arithmeticmean, Geometricmean, Harmonicmean := Means( x );   is( Arithmeticmean >= Geometricmean and Geometricmean >= Harmonicmean );  
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.
#Wren
Wren
import "/big" for BigInt import "/trait" for Comparable   class BTernary is Comparable { toBT_(v) { if (v < BigInt.zero) return flip_(toBT_(-v)) if (v == BigInt.zero) return "" var rem = mod3_(v) return (rem == BigInt.zero) ? toBT_(v/BigInt.three) + "0" : (rem == BigInt.one) ? toBT_(v/BigInt.three) + "+" : toBT_((v + BigInt.one)/BigInt.three) + "-" }   flip_(s) { var sb = "" for (c in s) { sb = sb + ((c == "+") ? "-" : (c == "-") ? "+" : "0") } return sb }   mod3_(v) { if (v > BigInt.zero) return v % BigInt.three return ((v % BigInt.three) + BigInt.three) % BigInt.three }   addDigits2_(a, b) { return (a == "0") ? b : (b == "0") ? a : (a == "+") ? ((b == "+") ? "+-" : "0") : (b == "+") ? "0" : "-+" }   addDigits3_(a, b, carry) { var sum1 = addDigits2_(a, b) var sum2 = addDigits2_(sum1[-1], carry) return (sum1.count == 1) ? sum2 : (sum2.count == 1) ? sum1[0] + sum2 : sum1[0] }   construct new(value) { if (value is String && value.all { |c| "0+-".contains(c) }) { _value = value.trimStart("0") } else if (value is BigInt) { _value = toBT_(value) } else if (value is Num && value.isInteger) { _value = toBT_(BigInt.new(value)) } else { Fiber.abort("Invalid argument.") } }   value { _value }   +(other) { var a = _value var b = other.value var longer = (a.count > b.count) ? a : b var shorter = (a.count > b.count) ? b : a while (shorter.count < longer.count) shorter = "0" + shorter a = longer b = shorter var carry = "0" var sum = "" for (i in 0...a.count) { var place = a.count - i - 1 var digisum = addDigits3_(a[place], b[place], carry) carry = (digisum.count != 1) ? digisum[0] : "0" sum = digisum[-1] + sum } sum = carry + sum return BTernary.new(sum) }   - { BTernary.new(flip_(_value)) }   -(other) { this + (-other) }   *(other) { var that = other.clone() var one = BTernary.new(1) var zero = BTernary.new(0) var mul = zero var flipFlag = false if (that < zero) { that = -that flipFlag = true } var i = one while (i <= that) { mul = mul + this i = i + one } if (flipFlag) mul = -mul return mul }   toBigInt { var len = _value.count var sum = BigInt.zero var pow = BigInt.one for (i in 0...len) { var c = _value[len-i-1] var dig = (c == "+") ? BigInt.one : (c == "-") ? BigInt.minusOne : BigInt.zero if (dig != BigInt.zero) sum = sum + dig*pow pow = pow * BigInt.three } return sum }   compare(other) { this.toBigInt.compare(other.toBigInt) }   clone() { BTernary.new(_value) }   toString { _value } }   var a = BTernary.new("+-0++0+") var b = BTernary.new(-436) var c = BTernary.new("+-++-") System.print("a = %(a.toBigInt)") System.print("b = %(b.toBigInt)") System.print("c = %(c.toBigInt)") var bResult = a * (b - c) var iResult = bResult.toBigInt System.print("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.
#SQL
SQL
  /* This code is an implementation of Babbage Problem in SQL ORACLE 19c p_ziel -- the substring to search for, which can start with leading zeros p_max -- upper bound of the cycle v_max -- safe determination of the upper bound of the cycle v_start -- safe starting point */ WITH FUNCTION babbage(p_ziel IN varchar2, p_max INTEGER) RETURN varchar2 IS v_max INTEGER := greatest(p_max,to_number('1E+'||LENGTH(to_char(p_ziel)))); v_start NUMBER := CASE WHEN substr(p_ziel,1,1)='0' THEN CEIL(SQRT('1'||p_ziel)) ELSE CEIL(SQRT(p_ziel)) END; v_length NUMBER := to_number('1E+'||LENGTH(to_char(p_ziel))); BEGIN -- first check IF substr(p_ziel,-1) IN (2,3,7,8) THEN RETURN 'The exact square of an integer cannot end with '''||substr(p_ziel,-1)||''', so there is no such smallest number whose square ends in '''||p_ziel||''''; END IF; -- second check IF regexp_count(p_ziel,'([^0]0{1,}$)')=1 AND MOD(regexp_count(regexp_substr(p_ziel,'(0{1,}$)'),'0'),2)=1 THEN RETURN 'An exact square of an integer cannot end with an odd number of zeros, so there is no such smallest number whose square ends in '''||p_ziel||''''; END IF; -- main cycle while v_start < v_max loop exit WHEN MOD(v_start**2,v_length) = p_ziel; v_start := v_start + 1; END loop; -- output IF v_start = v_max THEN RETURN 'There is no such smallest number before '||v_max||' whose square ends in '''||p_ziel||''''; ELSE RETURN ''||v_start||' is the smallest number, whose square '||regexp_replace(to_char(v_start**2),'(\d{1,})('||p_ziel||')','\1''\2''')||' ends in '''||p_ziel||''''; END IF; -- END;   --Test SELECT babbage('222',100000) AS res FROM dual UNION ALL SELECT babbage('33',100000) AS res FROM dual UNION ALL SELECT babbage('17',100000) AS res FROM dual UNION ALL SELECT babbage('888',100000) AS res FROM dual UNION ALL SELECT babbage('1000',100000) AS res FROM dual UNION ALL SELECT babbage('000',100000) AS res FROM dual UNION ALL SELECT babbage('269696',100000) AS res FROM dual -- strict Babbage Problem UNION ALL SELECT babbage('269696',10) AS res FROM dual UNION ALL SELECT babbage('169696',10) AS res FROM dual UNION ALL SELECT babbage('19696',100000) AS res FROM dual UNION ALL SELECT babbage('04',100000) AS res FROM dual;  
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
#F.23
F#
let isBalanced str = let rec loop count = function | ']'::_ when count = 0 -> false | '['::xs -> loop (count+1) xs | ']'::xs -> loop (count-1) xs | [] -> count = 0 | _::_ -> false   str |> Seq.toList |> loop 0     let shuffle arr = let rnd = new System.Random() Array.sortBy (fun _ -> rnd.Next()) arr   let generate n = new string( String.replicate n "[]" |> Array.ofSeq |> shuffle )     for n in 1..10 do let s = generate n printfn "\"%s\" is balanced: %b" s (isBalanced s)
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file
Append a record to the end of a text file
Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. This feature is most useful in the case of log files, where many jobs may be appending to the log file at the same time, or where care must be taken to avoid concurrently overwriting the same record from another job. Task Given a two record sample for a mythical "passwd" file: Write these records out in the typical system format. Ideally these records will have named fields of various types. Close the file, then reopen the file for append. Append a new record to the file and close the file again. Take appropriate care to avoid concurrently overwrites from another job. Open the file and demonstrate the new record has indeed written to the end. Source record field types and contents. account password UID GID fullname,office,extension,homephone,email directory shell string string int int struct(string,string,string,string,string) string string jsmith x 1001 1000 Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected] /home/jsmith /bin/bash jdoe x 1002 1000 Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected] /home/jdoe /bin/bash Record to be appended. account password UID GID fullname,office,extension,homephone,email directory shell string string int int struct(string,string,string,string,string) string string xyz x 1003 1000 X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected] /home/xyz /bin/bash Resulting file format: should mimic Linux's /etc/passwd file format with particular attention to the "," separator used in the GECOS field. But if the specific language has a particular or unique format of storing records in text file, then this format should be named and demonstrated with an additional example. Expected output: Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash Finally: Provide a summary of the language's "append record" capabilities in a table. eg. Append Capabilities. Data Representation IO Library Append Possible Automatic Append Multi-tasking Safe In core On disk C struct CSV text file glibc/stdio ☑ ☑ ☑ (Not all, eg NFS) Alternatively: If the language's appends can not guarantee its writes will always append, then note this restriction in the table. If possible, provide an actual code example (possibly using file/record locking) to guarantee correct concurrent appends.
#Julia
Julia
  using SHA # security instincts say do not write bare passwords to a shared file even in toy code :)   mutable struct Personnel fullname::String office::String extension::String homephone::String email::String Personnel(ful,off,ext,hom,ema) = new(ful,off,ext,hom,ema) end   mutable struct Passwd account::String password::String uid::Int32 gid::Int32 personal::Personnel directory::String shell::String Passwd(acc,pas,uid,gid,per,dir,she) = new(acc,pas,uid,gid,per,dir,she) end   function writepasswd(filename, passrecords) if(passrecords isa Array) == false passrecords = [passrecords] end fh = open(filename, "a") # should throw an exception if cannot open in a locked or exclusive mode for append for pas in passrecords record = join([pas.account, bytes2hex(sha256(pas.password)), pas.uid, pas.gid, join([pas.personal.fullname, pas.personal.office, pas.personal.extension, pas.personal.homephone, pas.personal.email], ','), pas.directory, pas.shell], ':') write(fh, record, "\n") end close(fh) end   const jsmith = Passwd("jsmith","x",1001, 1000, Personnel("Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "[email protected]"), "/home/jsmith", "/bin/bash") const jdoe = Passwd("jdoe","x",1002, 1000, Personnel("Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "[email protected]"), "/home/jdoe", "/bin/bash") const xyz = Passwd("xyz","x",1003, 1000, Personnel("X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "[email protected]"), "/home/xyz", "/bin/bash")   const pfile = "pfile.csv" writepasswd(pfile, [jsmith, jdoe]) println("Before last record added, file is:\n$(readstring(pfile))") writepasswd(pfile, xyz) println("After last record added, file is:\n$(readstring(pfile))")  
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file
Append a record to the end of a text file
Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. This feature is most useful in the case of log files, where many jobs may be appending to the log file at the same time, or where care must be taken to avoid concurrently overwriting the same record from another job. Task Given a two record sample for a mythical "passwd" file: Write these records out in the typical system format. Ideally these records will have named fields of various types. Close the file, then reopen the file for append. Append a new record to the file and close the file again. Take appropriate care to avoid concurrently overwrites from another job. Open the file and demonstrate the new record has indeed written to the end. Source record field types and contents. account password UID GID fullname,office,extension,homephone,email directory shell string string int int struct(string,string,string,string,string) string string jsmith x 1001 1000 Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected] /home/jsmith /bin/bash jdoe x 1002 1000 Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected] /home/jdoe /bin/bash Record to be appended. account password UID GID fullname,office,extension,homephone,email directory shell string string int int struct(string,string,string,string,string) string string xyz x 1003 1000 X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected] /home/xyz /bin/bash Resulting file format: should mimic Linux's /etc/passwd file format with particular attention to the "," separator used in the GECOS field. But if the specific language has a particular or unique format of storing records in text file, then this format should be named and demonstrated with an additional example. Expected output: Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash Finally: Provide a summary of the language's "append record" capabilities in a table. eg. Append Capabilities. Data Representation IO Library Append Possible Automatic Append Multi-tasking Safe In core On disk C struct CSV text file glibc/stdio ☑ ☑ ☑ (Not all, eg NFS) Alternatively: If the language's appends can not guarantee its writes will always append, then note this restriction in the table. If possible, provide an actual code example (possibly using file/record locking) to guarantee correct concurrent appends.
#Kotlin
Kotlin
// Version 1.2.41   import java.io.File   class Record( val account: String, val password: String, val uid: Int, val gid: Int, val gecos: List<String>, val directory: String, val shell: String ){ override fun toString() = "$account:$password:$uid:$gid:${gecos.joinToString(",")}:$directory:$shell" }   fun parseRecord(line: String): Record { val fields = line.split(':') return Record( fields[0], fields[1], fields[2].toInt(), fields[3].toInt(), fields[4].split(','), fields[5], fields[6] ) }   fun main(args: Array<String>) { val startData = listOf( "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash", "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash" ) val records = startData.map { parseRecord(it) } val f = File("passwd.csv") f.printWriter().use { for (record in records) it.println(record) } println("Initial records:\n") f.forEachLine { println(parseRecord(it)) }   val newData = "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash" val record = parseRecord(newData) if (!f.setWritable(true, true)) { println("\nFailed to make file writable only by owner\n.") } f.appendText("$record\n") println("\nRecords after another one is appended:\n") f.forEachLine { println(parseRecord(it)) } }
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
#Batch_File
Batch File
::assocarrays.cmd @echo off setlocal ENABLEDELAYEDEXPANSION set array.dog=1 set array.cat=2 set array.wolf=3 set array.cow=4 for %%i in (dog cat wolf cow) do call :showit array.%%i !array.%%i! set c=-27 call :mkarray sicko flu 5 measles 6 mumps 7 bromodrosis 8 for %%i in (flu measles mumps bromodrosis) do call :showit "sicko^&%%i" !sicko^&%%i! endlocal goto :eof   :mkarray set %1^&%2=%3 shift /2 shift /2 if "%2" neq "" goto :mkarray goto :eof   :showit echo %1 = %2 goto :eof  
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Fortran
Fortran
  program anti_primes use iso_fortran_env, only: output_unit implicit none   integer :: n, d, maxDiv, pCount   write(output_unit,*) "The first 20 anti-primes are:" n = 1 maxDiv = 0 pCount = 0 do if (pCount >= 20) exit   d = countDivisors(n) if (d > maxDiv) then write(output_unit,'(I0,x)', advance="no") n maxDiv = d pCount = pCount + 1 end if n = n + 1 end do write(output_unit,*) contains pure function countDivisors(n) integer, intent(in) :: n integer :: countDivisors integer :: i   countDivisors = 1 if (n < 2) return countDivisors = 2 do i = 2, n/2 if (modulo(n, i) == 0) countDivisors = countDivisors + 1 end do end function countDivisors end program anti_primes  
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#FreeBASIC
FreeBASIC
  ' convertido desde Ada Declare Function count_divisors(n As Integer) As Integer   Dim As Integer max_divisors, divisors, results(1 To 20), candidate, j candidate = 1   Function count_divisors(n As Integer) As Integer Dim As Integer i, count = 1 For i = 1 To n/2 If (n Mod i) = 0 Then count += 1 Next i count_divisors = count End Function   Print "Los primeros 20 anti-primos son:" For j = 1 To 20 Do divisors = count_divisors(Candidate) If max_divisors < divisors Then Results(j) = Candidate max_divisors = divisors Exit Do End If Candidate += 1 Loop Next j For j = 1 To 20 Print Results(j); Next j Print Sleep  
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.
#Racket
Racket
#lang racket   (struct bucket (value [lock #:auto]) #:auto-value #f #:mutable #:transparent)   (define *buckets* (build-vector 10 (λ (i) (bucket 100))))   (define (show-buckets) (let* ([values (for/list ([b *buckets*]) (bucket-value b))] [total (apply + values)]) (append values (list '- total))))   (define *equalizations* 0) (define *randomizations* 0) (define *blocks* 0)   (define (show-stats) (let ([n (length *log*)] [log (reverse *log*)]) (printf "Equalizations ~a, Randomizations ~a, Transfers: ~a, Blocks ~a\n" *equalizations* *randomizations* n *blocks*) (for ([i (in-range 10)]) (define j (min (floor (* i (/ n 9))) (sub1 n))) (printf "~a (~a). " (add1 i) (add1 j)) (displayln (list-ref log j)))))   (define *log* (list (show-buckets)))   (define-syntax-rule (inc! x) (set! x (add1 x)))   (define (get-bucket i) (vector-ref *buckets* i))   (define (get-value i) (bucket-value (get-bucket i))) (define (set-value! i v) (set-bucket-value! (get-bucket i) v))   (define (locked? i) (bucket-lock (vector-ref *buckets* i))) (define (lock! i v) (set-bucket-lock! (get-bucket i) v)) (define (unlock! i) (lock! i #f))   (define *clamp-lock* #f)   (define (clamp i j) (cond [*clamp-lock* (inc! *blocks*) #f] [else (set! *clamp-lock* #t) (let ([result #f] [g (gensym)]) (unless (locked? i) (lock! i g) (cond [(locked? j) (unlock! i)] [else (lock! j g) (set! result #t)])) (unless result (inc! *blocks*)) (set! *clamp-lock* #f) result)]))   (define (unclamp i j) (unlock! i) (unlock! j))   (define (transfer i j amount) (let* ([lock1 (locked? i)] [lock2 (locked? j)] [a (get-value i)] [b (get-value j)] [c (- a amount)] [d (+ b amount)]) (cond [(< c 0) (error 'transfer "Removing too much.")] [(< d 0) (error 'transfer "Stealing too much.")] [(and lock1 (equal? lock1 lock2)) (set-value! i c) (set-value! j d) (set! *log* (cons (show-buckets) *log*))] [else (error 'transfer "Lock problem")])))   (define (equalize i j) (when (clamp i j) (let ([a (get-value i)] [b (get-value j)]) (unless (= a b) (transfer i j (if (> a b) (floor (/ (- a b) 2)) (- (floor (/ (- b a) 2))))) (inc! *equalizations*))) (unclamp i j)))   (define (randomize i j) (when (clamp i j) (let* ([a (get-value i)] [b (get-value j)] [t (+ a b)] [r (if (= t 0) 0 (random t))]) (unless (= r 0) (transfer i j (- a r)) (inc! *randomizations*))) (unclamp i j)))   (thread (λ () (for ([_ (in-range 500000)]) (equalize (random 10) (random 10))))) (thread (λ () (for ([_ (in-range 500000)]) (randomize (random 10) (random 10)))))
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.
#Raku
Raku
#| A collection of non-negative integers, with atomic operations. class BucketStore {   has $.elems is required; has @!buckets = ^1024 .pick xx $!elems; has $lock = Lock.new;   #| Returns an array with the contents of all buckets. method buckets { $lock.protect: { [@!buckets] } }   #| Transfers $amount from bucket at index $from, to bucket at index $to. method transfer ($amount, :$from!, :$to!) { return if $from == $to;   $lock.protect: { my $clamped = $amount min @!buckets[$from];   @!buckets[$from] -= $clamped; @!buckets[$to] += $clamped; } } }   # Create bucket store my $bucket-store = BucketStore.new: elems => 8; my $initial-sum = $bucket-store.buckets.sum;   # Start a thread to equalize buckets Thread.start: { loop { my @buckets = $bucket-store.buckets;   # Pick 2 buckets, so that $to has not more than $from my ($to, $from) = @buckets.keys.pick(2).sort({ @buckets[$_] });   # Transfer half of the difference, rounded down $bucket-store.transfer: ([-] @buckets[$from, $to]) div 2, :$from, :$to; } }   # Start a thread to distribute values among buckets Thread.start: { loop { my @buckets = $bucket-store.buckets;   # Pick 2 buckets my ($to, $from) = @buckets.keys.pick(2);   # Transfer a random portion $bucket-store.transfer: ^@buckets[$from] .pick, :$from, :$to; } }   # Loop to display buckets loop { sleep 1;   my @buckets = $bucket-store.buckets; my $sum = @buckets.sum;   say "{@buckets.fmt: '%4d'}, total $sum";   if $sum != $initial-sum { note "ERROR: Total changed from $initial-sum to $sum"; exit 1; } }
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.
#Ol
Ol
  (define i 24)   (assert i ===> 42)  
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Oz
Oz
declare proc {PrintNumber N} N=42 %% assert {Show N} end in {PrintNumber 42} %% ok {PrintNumber 11} %% throws
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.
#PARI.2FGP
PARI/GP
#include <assert.h> #include <pari/pari.h>   void test() { GEN a; // ... input or change a here   assert(equalis(a, 42)); /* Aborts program if a is not 42, unless the NDEBUG macro was defined */ }
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.
#Dyalect
Dyalect
func Array.Select(pred) { let ys = [] for x in this when pred(x) { ys.Add(x) } return ys }   var arr = [1, 2, 3, 4, 5] var squares = arr.Select(x => x * x)   print(squares)
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#D.C3.A9j.C3.A0_Vu
Déjà Vu
!. map @++ [ 1 4 8 ]   #implemented roughly like this: #map f lst: # ] # for i in lst: # f i # [
http://rosettacode.org/wiki/Averages/Mode
Averages/Mode
Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#PicoLisp
PicoLisp
(de modes (Lst) (let A NIL (for X Lst (accu 'A X 1) ) (mapcar car (maxi cdar (by cdr group A) ) ) ) )
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
#PL.2FI
PL/I
av: procedure options (main); /* 28 October 2013 */ declare x(10) fixed binary static initial (1, 4, 2, 6, 2, 5, 6, 2, 4, 2); declare f(32767) fixed binary; declare (j, n, max, value) fixed binary; declare i fixed;   n = hbound(x,1);   do i = 1 to n; j = x(i); f(j) = f(j) + 1; end; max = 0; do i = 1 to hbound(f,1); if max < f(i) then do; max = f(i); value = i; end; end; put list ('The mode value is ' || value || ' occurred ' || max || ' times.');   end av;
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
#F.23
F#
  let myMap = [ ("Hello", 1); ("World", 2); ("!", 3) ]   for k, v in myMap do printfn "%s -> %d" k 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
#Factor
Factor
H{ { "hi" "there" } { "a" "b" } } [ ": " glue print ] assoc-each
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]
#Rust
Rust
use std::cmp::Ordering;   struct IIRFilter<'f>(&'f [f32], &'f [f32]);   impl<'f> IIRFilter<'f> { pub fn with_coefficients(a: &'f [f32], b: &'f [f32]) -> IIRFilter<'f> { IIRFilter(a, b) }   // Performs the calculation as an iterator chain. pub fn apply<I: Iterator<Item = &'f f32> + 'f>( &self, samples: I, ) -> impl Iterator<Item = f32> + 'f { // Name some things for readability let a_coeff = self.0; let b_coeff = self.1;   let mut prev_results = Vec::<f32>::new(); let mut prev_samples = Vec::<f32>::new();   // The actual calculation, done one number at a time samples.enumerate() // (i, sample[i]) .map(move |(i, sample)| { // for each sample, apply this function prev_samples.push(*sample); prev_results.push(0f32); // the initial version of the previous result   let sum_b: f32 = b_coeff.iter() // for each coefficient in b .enumerate() // (j, b_coeff[j]) .map(|(j, c)| { // calculate the weight of the coefficient if i >= j { (*c) * prev_samples[i-j] } else { 0f32 } }) .sum(); // add them all together   let sum_a: f32 = a_coeff.iter() // for each coefficient in a .enumerate() // (j, a_coeff[j]) .map(|(j, c)| { // calculate the weight of the coefficient if i >= j { (*c) * prev_results[i-j] } else { 0f32 } }) .sum(); // add them all together   // perform the final calculation let result = (sum_b - sum_a) / a_coeff[0];   // update the previous result for the next iteration prev_results[i] = result;   // return the current result in this iteration result } ) } }   fn main() { let a: &[f32] = &[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17]; let b: &[f32] = &[0.16666667, 0.5, 0.5, 0.16666667];   let samples: Vec<f32> = vec![ -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, ];   for (i, result) in IIRFilter::with_coefficients(a, b) .apply(samples.iter()) .enumerate() { print!("{:.8}", result); if (i + 1) % 5 != 0 { print!(", "); } else { println!(); } } println!(); }
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]
#Scala
Scala
object ButterworthFilter extends App { private def filter(a: Vector[Double], b: Vector[Double], signal: Vector[Double]): Vector[Double] = {   @scala.annotation.tailrec def outer(i: Int, acc: Vector[Double]): Vector[Double] = { if (i >= signal.length) acc else { @scala.annotation.tailrec def inner0(j: Int, tmp: Double): Double = if (j >= b.length) tmp else if ((i - j) >= 0) inner0(j + 1, tmp + b(j) * signal(i - j)) else inner0(j + 1, tmp)   @scala.annotation.tailrec def inner1(j: Int, tmp: Double): Double = if (j >= a.length) tmp else if (i - j >= 0) inner1(j + 1, tmp - a(j) * acc(i - j)) else inner1(j + 1, tmp)   outer(i + 1, acc :+ inner1(1, inner0(0, 0D)) / a(0)) } }   outer(0, Vector()) }   filter(Vector[Double](1, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17), Vector[Double](0.16666667, 0.5, 0.5, 0.16666667), Vector[Double]( -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) ).grouped(5) .map(_.map(x => f"$x% .8f")) .foreach(line => println(line.mkString(" ")))   }
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
#Fantom
Fantom
  class Main { static Float average (Float[] nums) { if (nums.size == 0) return 0.0f Float sum := 0f nums.each |num| { sum += num } return sum / nums.size.toFloat }   public static Void main () { [[,], [1f], [1f,2f,3f,4f]].each |Float[] i| { echo ("Average of $i is: " + average(i)) } } }  
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
#Fish
Fish
!vl0=?vl1=?vl&! v< +<>0n; >n; >l1)?^&,n;
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%)
#Wren
Wren
import "random" for Random import "/fmt" for Fmt   var nmax = 20 var rand = Random.new()   var avg = Fn.new { |n| var tests = 1e4 var sum = 0 for (t in 0...tests) { var v = List.filled(nmax, false) var x = 0 while (!v[x]) { v[x] = true sum = sum + 1 x = rand.int(n) } } return sum/tests }   var ana = Fn.new { |n| if (n < 2) return 1 var term = 1 var sum = 1 for (i in n-1..1) { term = term * i / n sum = sum + term } return sum }   System.print(" N average analytical (error)") System.print("=== ========= ============ =========") for (n in 1..nmax) { var a = avg.call(n) var b = ana.call(n) var ns = Fmt.d(3, n) var as = Fmt.f(9, a, 4) var bs = Fmt.f(12, b, 4) var e = (a - b).abs/ b * 100 var es = Fmt.f(6, e, 2) System.print("%(ns) %(as)  %(bs) (%(es)\%)") }
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
#Vlang
Vlang
fn sma(period int) fn(f64) f64 { mut i := int(0) mut sum := f64(0) mut storage := []f64{len: 0, cap:period}   return fn[mut storage, mut sum, mut i, period](input f64) f64 { if storage.len < period { sum += input storage << input }   sum += input - storage[i] storage[i], i = input, (i+1)%period return sum / f64(storage.len) } }   fn main() { sma3 := sma(3) sma5 := sma(5) println("x sma3 sma5") for x in [f64(1), 2, 3, 4, 5, 5, 4, 3, 2, 1] { println("${x:5.3f} ${sma3(x):5.3f} ${sma5(x):5.3f}") } }
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.
#PHP
PHP
<?php function isPrime ($x) { if ($x < 2) return false; if ($x < 4) return true; if ($x % 2 == 0) return false; for ($d = 3; $d < sqrt($x); $d++) { if ($x % $d == 0) return false; } return true; }   function countFacs ($n) { $count = 0; $divisor = 1; if ($n < 2) return 0; while (!isPrime($n)) { while (!isPrime($divisor)) $divisor++; while ($n % $divisor == 0) { $n /= $divisor; $count++; } $divisor++; if ($n == 1) return $count; } return $count + 1; }   for ($i = 1; $i <= 120; $i++) { if (isPrime(countFacs($i))) echo $i."&ensp;"; } ?>
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
#Run_BASIC
Run BASIC
global pi pi = acs(-1)   Print "Average of:" for i = 1 to 4 read t$ print t$ a = time2angle(t$) ss = ss+sin(a) sc = sc+cos(a) next a = atan2(ss,sc) if a < 0 then a = a + 2 * pi print "is ";angle2time$(a) end data "23:00:17", "23:40:20", "00:12:45", "00:17:19"   function nn$(n) nn$ = right$("0";n, 2) end function   function angle2time$(a) a = int(a / 2 / pi * 24 * 60 * 60) ss = a mod 60 a = int(a / 60) mm=a mod 60 hh=int(a/60) angle2time$=nn$(hh);":";nn$(mm);":";nn$(ss) end function   function time2angle(time$) hh=val(word$(time$,1,":")) mm=val(word$(time$,2,":")) ss=val(word$(time$,3,":")) time2angle=2*pi*(60*(60*hh+mm)+ss)/24/60/60 end function   function atan2(y, x) if y <> 0 then atan2 = (2 * (atn((sqr((x * x) + (y * y)) - x)/ y))) else atan2 = (y=0)*(x<0)*pi end if End Function
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
#Rust
Rust
  use std::f64::consts::PI;   #[derive(Debug, PartialEq, Eq)] struct Time { h: u8, m: u8, s: u8, }   impl Time { /// Create a Time from equivalent radian measure fn from_radians(mut rads: f64) -> Time { rads %= 2.0 * PI; if rads < 0.0 { rads += 2.0 * PI } Time { h: (rads * 12.0 / PI) as u8, m: ((rads * 720.0 / PI) % 60.0) as u8, s: ((rads * 43200.0 / PI) % 60.0).round() as u8, } }   /// Create a Time from H/M/S fn from_parts(h: u8, m: u8, s: u8) -> Result<Time, ()> { if h > 23 || m > 59 || s > 59 { return Err(()); } Ok(Time { h, m, s }) }   /// Return time as measure in radians fn as_radians(&self) -> f64 { ((self.h as f64 / 12.0) + (self.m as f64 / 720.0) + (self.s as f64 / 43200.0)) * PI } }   /// Compute the mean time from a slice of times fn mean_time(times: &[Time]) -> Time { // compute sum of sines and cosines let (ss, sc) = times .iter() .map(Time::as_radians) .map(|a| (a.sin(), a.cos())) .fold((0.0, 0.0), |(ss, sc), (s, c)| (ss + s, sc + c)); // scaling does not matter for atan2, meaning we do not have to divide sums by len Time::from_radians(ss.atan2(sc)) }   fn main() { let times = [ Time::from_parts(23, 00, 17).unwrap(), Time::from_parts(23, 40, 20).unwrap(), Time::from_parts(00, 12, 45).unwrap(), Time::from_parts(00, 17, 19).unwrap(), ];   let mean = mean_time(&times);   println!("{:02}:{:02}:{:02}", mean.h, mean.m, mean.s); }    
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
#Rust
Rust
  use std::f64; // the macro is from // http://stackoverflow.com/questions/30856285/assert-eq-with-floating- // point-numbers-and-delta fn mean_angle(angles: &[f64]) -> f64 { let length: f64 = angles.len() as f64; let cos_mean: f64 = angles.iter().fold(0.0, |sum, i| sum + i.to_radians().cos()) / length; let sin_mean: f64 = angles.iter().fold(0.0, |sum, i| sum + i.to_radians().sin()) / length; (sin_mean).atan2(cos_mean).to_degrees() }   fn main() { let angles1 = [350.0_f64, 10.0]; let angles2 = [90.0_f64, 180.0, 270.0, 360.0]; let angles3 = [10.0_f64, 20.0, 30.0]; println!("Mean Angle for {:?} is {:.5} degrees", &angles1, mean_angle(&angles1)); println!("Mean Angle for {:?} is {:.5} degrees", &angles2, mean_angle(&angles2)); println!("Mean Angle for {:?} is {:.5} degrees", &angles3, mean_angle(&angles3)); }   macro_rules! assert_diff{ ($x: expr,$y : expr, $diff :expr)=>{ if ( $x - $y ).abs() > $diff { panic!("floating point difference is to big {}", $x - $y ); } } }   #[test] fn calculate() { let angles1 = [350.0_f64, 10.0]; let angles2 = [90.0_f64, 180.0, 270.0, 360.0]; let angles3 = [10.0_f64, 20.0, 30.0]; assert_diff!(0.0, mean_angle(&angles1), 0.001); assert_diff!(-90.0, mean_angle(&angles2), 0.001); assert_diff!(20.0, mean_angle(&angles3), 0.001); }  
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
#Scala
Scala
trait MeanAnglesComputation { import scala.math.{Pi, atan2, cos, sin}   def meanAngle(angles: List[Double], convFactor: Double = 180.0 / Pi) = { val sums = angles.foldLeft((.0, .0))((r, c) => { val rads = c / convFactor (r._1 + sin(rads), r._2 + cos(rads)) }) val result = atan2(sums._1, sums._2) (result + (if (result.signum == -1) 2 * Pi else 0.0)) * convFactor } }   object MeanAngles extends App with MeanAnglesComputation { assert(meanAngle(List(350, 10), 180.0 / math.Pi).round == 360, "Unexpected result with 350, 10") assert(meanAngle(List(90, 180, 270, 360)).round == 270, "Unexpected result with 90, 180, 270, 360") assert(meanAngle(List(10, 20, 30)).round == 20, "Unexpected result with 10, 20, 30") println("Successfully completed without errors.") }
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
#jq
jq
def median: length as $length | sort as $s | if $length == 0 then null else ($length / 2 | floor) as $l2 | if ($length % 2) == 0 then ($s[$l2 - 1] + $s[$l2]) / 2 else $s[$l2] end 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
#Julia
Julia
using Statistics function median2(n) s = sort(n) len = length(n) if len % 2 == 0 return (s[floor(Int, len / 2) + 1] + s[floor(Int, len / 2)]) / 2 else return s[floor(Int, len / 2) + 1] end end   a = [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2] b = [4.1, 7.2, 1.7, 9.3, 4.4, 3.2]   @show a b median2(a) median(a) median2(b) median(b)
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of positive integers. The most common of the three means, the arithmetic mean, is the sum of the list divided by its length: A ( x 1 , … , x n ) = x 1 + ⋯ + x n n {\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}} The geometric mean is the n {\displaystyle n} th root of the product of the list: G ( x 1 , … , x n ) = x 1 ⋯ x n n {\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}} The harmonic mean is n {\displaystyle n} divided by the sum of the reciprocal of each item in the list: H ( x 1 , … , x n ) = n 1 x 1 + ⋯ + 1 x n {\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}} See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Print["{Arithmetic Mean, Geometric Mean, Harmonic Mean} = ", N@Through[{Mean, GeometricMean, HarmonicMean}[Range@10]]]
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.
#Swift
Swift
import Swift   for i in 2...Int.max { if i * i % 1000000 == 269696 { print(i, "is the smallest number that ends with 269696") break } }
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
#Factor
Factor
USING: io formatting locals kernel math sequences unicode.case ; IN: balanced-brackets   :: balanced ( str -- ) 0 :> counter! 1 :> ok! str [ dup length 0 > ] [ 1 cut swap "[" = [ counter 1 + counter! ] [ counter 1 - counter! ] if counter 0 < [ 0 ok! ] when ] while drop ok 0 = [ "NO" ] [ counter 0 > [ "NO" ] [ "YES" ] if ] if print ;   readln balanced
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file
Append a record to the end of a text file
Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. This feature is most useful in the case of log files, where many jobs may be appending to the log file at the same time, or where care must be taken to avoid concurrently overwriting the same record from another job. Task Given a two record sample for a mythical "passwd" file: Write these records out in the typical system format. Ideally these records will have named fields of various types. Close the file, then reopen the file for append. Append a new record to the file and close the file again. Take appropriate care to avoid concurrently overwrites from another job. Open the file and demonstrate the new record has indeed written to the end. Source record field types and contents. account password UID GID fullname,office,extension,homephone,email directory shell string string int int struct(string,string,string,string,string) string string jsmith x 1001 1000 Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected] /home/jsmith /bin/bash jdoe x 1002 1000 Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected] /home/jdoe /bin/bash Record to be appended. account password UID GID fullname,office,extension,homephone,email directory shell string string int int struct(string,string,string,string,string) string string xyz x 1003 1000 X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected] /home/xyz /bin/bash Resulting file format: should mimic Linux's /etc/passwd file format with particular attention to the "," separator used in the GECOS field. But if the specific language has a particular or unique format of storing records in text file, then this format should be named and demonstrated with an additional example. Expected output: Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash Finally: Provide a summary of the language's "append record" capabilities in a table. eg. Append Capabilities. Data Representation IO Library Append Possible Automatic Append Multi-tasking Safe In core On disk C struct CSV text file glibc/stdio ☑ ☑ ☑ (Not all, eg NFS) Alternatively: If the language's appends can not guarantee its writes will always append, then note this restriction in the table. If possible, provide an actual code example (possibly using file/record locking) to guarantee correct concurrent appends.
#Lua
Lua
function append(tbl,filename) local file,err = io.open(filename, "a") if err then return err end   file:write(tbl.account..":") file:write(tbl.password..":") file:write(tbl.uid..":") file:write(tbl.gid..":")   for i,v in ipairs(tbl.gecos) do if i>1 then file:write(",") end file:write(v) end file:write(":")   file:write(tbl.directory..":") file:write(tbl.shell.."\n")   file:close() end   local smith = {} smith.account = "jsmith" smith.password = "x" smith.uid = 1001 smith.gid = 1000 smith.gecos = {"Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "[email protected]"} smith.directory = "/home/jsmith" smith.shell = "/bin/bash" append(smith, ".passwd")   local doe = {} doe.account = "jdoe" doe.password = "x" doe.uid = 1002 doe.gid = 1000 doe.gecos = {"Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "[email protected]"} doe.directory = "/home/jdoe" doe.shell = "/bin/bash" append(doe, ".passwd")   local xyz = {} xyz.account = "xyz" xyz.password = "x" xyz.uid = 1003 xyz.gid = 1000 xyz.gecos = {"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "[email protected]"} xyz.directory = "/home/xyz" xyz.shell = "/bin/bash" append(xyz, ".passwd")
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#BBC_BASIC
BBC BASIC
REM Store some values with their keys: PROCputdict(mydict$, "FF0000", "red") PROCputdict(mydict$, "00FF00", "green") PROCputdict(mydict$, "0000FF", "blue")   REM Retrieve some values using their keys: PRINT FNgetdict(mydict$, "green") PRINT FNgetdict(mydict$, "red") END   DEF PROCputdict(RETURN dict$, value$, key$) IF dict$ = "" dict$ = CHR$(0) dict$ += key$ + CHR$(1) + value$ + CHR$(0) ENDPROC   DEF FNgetdict(dict$, key$) LOCAL I%, J% I% = INSTR(dict$, CHR$(0) + key$ + CHR$(1)) IF I% = 0 THEN = "" ELSE I% += LEN(key$) + 2 J% = INSTR(dict$, CHR$(0), I%) = MID$(dict$, I%, J% - I%)
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Go
Go
package main   import "fmt"   func countDivisors(n int) int { if n < 2 { return 1 } count := 2 // 1 and n for i := 2; i <= n/2; i++ { if n%i == 0 { count++ } } return count }   func main() { fmt.Println("The first 20 anti-primes are:") maxDiv := 0 count := 0 for n := 1; count < 20; n++ { d := countDivisors(n) if d > maxDiv { fmt.Printf("%d ", n) maxDiv = d count++ } } fmt.Println() }
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Groovy
Groovy
def getAntiPrimes(def limit = 10) { def antiPrimes = [] def candidate = 1L def maxFactors = 0   while (antiPrimes.size() < limit) { def factors = factorize(candidate) if (factors.size() > maxFactors) { maxFactors = factors.size() antiPrimes << candidate } candidate++ } antiPrimes }
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.
#Ring
Ring
  # Project : Atomic updates   bucket = list(10) f2 = 0 for i = 1 to 10 bucket[i] = floor(random(9)*10) next   a = display("display:") see nl a = flatten(a) see "" + a + nl a = display("flatten:") see nl a = transfer(3,5) see a + nl see "19 from 3 to 5: " a = display(a) see nl   func display(a) display = 0 see "" + a + " " + char(9) for i = 1 to 10 display = display + bucket[i] see "" + bucket[i] + " " next see " total:" + display return display   func flatten(f) f1 = floor((f / 10) + 0.5) for i = 1 to 10 bucket[i] = f1 f2 = f2 + f1 next bucket[10] = bucket[10] + f - f2   func transfer(a1,a2) transfer = floor(random(9)/10 * bucket[a1]) bucket[a1] = bucket[a1] - transfer bucket[a2] = bucket[a2] + transfer  
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.
#Ruby
Ruby
require 'thread'   # A collection of buckets, filled with random non-negative integers. # There are atomic operations to look at the bucket contents, and # to move amounts between buckets. class BucketStore   # Creates a BucketStore with +nbuckets+ buckets. Fills each bucket # with a random non-negative integer. def initialize nbuckets # Create an array for the buckets @buckets = (0...nbuckets).map { rand(1024) }   # Mutex used to make operations atomic @mutex = Mutex.new end   # Returns an array with the contents of all buckets. def buckets @mutex.synchronize { Array.new(@buckets) } end   # Transfers _amount_ to bucket at array index _destination_, # from bucket at array index _source_. def transfer destination, source, amount # Do nothing if both buckets are same return nil if destination == source   @mutex.synchronize do # Clamp amount to prevent negative value in bucket amount = [amount, @buckets[source]].min   @buckets[source] -= amount @buckets[destination] += amount end nil end end   # Create bucket store bucket_store = BucketStore.new 8   # Get total amount in the store TOTAL = bucket_store.buckets.inject { |a, b| a += b }   # Start a thread to equalize buckets Thread.new do loop do # Pick 2 buckets buckets = bucket_store.buckets first = rand buckets.length second = rand buckets.length   # Swap buckets so that _first_ has not more than _second_ first, second = second, first if buckets[first] > buckets[second]   # Transfer half of the difference, rounded down bucket_store.transfer first, second, (buckets[second] - buckets[first]) / 2 end end   # Start a thread to distribute values among buckets Thread.new do loop do # Pick 2 buckets buckets = bucket_store.buckets first = rand buckets.length second = rand buckets.length   # Transfer random amount to _first_ from _second_ bucket_store.transfer first, second, rand(buckets[second]) end end   # Loop to display buckets loop do sleep 1   buckets = bucket_store.buckets   # Compute the total value in all buckets. # We calculate this outside BucketStore so BucketStore can't cheat by # always reporting the same value. n = buckets.inject { |a, b| a += b }   # Display buckets and total printf "%s, total %d\n", (buckets.map { |v| sprintf "%4d", v }.join " "), n   if n != TOTAL # This should never happen $stderr.puts "ERROR: Total changed from #{TOTAL} to #{n}" exit 1 end end
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.
#Pascal
Pascal
print "Give me a number: "; chomp(my $a = <>);   $a == 42 or die "Error message\n";   # Alternatives die "Error message\n" unless $a == 42; die "Error message\n" if not $a == 42; die "Error message\n" if $a != 42;
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Perl
Perl
print "Give me a number: "; chomp(my $a = <>);   $a == 42 or die "Error message\n";   # Alternatives die "Error message\n" unless $a == 42; die "Error message\n" if not $a == 42; die "Error message\n" if $a != 42;
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#E
E
def array := [1,2,3,4,5] def square(value) { return value * value }
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.
#EchoLisp
EchoLisp
  (vector-map sqrt #(0 4 16 49)) → #( 0 2 4 7) ;; or (map exp #(0 1 2)) → #( 1 2.718281828459045 7.38905609893065) ;; or (for/vector ([elem #(2 3 4)] [i (in-naturals)]) (printf "v[%d] = %a" i elem) (* elem elem)) v[0] = 2 v[1] = 3 v[2] = 4 → #( 4 9 16)  
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
#PowerShell
PowerShell
$data = @(1,1,1,2,3,4,5,5,6,7,7,7) $groups = $data | group-object | sort-object count -Descending $groups | ? {$_.Count -eq $groups[0].Count}
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
#Fantom
Fantom
  class Main { public static Void main () { Int:Str map := [1:"alpha", 2:"beta", 3:"gamma"]   map.keys.each |Int key| { echo ("Key is: $key") }   map.vals.each |Str value| { echo ("Value is: $value") }   map.each |Str value, Int key| { echo ("Key $key maps to $value") } } }  
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Forth
Forth
include ffl/hct.fs include ffl/hci.fs   \ Create hashtable and iterator in dictionary 10 hct-create htable htable hci-create hiter   \ Insert entries 1 s" hello" htable hct-insert 2 s" world" htable hct-insert 3 s" !" htable hct-insert   : iterate hiter hci-first BEGIN WHILE ." key = " hiter hci-key type ." , value = " . cr hiter hci-next REPEAT ;   iterate
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]
#Sidef
Sidef
func TDF_II_filter(signal, a, b) { var out = [0]*signal.len for i in ^signal { var this = 0 for j in ^b { i-j >= 0 && (this += b[j]*signal[i-j]) } for j in ^a { i-j >= 0 && (this -= a[j]* out[i-j]) } out[i] = this/a[0] } return out }   var signal = [ -0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589 ]   var a = [1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] var b = [0.16666667, 0.5, 0.5, 0.16666667 ] var f = TDF_II_filter(signal, a, b)   say "[" say f.map { "% 0.8f" % _ }.slices(5).map{.join(', ')}.join(",\n") say "]"
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]
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Function Filter(a As Double(), b As Double(), signal As Double()) As Double() Dim result(signal.Length - 1) As Double For i = 1 To signal.Length Dim tmp = 0.0 For j = 1 To b.Length If i - j < 0 Then Continue For End If tmp += b(j - 1) * signal(i - j) Next For j = 2 To a.Length If i - j < 0 Then Continue For End If tmp -= a(j - 1) * result(i - j) Next tmp /= a(0) result(i - 1) = tmp Next Return result End Function   Sub Main() Dim a() As Double = {1.0, -0.000000000000000277555756, 0.333333333, -1.85037171E-17} Dim b() As Double = {0.16666667, 0.5, 0.5, 0.16666667}   Dim signal() As Double = { -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 }   Dim result = Filter(a, b, signal) For i = 1 To result.Length Console.Write("{0,11:F8}", result(i - 1)) Console.Write(If(i Mod 5 <> 0, ", ", vbNewLine)) Next End Sub   End Module
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
#Forth
Forth
: fmean ( addr n -- f ) 0e dup 0= if 2drop exit then tuck floats bounds do i f@ f+ 1 floats +loop 0 d>f f/ ;   create test 3e f, 1e f, 4e f, 1e f, 5e f, 9e f, test 6 fmean f. \ 3.83333333333333
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
#Fortran
Fortran
real, target, dimension(100) :: a = (/ (i, i=1, 100) /) real, dimension(5,20) :: b = reshape( a, (/ 5,20 /) ) real, pointer, dimension(:) :: p => a(2:1) ! pointer to zero-length array real :: mean, zmean, bmean real, dimension(20) :: colmeans real, dimension(5) :: rowmeans   mean = sum(a)/size(a) ! SUM of A's elements divided by SIZE of A mean = sum(a)/max(size(a),1) ! Same result, but safer code ! MAX of SIZE and 1 prevents divide by zero if SIZE == 0 (zero-length array)   zmean = sum(p)/max(size(p),1) ! Here the safety check pays off. Since P is a zero-length array, ! expression becomes "0 / MAX( 0, 1 ) -> 0 / 1 -> 0", rather than "0 / 0 -> NaN"   bmean = sum(b)/max(size(b),1) ! multidimensional SUM over multidimensional SIZE   rowmeans = sum(b,1)/max(size(b,2),1) ! SUM elements in each row (dimension 1) ! dividing by the length of the row, which is the number of columns (SIZE of dimension 2) colmeans = sum(b,2)/max(size(b,1),1) ! SUM elements in each column (dimension 2) ! dividing by the length of the column, which is the number of rows (SIZE of dimension 1)
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%)
#zkl
zkl
const N=20;   (" N average analytical (error)").println(); ("=== ========= ============ =========").println(); foreach n in ([1..N]){ a := avg(n); b := ana(n); "%3d  %9.4f  %12.4f (%6.2f%%)".fmt( n, a, b, ((a-b)/b*100)).println(); }   fcn f(n){ (0).random(n) }   fcn avg(n){ tests := 0d10_000; sum := 0; do(tests){ v:=(0).pump(n,List,T(Void,False)).copy(); while(1){ z := f(n); if(v[z]) break; v[z] = True; sum += 1; } } return(sum.toFloat() / tests); }   fcn fact(n) { (1).reduce(n,fcn(N,n){N*n},1.0) } //-->Float fcn ana(n){ n=n.toFloat(); (1).reduce(n,'wrap(sum,i){ sum+fact(n)/n.pow(i)/fact(n-i) },0.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
#Wren
Wren
import "/fmt" for Fmt   var sma = Fn.new { |period| var i = 0 var sum = 0 var storage = [] return Fn.new { |input| if (storage.count < period) { sum = sum + input storage.add(input) } sum = sum + input - storage[i] storage[i] = input i = (i+1) % period return sum/storage.count } }   var sma3 = sma.call(3) var sma5 = sma.call(5) System.print(" x sma3 sma5") for (x in [1, 2, 3, 4, 5, 5, 4, 3, 2, 1]) { Fmt.precision = 3 System.print("%(Fmt.f(5, x))  %(Fmt.f(5, sma3.call(x)))  %(Fmt.f(5, sma5.call(x)))") }
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.
#PL.2FI
PL/I
attractive: procedure options(main);  %replace MAX by 120; declare prime(1:MAX) bit(1);   sieve: procedure; declare (i, j, sqm) fixed; prime(1) = 0; do i=2 to MAX; prime(i) = '1'b; end;   sqm = sqrt(MAX); do i=2 to sqm; if prime(i) then do j=i*2 to MAX by i; prime(j) = '0'b; end; end; end sieve;   factors: procedure(nn) returns(fixed); declare (f, i, n, nn) fixed; n = nn; f = 0; do i=2 to n; if prime(i) then do while(mod(n,i) = 0); f = f+1; n = n/i; end; end; return(f); end factors;   attractive: procedure(n) returns(bit(1)); declare n fixed; return(prime(factors(n))); end attractive;   declare (i, col) fixed; i = 0; col = 0; call sieve(); do i=2 to MAX; if attractive(i) then do; put edit(i) (F(4)); col = col + 1; if mod(col,18) = 0 then put skip; end; end; end attractive;
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
#Scala
Scala
import java.time.LocalTime import scala.compat.Platform   trait MeanAnglesComputation { import scala.math.{Pi, atan2, cos, sin}   def meanAngle(angles: List[Double], convFactor: Double = 180.0 / Pi) = { val sums = angles.foldLeft((.0, .0))((r, c) => { val rads = c / convFactor (r._1 + sin(rads), r._2 + cos(rads)) }) val result = atan2(sums._1, sums._2) (result + (if (result.signum == -1) 2 * Pi else 0.0)) * convFactor } }   object MeanBatTime extends App with MeanAnglesComputation { val dayInSeconds = 60 * 60 * 24   def times = batTimes.map(t => afterMidnight(t).toDouble)   def afterMidnight(twentyFourHourTime: String) = { val t = LocalTime.parse(twentyFourHourTime) (if (t.isBefore(LocalTime.NOON)) dayInSeconds else 0) + LocalTime.parse(twentyFourHourTime).toSecondOfDay }   def batTimes = List("23:00:17", "23:40:20", "00:12:45", "00:17:19") assert(LocalTime.MIN.plusSeconds(meanAngle(times, dayInSeconds).round).toString == "23:47:40") println(s"Successfully completed without errors. [total ${Platform.currentTime - executionStart} ms]") }
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
#Scheme
Scheme
  (import (srfi 1 lists)) ;; use 'fold' from library   (define (average l) (/ (fold + 0 l) (length l)))   (define pi 3.14159265358979323846264338327950288419716939937510582097)   (define (radians a) (* pi 1/180 a))   (define (degrees a) (* 180 (/ 1 pi) a))   (define (mean-angle angles) (let* ((angles (map radians angles)) (cosines (map cos angles)) (sines (map sin angles))) (degrees (atan (average sines) (average cosines)))))   (for-each (lambda (angles) (display "The mean angle of ") (display angles) (display " is ") (display (mean-angle angles)) (newline)) '((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
#K
K
  med:{a:x@<x; i:(#a)%2; :[(#a)!2; a@i; {(+/x)%#x} a@i,i-1]} v:10*6 _draw 0 v 5.961475 2.025856 7.262835 1.814272 2.281911 4.854716 med[v] 3.568313 med[1_ v] 2.281911  
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
#Kotlin
Kotlin
fun median(l: List<Double>) = l.sorted().let { (it[it.size / 2] + it[(it.size - 1) / 2]) / 2 }   fun main(args: Array<String>) { median(listOf(5.0, 3.0, 4.0)).let { println(it) } // 4 median(listOf(5.0, 4.0, 2.0, 3.0)).let { println(it) } // 3.5 median(listOf(3.0, 4.0, 1.0, -8.4, 7.2, 4.0, 1.0, 1.2)).let { println(it) } // 2.1 }
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
#MATLAB
MATLAB
function [A,G,H] = pythagoreanMeans(list)   A = mean(list); G = geomean(list); H = harmmean(list);   end
http://rosettacode.org/wiki/Babbage_problem
Babbage problem
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125. He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain. Task[edit] The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand. As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred. For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L]. Motivation The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
#Tcl
Tcl
for {set i 1} {![string match *269696 [expr $i*$i]]} {incr i} {} puts "$i squared is [expr $i*$i]"
http://rosettacode.org/wiki/Babbage_problem
Babbage problem
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125. He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain. Task[edit] The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand. As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred. For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L]. Motivation The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
#TI-83_BASIC
TI-83 BASIC
536→N
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
#Fantom
Fantom
  class Main { static Bool matchingBrackets (Str[] brackets) { Int opened := 0 Int i := 0 while (i < brackets.size) { if (brackets[i] == "[") opened += 1 else opened -= 1 if (opened < 0) return false i += 1 } return true }   public static Void main (Str[] args) { if (args.size == 1 && Int.fromStr(args[0], 10, false) != null) { n := Int.fromStr(args[0]) Str[] brackets := [,] 20.times { brackets = [,] // create a random set of brackets n.times { brackets.addAll (["[", "]"]) } n.times { brackets.swap(Int.random(0..<2*n), Int.random(0..<2*n)) } // report if matching or not if (matchingBrackets(brackets)) echo (brackets.join(" ") + " Matching") else echo (brackets.join(" ") + " not matching") } } } }  
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file
Append a record to the end of a text file
Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. This feature is most useful in the case of log files, where many jobs may be appending to the log file at the same time, or where care must be taken to avoid concurrently overwriting the same record from another job. Task Given a two record sample for a mythical "passwd" file: Write these records out in the typical system format. Ideally these records will have named fields of various types. Close the file, then reopen the file for append. Append a new record to the file and close the file again. Take appropriate care to avoid concurrently overwrites from another job. Open the file and demonstrate the new record has indeed written to the end. Source record field types and contents. account password UID GID fullname,office,extension,homephone,email directory shell string string int int struct(string,string,string,string,string) string string jsmith x 1001 1000 Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected] /home/jsmith /bin/bash jdoe x 1002 1000 Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected] /home/jdoe /bin/bash Record to be appended. account password UID GID fullname,office,extension,homephone,email directory shell string string int int struct(string,string,string,string,string) string string xyz x 1003 1000 X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected] /home/xyz /bin/bash Resulting file format: should mimic Linux's /etc/passwd file format with particular attention to the "," separator used in the GECOS field. But if the specific language has a particular or unique format of storing records in text file, then this format should be named and demonstrated with an additional example. Expected output: Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash Finally: Provide a summary of the language's "append record" capabilities in a table. eg. Append Capabilities. Data Representation IO Library Append Possible Automatic Append Multi-tasking Safe In core On disk C struct CSV text file glibc/stdio ☑ ☑ ☑ (Not all, eg NFS) Alternatively: If the language's appends can not guarantee its writes will always append, then note this restriction in the table. If possible, provide an actual code example (possibly using file/record locking) to guarantee correct concurrent appends.
#M2000_Interpreter
M2000 Interpreter
Module TestThis { Class passwd { account$, password$ UID, GID group GECOS { fullname$,office$,extension$,homephone$,email$ function Line$() { =format$("{0},{1} {2},{3},{4}", .fullname$,.office$,.extension$,.homephone$,.email$) } } directory$, shell$ Function Line$() { =format$("{0}:{1}:{2}:{3}:{4}:{5}:{6}",.account$,.password$, .UID, .GID, .GECOS.Line$(), .directory$, .shell$) } class: Module passwd { if match("SSNNSSSSSSS") then Read .account$, .password$ Read .UID, .GID For .GECOS { Read .fullname$,.office$,.extension$,.homephone$,.email$ } Read .directory$, .shell$ Else.If Match("S") then Dim a$(), b$() a$()=Piece$(letter$, ":") .account$<=a$(0) .password$<=a$(1) .UID<=Val(a$(2)) .GID<=Val(a$(3)) For .GECOS { b$()=Piece$(a$(4), ",") .fullname$<=b$(0) .office$<=Piece$(b$(1), " ")(0) .extension$<=Piece$(b$(1), " ")(1) .homephone$<=b$(2) .email$<=b$(3) } .directory$<=a$(5) .shell$<=a$(6) End if } } Flush Data PASSWD("jsmith", "x", 1001, 1000, "Joe Smith", "Room", "1007","(234)555-8917","(234)555-0077","[email protected]","/home/jsmith","/bin/bash") Data PASSWD("jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044:[email protected]:/home/jdoe") \\ we have to make the file if not exist before we use APPEND if not exist("passwd") then Open "passwd" for Output as #F Close #F end if Open "passwd" for wide append as #F While not empty read A Print #F, A.Line$() End While Close #F Ret=PASSWD("xyz","x",1003,1000,"X Yz", "Room", "1003", "(234)555-8913", "(234)555-0033", "[email protected]","/home/xyz","/bin/bash") Repeat Try ok { Open "passwd" for wide append exclusive as F Print #F, Ret.Line$() close #F }   Until Not (Error or Not ok) I=1 Document Ret$ Open "passwd" for wide input as #F While not Eof(#F) Line Input #F, record$ Ret$=Format$("{0}|{1}",Str$(I,"0000"),Record$)+{ } I++ End While Close #F ClipBoard Ret$ Report Ret$ } TestThis  
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file
Append a record to the end of a text file
Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. This feature is most useful in the case of log files, where many jobs may be appending to the log file at the same time, or where care must be taken to avoid concurrently overwriting the same record from another job. Task Given a two record sample for a mythical "passwd" file: Write these records out in the typical system format. Ideally these records will have named fields of various types. Close the file, then reopen the file for append. Append a new record to the file and close the file again. Take appropriate care to avoid concurrently overwrites from another job. Open the file and demonstrate the new record has indeed written to the end. Source record field types and contents. account password UID GID fullname,office,extension,homephone,email directory shell string string int int struct(string,string,string,string,string) string string jsmith x 1001 1000 Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected] /home/jsmith /bin/bash jdoe x 1002 1000 Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected] /home/jdoe /bin/bash Record to be appended. account password UID GID fullname,office,extension,homephone,email directory shell string string int int struct(string,string,string,string,string) string string xyz x 1003 1000 X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected] /home/xyz /bin/bash Resulting file format: should mimic Linux's /etc/passwd file format with particular attention to the "," separator used in the GECOS field. But if the specific language has a particular or unique format of storing records in text file, then this format should be named and demonstrated with an additional example. Expected output: Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash Finally: Provide a summary of the language's "append record" capabilities in a table. eg. Append Capabilities. Data Representation IO Library Append Possible Automatic Append Multi-tasking Safe In core On disk C struct CSV text file glibc/stdio ☑ ☑ ☑ (Not all, eg NFS) Alternatively: If the language's appends can not guarantee its writes will always append, then note this restriction in the table. If possible, provide an actual code example (possibly using file/record locking) to guarantee correct concurrent appends.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
data = <|"account" -> "xyz", "password" -> "x", "UID" -> 1003, "GID" -> 1000, "fullname" -> "X Yz", "office" -> "Room 1003", "extension" -> "(234)555-8913", "homephone" -> "(234)555-0033", "email" -> "[email protected]", "directory" -> "/home/xyz", "shell" -> "/bin/bash"|>; asString[data_] := StringRiffle[ ToString /@ Insert[data /@ {"account", "password", "UID", "GID", "directory", "shell"}, StringRiffle[ data /@ {"fullname", "office", "extension", "homephone", "email"}, ","], 5], ":"]; fname = FileNameJoin[{$TemporaryDirectory, "testfile"}]; str = OpenWrite[fname]; (* Use OpenAppend if file exists *) Close[str]; Print["Appended record: " <> asString[data]];
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
#Bracmat
Bracmat
new$hash:?myhash & (myhash..insert)$(title."Some title") & (myhash..insert)$(formula.a+b+x^7) & (myhash..insert)$(fruit.apples oranges kiwis) & (myhash..insert)$(meat.) & (myhash..insert)$(fruit.melons bananas) & out$(myhash..find)$fruit & (myhash..remove)$formula & (myhash..insert)$(formula.x^2+y^2) & out$(myhash..find)$formula;
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#GW-BASIC
GW-BASIC
10 C = -999 20 N = N + 1 30 GOSUB 60 40 IF T = 20 THEN END 50 GOTO 20 60 D = 0 70 FOR F = 1 TO INT(N/2) 80 IF N MOD F = 0 THEN D = D + 1 90 NEXT F 100 IF D > C THEN GOSUB 120 110 RETURN 120 C = D 130 T = T + 1 140 PRINT N 150 RETURN
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Haskell
Haskell
import Data.List (find, group) import Data.Maybe (fromJust)   firstPrimeFactor :: Int -> Int firstPrimeFactor n = head $ filter ((0 ==) . mod n) [2 .. n]   allPrimeFactors :: Int -> [Int] allPrimeFactors 1 = [] allPrimeFactors n = let first = firstPrimeFactor n in first : allPrimeFactors (n `div` first)   factorCount :: Int -> Int factorCount 1 = 1 factorCount n = product ((succ . length) <$> group (allPrimeFactors n))   divisorCount :: Int -> (Int, Int) divisorCount = (,) <*> factorCount   hcnNext :: (Int, Int) -> (Int, Int) hcnNext (num, factors) = fromJust $ find ((> factors) . snd) (divisorCount <$> [num ..])   hcnSequence :: [Int] hcnSequence = fst <$> iterate hcnNext (1, 1)   main :: IO () main = print $ take 20 hcnSequence
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.
#Run_BASIC
Run BASIC
DIM bucket(10) FOR i = 1 TO 10 : bucket(i) = int(RND(0)*100) : NEXT   a = display(" Display:") ' show original array a = flatten(a) ' flatten the array a = display(" Flatten:") ' show flattened array a = transfer(3,5) ' transfer some amount from 3 to 5 a = display(a;" from 3 to 5:") ' Show transfer array end   FUNCTION display(a$) print a$;" ";chr$(9); for i = 1 to 10 display = display + bucket(i) print bucket(i);chr$(9); next i print " Total:";display END FUNCTION   FUNCTION flatten(f) f1 = int((f / 10) + .5) for i = 1 to 10 bucket(i) = f1 f2 = f2 + f1 next i bucket(10) = bucket(10) + f - f2 END FUNCTION     FUNCTION transfer(a1,a2) transfer = int(rnd(0) * bucket(a1)) bucket(a1) = bucket(a1) - transfer bucket(a2) = bucket(a2) + transfer END FUNCTION
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.
#Rust
Rust
extern crate rand;   use std::sync::{Arc, Mutex}; use std::thread; use std::cmp; use std::time::Duration;   use rand::Rng; use rand::distributions::{IndependentSample, Range};   trait Buckets { fn equalize<R:Rng>(&mut self, rng: &mut R); fn randomize<R:Rng>(&mut self, rng: &mut R); fn print_state(&self); }   impl Buckets for [i32] { fn equalize<R:Rng>(&mut self, rng: &mut R) { let range = Range::new(0,self.len()-1); let src = range.ind_sample(rng); let dst = range.ind_sample(rng); if dst != src { let amount = cmp::min(((dst + src) / 2) as i32, self[src]); let multiplier = if amount >= 0 { -1 } else { 1 }; self[src] += amount * multiplier; self[dst] -= amount * multiplier; } } fn randomize<R:Rng>(&mut self, rng: &mut R) { let ind_range = Range::new(0,self.len()-1); let src = ind_range.ind_sample(rng); let dst = ind_range.ind_sample(rng); if dst != src { let amount = cmp::min(Range::new(0,20).ind_sample(rng), self[src]); self[src] -= amount; self[dst] += amount;   } } fn print_state(&self) { println!("{:?} = {}", self, self.iter().sum::<i32>()); } }   fn main() { let e_buckets = Arc::new(Mutex::new([10; 10])); let r_buckets = e_buckets.clone(); let p_buckets = e_buckets.clone();   thread::spawn(move || { let mut rng = rand::thread_rng(); loop { let mut buckets = e_buckets.lock().unwrap(); buckets.equalize(&mut rng); } }); thread::spawn(move || { let mut rng = rand::thread_rng(); loop { let mut buckets = r_buckets.lock().unwrap(); buckets.randomize(&mut rng); } });   let sleep_time = Duration::new(1,0); loop { { let buckets = p_buckets.lock().unwrap(); buckets.print_state(); } thread::sleep(sleep_time); } }
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.
#Phix
Phix
type int42(object i) return i=42 end type int42 i i = 41 -- type-check failure (desktop/Phix only)
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.
#PHP
PHP
<?php $a = 5 #...input or change $a here assert($a == 42) # when $a is not 42, take appropriate actions, # which is set by assert_options() ?>
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.
#Picat
Picat
go =>    %  % Test predicates  % S = "ablewasiereisawelba", assert("test1",$is_palindrome(S)), assert_failure("test2",$not is_palindrome(S)),   assert("test3",$member(1,1..10)), assert_failure("test4",$member(1,1..10)), % bad test nl,    %  % Test functions  % assert("test5",$2+2,4), assert_failure("test6",$2+2, 5),   assert("test7",$to_lowercase("PICAT"),"picat"), assert_failure("test8",$sort([3,2,1]),[1,3,2]), nl.   is_palindrome(S) => S == S.reverse().   % Test a predicate with call/1 assert(Name, A) => println(Name ++ ": " ++ cond(call(A), "ok", "not ok")). assert_failure(Name, A) => println(Name ++ ": " ++ cond(not call(A), "ok", "not ok")).   % Test a function with apply/1 assert(Name, A, Expected) => println(Name ++ ": " ++ cond(apply(A) == Expected, "ok", "not ok")). assert_failure(Name, A, Expected) => println(Name ++ ": " ++ cond(apply(A) != Expected , "ok", "not ok")).
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.
#Efene
Efene
square = fn (N) { N * N }   # list comprehension squares1 = fn (Numbers) { [square(N) for N in Numbers] }   # functional form squares2a = fn (Numbers) { lists.map(fn square:1, Numbers) }   # functional form with lambda squares2b = fn (Numbers) { lists.map(fn (N) { N * N }, Numbers) }   # no need for a function squares3 = fn (Numbers) { [N * N for N in Numbers] }   @public run = fn () { Numbers = [1, 3, 5, 7] io.format("squares1 : ~p~n", [squares1(Numbers)]) io.format("squares2a: ~p~n", [squares2a(Numbers)]) io.format("squares2b: ~p~n", [squares2b(Numbers)]) io.format("squares3 : ~p~n", [squares3(Numbers)]) }  
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
#PureBasic
PureBasic
Procedure mean(Array InArray(1))   Structure MyMean Value.i Cnt.i EndStructure   Protected i, max, found Protected NewList MyDatas.MyMean()   Repeat found=#False ForEach MyDatas() If InArray(i)=MyDatas()\Value MyDatas()\Cnt+1 found=#True Break EndIf Next If Not found AddElement(MyDatas()) MyDatas()\Value=InArray(i) MyDatas()\cnt+1 EndIf If MyDatas()\Cnt>max max=MyDatas()\Cnt EndIf i+1 Until i>ArraySize(InArray())   ForEach MyDatas() If MyDatas()\Cnt=max For i=1 To max Print(Str(MyDatas()\Value)+" ") Next EndIf Next EndProcedure
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
#FreeBASIC
FreeBASIC
#include"assoc.bas"   function get_dict_data_string( d as dicitem ) as string select case d.datatype case BOOL if d.value.bool then return "true" else return "false" case INTEG return str(d.value.integ) case STRNG return """"+d.value.strng+"""" case FLOAT return str(d.value.float) case BYYTE return str(d.value.byyte) case else return "DATATYPE ERROR" end select end function   sub print_keyval_pair( d as dicentry ) print using "{&} : {&}";get_dict_data_string( d.key ); get_dict_data_string(d.value)   end sub   for i as uinteger = 0 to ubound(Dictionary) print_keyval_pair(Dictionary(i)) next i
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]
#Vlang
Vlang
struct Filter { b []f64 a []f64 }   fn (f Filter) filter(inp []f64) []f64 { mut out := []f64{len: inp.len} s := 1.0 / f.a[0] for i in 0..inp.len { mut tmp := 0.0 mut b := f.b if i+1 < b.len { b = b[..i+1] } for j, bj in b { tmp += bj * inp[i-j] } mut a := f.a[1..] if i < a.len { a = a[..i] } for j, aj in a { tmp -= aj * out[i-j-1] } out[i] = tmp * s } return out }   //Constants for a Butterworth Filter (order 3, low pass) const bwf = Filter{ a: [f64(1.00000000), -2.77555756e-16, 3.33333333e-01, -1.85037171e-17], b: [f64(0.16666667), 0.5, 0.5, 0.16666667], }   const sig = [ f64(-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, ]   fn main() { for v in bwf.filter(sig) { println("${v:9.6}") } }
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]
#Wren
Wren
import "/fmt" for Fmt   var filter = Fn.new { |a, b, signal| var result = List.filled(signal.count, 0) for (i in 0...signal.count) { var tmp = 0 for (j in 0...b.count) { if (i - j < 0) continue tmp = tmp + b[j] * signal[i - j] } for (j in 1...a.count) { if (i - j < 0) continue tmp = tmp - a[j] * result[i - j] } tmp = tmp / a[0] result[i] = tmp } return result }   var a = [1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] var b = [0.16666667, 0.5, 0.5, 0.16666667]   var signal = [ -0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589 ]   var result = filter.call(a, b, signal) for (i in 0...result.count) { Fmt.write("$11.8f", result[i]) System.write(((i + 1) % 5 != 0) ? ", " : "\n") }
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#FreeBASIC
FreeBASIC
  ' FB 1.05.0 Win64   Function Mean(array() As Double) As Double Dim length As Integer = Ubound(array) - Lbound(array) + 1 If length = 0 Then Return 0.0/0.0 'NaN End If Dim As Double sum = 0.0 For i As Integer = LBound(array) To UBound(array) sum += array(i) Next Return sum/length End Function   Function IsNaN(number As Double) As Boolean Return Str(number) = "-1.#IND" ' NaN as a string in FB End Function   Dim As Integer n, i Dim As Double num Print "Sample input and output" Print Do Input "How many numbers are to be input ? : ", n Loop Until n > 0 Dim vector(1 To N) As Double Print For i = 1 to n Print " Number #"; i; " : "; Input "", vector(i) Next Print Print "Mean is"; Mean(vector()) Print Erase vector num = Mean(vector()) If IsNaN(num) Then Print "After clearing the vector, the mean is 'NaN'" End If Print Print "Press any key to quit the program" 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
#zkl
zkl
fcn SMA(P){ fcn(n,ns,P){ sz:=ns.append(n.toFloat()).len(); if(P>sz) return(0.0); if(P<sz) ns.del(0); ns.sum(0.0)/P; }.fp1(List.createLong(P+1),P) // pre-allocate a list of length P+1 }