task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Clean
Clean
square x = x * x   values :: {#Int} values = {x \\ x <- [1 .. 10]}
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
#Octave
Octave
function m = mode2(v) sv = sort(v); % build two vectors, vals and c, so that % c(i) holds how many times vals(i) appears i = 1; c = []; vals = []; while (i <= numel(v) ) tc = sum(sv==sv(i)); % it would be faster to count % them "by hand", since sv is sorted... c = [c, tc]; vals = [vals, sv(i)]; i += tc; endwhile % stack vals and c building a 2-rows matrix x x = cat(1,vals,c); % sort the second row (frequencies) into t (most frequent % first) and take the "original indices" i ... [t, i] = sort(x(2,:), "descend"); % ... so that we can use them to sort columns according % to frequencies nv = x(1,i); % at last, collect into m (the result) all the values % having the same bigger frequency r = t(1); i = 1; m = []; while ( t(i) == r ) m = [m, nv(i)]; i++; endwhile endfunction
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
#D
D
import std.stdio: writeln;   void main() { // the associative array auto aa = ["alice":2, "bob":97, "charlie":45];   // how to iterate key/value pairs: foreach (key, value; aa) writeln("1) Got key ", key, " with value ", value); writeln();   // how to iterate the keys: foreach (key, _; aa) writeln("2) Got key ", key); writeln();   // how to iterate the values: foreach (value; aa) writeln("3) Got value ", value); writeln();   // how to extract the values, lazy: foreach (value; aa.byValue()) writeln("4) Got value ", value); writeln();   // how to extract the keys, lazy: foreach (key; aa.byKey()) writeln("5) Got key ", key); writeln();   // how to extract all the keys: foreach (key; aa.keys) writeln("6) Got key ", key); writeln();   // how to extract all the values: foreach (value; aa.values) writeln("7) Got value ", value); }
http://rosettacode.org/wiki/Apply_a_digital_filter_(direct_form_II_transposed)
Apply a digital filter (direct form II transposed)
Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [1] Task Filter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667] The signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
b = {0.16666667, 0.5, 0.5, 0.16666667}; a = {1.00000000, -2.77555756*^-16, 3.33333333*^-01, -1.85037171*^-17}; 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}; RecurrenceFilter[{a, b}, signal]
http://rosettacode.org/wiki/Apply_a_digital_filter_(direct_form_II_transposed)
Apply a digital filter (direct form II transposed)
Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [1] Task Filter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667] The signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]
#MATLAB
MATLAB
  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]; a = [1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17]; b = [0.16666667, 0.5, 0.5, 0.16666667];   out = filter(b,a,signal)   figure subplot(1,2,1) stem(0:19, signal) xlabel('n') title('Original Signal')   subplot(1,2,2) stem(0:19, out) xlabel('n') title('Filtered Signal')  
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#Dyalect
Dyalect
func avg(args...) { var acc = .0 var len = 0 for x in args { len += 1 acc += x } acc / len }   avg(1, 2, 3, 4, 5, 6)
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
#E
E
def meanOrZero(numbers) { var count := 0 var sum := 0 for x in numbers { sum += x count += 1 } return sum / 1.max(count) }
http://rosettacode.org/wiki/Associative_array/Merging
Associative array/Merging
Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be: Key Value "name" "Rocket Skates" "price" 15.25 "color" "red" "year" 1974
#Tcl
Tcl
set dict1 [dict create name "Rocket Skates" price 12.75 color yellow] set dict2 [dict create price 15.25 color red year 1974] dict for {key val} [dict merge $dict1 $dict2] { puts "$key: $val" }
http://rosettacode.org/wiki/Associative_array/Merging
Associative array/Merging
Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be: Key Value "name" "Rocket Skates" "price" 15.25 "color" "red" "year" 1974
#VBA
VBA
  Private Type Associative Key As String Value As Variant End Type Sub Main_Array_Associative() Dim BaseArray(2) As Associative, UpdateArray(2) As Associative FillArrays BaseArray, UpdateArray ReDim Result(UBound(BaseArray)) As Associative MergeArray Result, BaseArray, UpdateArray PrintOut Result End Sub Private Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative) Dim i As Long, Respons As Long Res = Base For i = LBound(Update) To UBound(Update) If Exist(Respons, Base, Update(i).Key) Then Res(Respons).Value = Update(i).Value Else ReDim Preserve Res(UBound(Res) + 1) Res(UBound(Res)).Key = Update(i).Key Res(UBound(Res)).Value = Update(i).Value End If Next End Sub Private Function Exist(R As Long, B() As Associative, K As String) As Boolean Dim i As Long Do If B(i).Key = K Then Exist = True R = i End If i = i + 1 Loop While i <= UBound(B) And Not Exist End Function Private Sub FillArrays(B() As Associative, U() As Associative) B(0).Key = "name" B(0).Value = "Rocket Skates" B(1).Key = "price" B(1).Value = 12.75 B(2).Key = "color" B(2).Value = "yellow" U(0).Key = "price" U(0).Value = 15.25 U(1).Key = "color" U(1).Value = "red" U(2).Key = "year" U(2).Value = 1974 End Sub Private Sub PrintOut(A() As Associative) Dim i As Long Debug.Print "Key", "Value" For i = LBound(A) To UBound(A) Debug.Print A(i).Key, A(i).Value Next i Debug.Print "-----------------------------" End Sub
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%)
#Ruby
Ruby
class Integer def factorial self == 0 ? 1 : (1..self).inject(:*) end end   def rand_until_rep(n) rands = {} loop do r = rand(1..n) return rands.size if rands[r] rands[r] = true end end   runs = 1_000_000   puts " N average exp. diff ", "=== ======== ======== ===========" (1..20).each do |n| sum_of_runs = runs.times.inject(0){|sum, _| sum += rand_until_rep(n)} avg = sum_of_runs / runs.to_f analytical = (1..n).inject(0){|sum, i| sum += (n.factorial / (n**i).to_f / (n-i).factorial)} puts "%3d  %8.4f  %8.4f (%8.4f%%)" % [n, avg, analytical, (avg/analytical - 1)*100] end
http://rosettacode.org/wiki/Average_loop_length
Average loop length
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence. Task Write a program or a script that estimates, for each N, the average length until the first such repetition. Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one. This problem comes from the end of Donald Knuth's Christmas tree lecture 2011. Example of expected output: N average analytical (error) === ========= ============ ========= 1 1.0000 1.0000 ( 0.00%) 2 1.4992 1.5000 ( 0.05%) 3 1.8784 1.8889 ( 0.56%) 4 2.2316 2.2188 ( 0.58%) 5 2.4982 2.5104 ( 0.49%) 6 2.7897 2.7747 ( 0.54%) 7 3.0153 3.0181 ( 0.09%) 8 3.2429 3.2450 ( 0.07%) 9 3.4536 3.4583 ( 0.14%) 10 3.6649 3.6602 ( 0.13%) 11 3.8091 3.8524 ( 1.12%) 12 3.9986 4.0361 ( 0.93%) 13 4.2074 4.2123 ( 0.12%) 14 4.3711 4.3820 ( 0.25%) 15 4.5275 4.5458 ( 0.40%) 16 4.6755 4.7043 ( 0.61%) 17 4.8877 4.8579 ( 0.61%) 18 4.9951 5.0071 ( 0.24%) 19 5.1312 5.1522 ( 0.41%) 20 5.2699 5.2936 ( 0.45%)
#Rust
Rust
extern crate rand;   use rand::{ThreadRng, thread_rng}; use rand::distributions::{IndependentSample, Range}; use std::collections::HashSet; use std::env; use std::process;   fn help() { println!("usage: average_loop_length <max_N> <trials>"); }   fn main() { let args: Vec<String> = env::args().collect(); let mut max_n: u32 = 20; let mut trials: u32 = 1000;   match args.len() { 1 => {} 3 => { max_n = args[1].parse::<u32>().unwrap(); trials = args[2].parse::<u32>().unwrap(); } _ => { help(); process::exit(0); } }   let mut rng = thread_rng();   println!(" N average analytical (error)"); println!("=== ========= ============ ========="); for n in 1..(max_n + 1) { let the_analytical = analytical(n); let the_empirical = empirical(n, trials, &mut rng); println!(" {:>2} {:3.4} {:3.4} ( {:>+1.2}%)", n, the_empirical, the_analytical, 100f64 * (the_empirical / the_analytical - 1f64)); } }   fn factorial(n: u32) -> f64 { (1..n + 1).fold(1f64, |p, n| p * n as f64) }   fn analytical(n: u32) -> f64 { let sum: f64 = (1..(n + 1)) .map(|i| factorial(n) / (n as f64).powi(i as i32) / factorial(n - i)) .fold(0f64, |a, v| a + v); sum }   fn empirical(n: u32, trials: u32, rng: &mut ThreadRng) -> f64 { let sum: f64 = (0..trials) .map(|_t| { let mut item = 1u32; let mut seen = HashSet::new(); let range = Range::new(1u32, n + 1);   for step in 0..n { if seen.contains(&item) { return step as f64; } seen.insert(item); item = range.ind_sample(rng); } n as f64 }) .fold(0f64, |a, v| a + v); sum / trials as f64 }      
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
#Smalltalk
Smalltalk
Object subclass: MovingAverage [ |valueCollection period collectedNumber sum| MovingAverage class >> newWithPeriod: thePeriod [ |r| r := super basicNew. ^ r initWithPeriod: thePeriod ] initWithPeriod: thePeriod [ valueCollection := OrderedCollection new: thePeriod. period := thePeriod. collectedNumber := 0. sum := 0 ] sma [ collectedNumber < period ifTrue: [ ^ sum / collectedNumber ] ifFalse: [ ^ sum / period ] ] add: value [ collectedNumber < period ifTrue: [ sum := sum + value. valueCollection add: value. collectedNumber := collectedNumber + 1. ] ifFalse: [ sum := sum - (valueCollection removeFirst). sum := sum + value. valueCollection add: value ]. ^ self sma ] ].
http://rosettacode.org/wiki/Attractive_numbers
Attractive numbers
A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show sequence items up to   120. Reference   The OEIS entry:   A063989: Numbers with a prime number of prime divisors.
#Lua
Lua
-- Returns true if x is prime, and false otherwise function isPrime (x) if x < 2 then return false end if x < 4 then return true end if x % 2 == 0 then return false end for d = 3, math.sqrt(x), 2 do if x % d == 0 then return false end end return true end   -- Compute the prime factors of n function factors (n) local facList, divisor, count = {}, 1 if n < 2 then return facList end while not isPrime(n) do while not isPrime(divisor) do divisor = divisor + 1 end count = 0 while n % divisor == 0 do n = n / divisor table.insert(facList, divisor) end divisor = divisor + 1 if n == 1 then return facList end end table.insert(facList, n) return facList end   -- Main procedure for i = 1, 120 do if isPrime(#factors(i)) then io.write(i .. "\t") end end
http://rosettacode.org/wiki/Averages/Mean_time_of_day
Averages/Mean time of day
Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ideas of Averages/Mean angle compute and show the average time of the nocturnal activity to an accuracy of one second of time. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#PHP
PHP
  <?php function time2ang($tim) { if (!is_string($tim)) return $tim; $parts = explode(':',$tim); if (count($parts)!=3) return $tim; $sec = ($parts[0]*3600)+($parts[1]*60)+$parts[2]; $ang = 360.0 * ($sec/86400.0); return $ang; } function ang2time($ang) { if (!is_numeric($ang)) return $ang; $sec = 86400.0 * $ang / 360.0; $parts = array(floor($sec/3600),floor(($sec % 3600)/60),$sec % 60); $tim = sprintf('%02d:%02d:%02d',$parts[0],$parts[1],$parts[2]); return $tim; } function meanang($ang) { if (!is_array($ang)) return $ang; $sins = 0.0; $coss = 0.0; foreach($ang as $a) { $sins += sin(deg2rad($a)); $coss += cos(deg2rad($a)); } $avgsin = $sins / (0.0+count($ang)); $avgcos = $coss / (0.0+count($ang)); $avgang = rad2deg(atan2($avgsin,$avgcos)); while ($avgang < 0.0) $avgang += 360.0; return $avgang; } $bats = array('23:00:17','23:40:20','00:12:45','00:17:19'); $angs = array(); foreach ($bats as $t) $angs[] = time2ang($t); $ma = meanang($angs); $result = ang2time($ma); print "The mean time of day is $result (angle $ma).\n"; ?>  
http://rosettacode.org/wiki/AVL_tree
AVL tree
This page uses content from Wikipedia. The original article was at AVL tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In computer science, an AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; at no time do they differ by more than one because rebalancing is done ensure this is the case. Lookup, insertion, and deletion all take O(log n) time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations. Note the tree of nodes comprise a set, so duplicate node keys are not allowed. AVL trees are often compared with red-black trees because they support the same set of operations and because red-black trees also take O(log n) time for the basic operations. Because AVL trees are more rigidly balanced, they are faster than red-black trees for lookup-intensive applications. Similar to red-black trees, AVL trees are height-balanced, but in general not weight-balanced nor μ-balanced; that is, sibling nodes can have hugely differing numbers of descendants. Task Implement an AVL tree in the language of choice, and provide at least basic operations.
#Scheme
Scheme
(cond-expand (r7rs) (chicken (import r7rs)))   (define-library (avl-trees)   ;; ;; This library implements ‘persistent’ (that is, ‘immutable’) AVL ;; trees for R7RS Scheme. ;; ;; Included are generators of the key-data pairs in a tree. Because ;; the trees are persistent (‘immutable’), these generators are safe ;; from alterations of the tree. ;; ;; References: ;; ;; * Niklaus Wirth, 1976. Algorithms + Data Structures = ;; Programs. Prentice-Hall, Englewood Cliffs, New Jersey. ;; ;; * Niklaus Wirth, 2004. Algorithms and Data Structures. Updated ;; by Fyodor Tkachov, 2014. ;; ;; Note that the references do not discuss persistent ;; implementations. It seems worthwhile to compare the methods of ;; implementation. ;;   (export avl) (export alist->avl) (export avl->alist) (export avl?) (export avl-empty?) (export avl-size) (export avl-insert) (export avl-delete) (export avl-delete-values) (export avl-has-key?) (export avl-search) (export avl-search-values) (export avl-make-generator) (export avl-pretty-print) (export avl-check-avl-condition) (export avl-check-usage)   (import (scheme base)) (import (scheme case-lambda)) (import (scheme process-context)) (import (scheme write))   (cond-expand (chicken (import (only (chicken base) define-record-printer)) (import (only (chicken format) format))) ; For debugging. (else))   (begin   ;; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;; ;; Tools for making generators. These use call/cc and so might be ;; inefficient in your Scheme. I am using CHICKEN, in which ;; call/cc is not so inefficient. ;; ;; Often I have made &fail a unique object rather than #f, but in ;; this case #f will suffice. ;;   (define &fail #f)   (define *suspend* (make-parameter (lambda (x) x)))   (define (suspend v) ((*suspend*) v))   (define (fail-forever) (let loop () (suspend &fail) (loop)))   (define (make-generator-procedure thunk) ;; Make a suspendable procedure that takes no arguments. The ;; result is a simple generator of values. (This can be ;; elaborated upon for generators to take values on resumption, ;; in the manner of Icon co-expressions.) (define (next-run return) (define (my-suspend v) (set! return (call/cc (lambda (resumption-point) (set! next-run resumption-point) (return v))))) (parameterize ((*suspend* my-suspend)) (suspend (thunk)) (fail-forever))) (lambda () (call/cc next-run)))   ;; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -   (define-syntax avl-check-usage (syntax-rules () ((_ pred msg) (or pred (usage-error msg)))))   ;; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -   (define-record-type <avl> (%avl key data bal left right) avl? (key %key) (data %data) (bal %bal) (left %left) (right %right))   (cond-expand (chicken (define-record-printer (<avl> rt out) (display "#<avl " out) (display (%key rt) out) (display " " out) (display (%data rt) out) (display " " out) (display (%bal rt) out) (display " " out) (display (%left rt) out) (display " " out) (display (%right rt) out) (display ">" out))) (else))   ;; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -   (define avl (case-lambda (() (%avl #f #f #f #f #f)) ((pred<? . args) (alist->avl pred<? args))))   (define (avl-empty? tree) (avl-check-usage (avl? tree) "avl-empty? expects an AVL tree as argument") (not (%bal tree)))   (define (avl-size tree) (define (traverse p sz) (if (not p) sz (traverse (%left p) (traverse (%right p) (+ sz 1))))) (if (avl-empty? tree) 0 (traverse tree 0)))   (define (avl-has-key? pred<? tree key) (define (search p) (and p (let ((k (%key p))) (cond ((pred<? key k) (search (%left p))) ((pred<? k key) (search (%right p))) (else #t))))) (avl-check-usage (procedure? pred<?) "avl-has-key? expects a procedure as first argument") (and (not (avl-empty? tree)) (search tree)))   (define (avl-search pred<? tree key) ;; Return the data matching a key, or #f if the key is not ;; found. (Note that the data matching the key might be #f.) (define (search p) (and p (let ((k (%key p))) (cond ((pred<? key k) (search (%left p))) ((pred<? k key) (search (%right p))) (else (%data p)))))) (avl-check-usage (procedure? pred<?) "avl-search expects a procedure as first argument") (and (not (avl-empty? tree)) (search tree)))   (define (avl-search-values pred<? tree key) ;; Return two values: the data matching the key, or #f is the ;; key is not found; and a second value that is either #f or #t, ;; depending on whether the key is found. (define (search p) (if (not p) (values #f #f) (let ((k (%key p))) (cond ((pred<? key k) (search (%left p))) ((pred<? k key) (search (%right p))) (else (values (%data p) #t)))))) (avl-check-usage (procedure? pred<?) "avl-search-values expects a procedure as first argument") (if (avl-empty? tree) (values #f #f) (search tree)))   (define (alist->avl pred<? alst) ;; Go from association list to AVL tree. (avl-check-usage (procedure? pred<?) "alist->avl expects a procedure as first argument") (let loop ((tree (avl)) (lst alst)) (if (null? lst) tree (let ((head (car lst))) (loop (avl-insert pred<? tree (car head) (cdr head)) (cdr lst))))))   (define (avl->alist tree) ;; Go from AVL tree to association list. The output will be in ;; order. (define (traverse p lst) ;; Reverse in-order traversal of the tree, to produce an ;; in-order cons-list. (if (not p) lst (traverse (%left p) (cons (cons (%key p) (%data p)) (traverse (%right p) lst))))) (if (avl-empty? tree) '() (traverse tree '())))   (define (avl-insert pred<? tree key data)   (define (search p fix-balance?) (cond ((not p) ;; The key was not found. Make a new node and set ;; fix-balance? (values (%avl key data 0 #f #f) #t))   ((pred<? key (%key p)) ;; Continue searching. (let-values (((p1 fix-balance?) (search (%left p) fix-balance?))) (cond ((not fix-balance?) (let ((p^ (%avl (%key p) (%data p) (%bal p) p1 (%right p)))) (values p^ #f))) (else ;; A new node has been inserted on the left side. (case (%bal p) ((1) (let ((p^ (%avl (%key p) (%data p) 0 p1 (%right p)))) (values p^ #f))) ((0) (let ((p^ (%avl (%key p) (%data p) -1 p1 (%right p)))) (values p^ fix-balance?))) ((-1) ;; Rebalance. (case (%bal p1) ((-1) ;; A single LL rotation. (let* ((p^ (%avl (%key p) (%data p) 0 (%right p1) (%right p))) (p1^ (%avl (%key p1) (%data p1) 0 (%left p1) p^))) (values p1^ #f))) ((0 1) ;; A double LR rotation. (let* ((p2 (%right p1)) (bal2 (%bal p2)) (p^ (%avl (%key p) (%data p) (- (min bal2 0)) (%right p2) (%right p))) (p1^ (%avl (%key p1) (%data p1) (- (max bal2 0)) (%left p1) (%left p2))) (p2^ (%avl (%key p2) (%data p2) 0 p1^ p^))) (values p2^ #f))) (else (internal-error)))) (else (internal-error)))))))   ((pred<? (%key p) key) ;; Continue searching. (let-values (((p1 fix-balance?) (search (%right p) fix-balance?))) (cond ((not fix-balance?) (let ((p^ (%avl (%key p) (%data p) (%bal p) (%left p) p1))) (values p^ #f))) (else ;; A new node has been inserted on the right side. (case (%bal p) ((-1) (let ((p^ (%avl (%key p) (%data p) 0 (%left p) p1))) (values p^ #f))) ((0) (let ((p^ (%avl (%key p) (%data p) 1 (%left p) p1))) (values p^ fix-balance?))) ((1) ;; Rebalance. (case (%bal p1) ((1) ;; A single RR rotation. (let* ((p^ (%avl (%key p) (%data p) 0 (%left p) (%left p1))) (p1^ (%avl (%key p1) (%data p1) 0 p^ (%right p1)))) (values p1^ #f))) ((-1 0) ;; A double RL rotation. (let* ((p2 (%left p1)) (bal2 (%bal p2)) (p^ (%avl (%key p) (%data p) (- (max bal2 0)) (%left p) (%left p2))) (p1^ (%avl (%key p1) (%data p1) (- (min bal2 0)) (%right p2) (%right p1))) (p2^ (%avl (%key p2) (%data p2) 0 p^ p1^))) (values p2^ #f))) (else (internal-error)))) (else (internal-error)))))))   (else ;; The key was found; p is an existing node. (values (%avl key data (%bal p) (%left p) (%right p)) #f))))   (avl-check-usage (procedure? pred<?) "avl-insert expects a procedure as first argument") (if (avl-empty? tree) (%avl key data 0 #f #f) (let-values (((p fix-balance?) (search tree #f))) p)))   (define (avl-delete pred<? tree key) ;; If one is not interested in whether the key was in the tree, ;; then throw away that information. (let-values (((tree had-key?) (avl-delete-values pred<? tree key))) tree))   (define (balance-for-shrunken-left p) ;; Returns two values: a new p and a new fix-balance? (case (%bal p) ((-1) (values (%avl (%key p) (%data p) 0 (%left p) (%right p)) #t)) ((0) (values (%avl (%key p) (%data p) 1 (%left p) (%right p)) #f)) ((1) ;; Rebalance. (let* ((p1 (%right p)) (bal1 (%bal p1))) (case bal1 ((0) ;; A single RR rotation. (let* ((p^ (%avl (%key p) (%data p) 1 (%left p) (%left p1))) (p1^ (%avl (%key p1) (%data p1) -1 p^ (%right p1)))) (values p1^ #f))) ((1) ;; A single RR rotation. (let* ((p^ (%avl (%key p) (%data p) 0 (%left p) (%left p1))) (p1^ (%avl (%key p1) (%data p1) 0 p^ (%right p1)))) (values p1^ #t))) ((-1) ;; A double RL rotation. (let* ((p2 (%left p1)) (bal2 (%bal p2)) (p^ (%avl (%key p) (%data p) (- (max bal2 0)) (%left p) (%left p2))) (p1^ (%avl (%key p1) (%data p1) (- (min bal2 0)) (%right p2) (%right p1))) (p2^ (%avl (%key p2) (%data p2) 0 p^ p1^))) (values p2^ #t))) (else (internal-error))))) (else (internal-error))))   (define (balance-for-shrunken-right p) ;; Returns two values: a new p and a new fix-balance? (case (%bal p) ((1) (values (%avl (%key p) (%data p) 0 (%left p) (%right p)) #t)) ((0) (values (%avl (%key p) (%data p) -1 (%left p) (%right p)) #f)) ((-1) ;; Rebalance. (let* ((p1 (%left p)) (bal1 (%bal p1))) (case bal1 ((0) ;; A single LL rotation. (let* ((p^ (%avl (%key p) (%data p) -1 (%right p1) (%right p))) (p1^ (%avl (%key p1) (%data p1) 1 (%left p1) p^))) (values p1^ #f))) ((-1) ;; A single LL rotation. (let* ((p^ (%avl (%key p) (%data p) 0 (%right p1) (%right p))) (p1^ (%avl (%key p1) (%data p1) 0 (%left p1) p^))) (values p1^ #t))) ((1) ;; A double LR rotation. (let* ((p2 (%right p1)) (bal2 (%bal p2)) (p^ (%avl (%key p) (%data p) (- (min bal2 0)) (%right p2) (%right p))) (p1^ (%avl (%key p1) (%data p1) (- (max bal2 0)) (%left p1) (%left p2))) (p2^ (%avl (%key p2) (%data p2) 0 p1^ p^))) (values p2^ #t))) (else (internal-error))))) (else (internal-error))))   (define (avl-delete-values pred<? tree key)   (define-syntax balance-L (syntax-rules () ((_ p fix-balance?) (if fix-balance? (balance-for-shrunken-left p) (values p #f)))))   (define-syntax balance-R (syntax-rules () ((_ p fix-balance?) (if fix-balance? (balance-for-shrunken-right p) (values p #f)))))   (define (del r fix-balance?) ;; Returns a new r, a new fix-balance?, and key and data to be ;; ‘moved up the tree’. (if (%right r) (let*-values (((q fix-balance? key^ data^) (del (%right r) fix-balance?)) ((r fix-balance?) (balance-R (%avl (%key r) (%data r) (%bal r) (%left r) q) fix-balance?))) (values r fix-balance? key^ data^)) (values (%left r) #t (%key r) (%data r))))   (define (search p fix-balance?) ;; Return three values: a new p, a new fix-balance, and ;; whether the key was found. (cond ((not p) (values #f #f #f)) ((pred<? key (%key p)) ;; Recursive search down the left branch. (let*-values (((q fix-balance? found?) (search (%left p) fix-balance?)) ((p fix-balance?) (balance-L (%avl (%key p) (%data p) (%bal p) q (%right p)) fix-balance?))) (values p fix-balance? found?))) ((pred<? (%key p) key) ;; Recursive search down the right branch. (let*-values (((q fix-balance? found?) (search (%right p) fix-balance?)) ((p fix-balance?) (balance-R (%avl (%key p) (%data p) (%bal p) (%left p) q) fix-balance?))) (values p fix-balance? found?))) ((not (%right p)) ;; Delete p, replace it with its left branch, then ;; rebalance. (values (%left p) #t #t)) ((not (%left p)) ;; Delete p, replace it with its right branch, then ;; rebalance. (values (%right p) #t #t)) (else ;; Delete p, but it has both left and right branches, ;; and therefore may have complicated branch structure. (let*-values (((q fix-balance? key^ data^) (del (%left p) fix-balance?)) ((p fix-balance?) (balance-L (%avl key^ data^ (%bal p) q (%right p)) fix-balance?))) (values p fix-balance? #t)))))   (avl-check-usage (procedure? pred<?) "avl-delete-values expects a procedure as first argument") (if (avl-empty? tree) (values tree #f) (let-values (((tree fix-balance? found?) (search tree #f))) (if found? (values (or tree (avl)) #t) (values tree #f)))))   (define avl-make-generator (case-lambda ((tree) (avl-make-generator tree 1)) ((tree direction) (if (negative? direction) (make-generator-procedure (lambda () (define (traverse p) (unless (or (not p) (avl-empty? p)) (traverse (%right p)) (suspend (cons (%key p) (%data p))) (traverse (%left p))) &fail) (traverse tree))) (make-generator-procedure (lambda () (define (traverse p) (unless (or (not p) (avl-empty? p)) (traverse (%left p)) (suspend (cons (%key p) (%data p))) (traverse (%right p))) &fail) (traverse tree)))))))   (define avl-pretty-print (case-lambda ((tree) (avl-pretty-print tree (current-output-port))) ((tree port) (avl-pretty-print tree port (lambda (port key data) (display "(" port) (write key port) (display ", " port) (write data port) (display ")" port)))) ((tree port key-data-printer) ;; In-order traversal, so the printing is done in ;; order. Reflect the display diagonally to get the more ;; usual orientation of left-to-right, top-to-bottom. (define (pad depth) (unless (zero? depth) (display " " port) (pad (- depth 1)))) (define (traverse p depth) (when p (traverse (%left p) (+ depth 1)) (pad depth) (key-data-printer port (%key p) (%data p)) (display "\t\tdepth = " port) (display depth port) (display " bal = " port) (display (%bal p) port) (display "\n" port) (traverse (%right p) (+ depth 1)))) (unless (avl-empty? tree) (traverse (%left tree) 1) (key-data-printer port (%key tree) (%data tree)) (display "\t\tdepth = 0 bal = " port) (display (%bal tree) port) (display "\n" port) (traverse (%right tree) 1)))))   (define (avl-check-avl-condition tree) ;; Check that the AVL condition is satisfied. (define (check-heights height-L height-R) (when (<= 2 (abs (- height-L height-R))) (display "*** AVL condition violated ***" (current-error-port)) (internal-error))) (define (get-heights p) (if (not p) (values 0 0) (let-values (((height-LL height-LR) (get-heights (%left p))) ((height-RL height-RR) (get-heights (%right p)))) (check-heights height-LL height-LR) (check-heights height-RL height-RR) (values (+ height-LL height-LR) (+ height-RL height-RR))))) (unless (avl-empty? tree) (let-values (((height-L height-R) (get-heights tree))) (check-heights height-L height-R))))   (define (internal-error) (display "internal error\n" (current-error-port)) (emergency-exit 123))   (define (usage-error msg) (display "Procedure usage error:\n" (current-error-port)) (display " " (current-error-port)) (display msg (current-error-port)) (newline (current-error-port)) (exit 1))   )) ;; end library (avl-trees)     (cond-expand (DEMONSTRATION (begin (import (avl-trees)) (import (scheme base)) (import (scheme time)) (import (scheme process-context)) (import (scheme write))   (cond-expand (chicken (import (only (chicken format) format))) ; For debugging. (else))   (define 2**64 (expt 2 64))   (define seed (truncate-remainder (exact (current-second)) 2**64)) (define random ;; A really slow (but presumably highly portable) ;; implementation of Donald Knuth’s linear congruential random ;; number generator, returning a rational number in [0,1). See ;; https://en.wikipedia.org/w/index.php?title=Linear_congruential_generator&oldid=1076681286 (let ((a 6364136223846793005) (c 1442695040888963407)) (lambda () (let ((result (/ seed 2**64))) (set! seed (truncate-remainder (+ (* a seed) c) 2**64)) result)))) (do ((i 0 (+ i 1))) ((= i 10)) (random))   (define (fisher-yates-shuffle keys) (let ((n (vector-length keys))) (do ((i 1 (+ i 1))) ((= i n)) (let* ((randnum (random)) (j (+ i (floor (* randnum (- n i))))) (xi (vector-ref keys i)) (xj (vector-ref keys j))) (vector-set! keys i xj) (vector-set! keys j xi)))))   (define (display-key-data key data) (display "(") (write key) (display ", ") (write data) (display ")"))   (define (display-tree-contents tree) (do ((p (avl->alist tree) (cdr p))) ((null? p)) (display-key-data (caar p) (cdar p)) (newline)))   (define (error-stop) (display "*** ERROR STOP ***\n" (current-error-port)) (emergency-exit 1))   (define n 20) (define keys (make-vector (+ n 1))) (do ((i 0 (+ i 1))) ((= i n)) ;; To keep things more like Fortran, do not use index zero. (vector-set! keys (+ i 1) (+ i 1)))   (fisher-yates-shuffle keys)   ;; Insert key-data pairs in the shuffled order. (define tree (avl)) (avl-check-avl-condition tree) (do ((i 1 (+ i 1))) ((= i (+ n 1))) (let ((ix (vector-ref keys i))) (set! tree (avl-insert < tree ix (inexact ix))) (avl-check-avl-condition tree) (do ((j 1 (+ j 1))) ((= j (+ n 1))) (let*-values (((k) (vector-ref keys j)) ((has-key?) (avl-has-key? < tree k)) ((data) (avl-search < tree k)) ((data^ has-key?^) (avl-search-values < tree k))) (unless (exact? k) (error-stop)) (if (<= j i) (unless (and has-key? data data^ has-key?^ (inexact? data) (= data k) (inexact? data^) (= data^ k)) (error-stop)) (when (or has-key? data data^ has-key?^) (error-stop)))))))   (display "----------------------------------------------------------------------\n") (display "keys = ") (write (cdr (vector->list keys))) (newline) (display "----------------------------------------------------------------------\n") (avl-pretty-print tree) (display "----------------------------------------------------------------------\n") (display "tree size = ") (display (avl-size tree)) (newline) (display-tree-contents tree) (display "----------------------------------------------------------------------\n")   ;; ;; Reshuffle the keys, and change the data from inexact numbers ;; to strings. ;;   (fisher-yates-shuffle keys)   (do ((i 1 (+ i 1))) ((= i (+ n 1))) (let ((ix (vector-ref keys i))) (set! tree (avl-insert < tree ix (number->string ix))) (avl-check-avl-condition tree)))   (avl-pretty-print tree) (display "----------------------------------------------------------------------\n") (display "tree size = ") (display (avl-size tree)) (newline) (display-tree-contents tree) (display "----------------------------------------------------------------------\n")   ;; ;; Reshuffle the keys, and delete the contents of the tree, but ;; also keep the original tree by saving it in a variable. Check ;; persistence of the tree. ;;   (fisher-yates-shuffle keys)   (define saved-tree tree)   (do ((i 1 (+ i 1))) ((= i (+ n 1))) (let ((ix (vector-ref keys i))) (set! tree (avl-delete < tree ix)) (avl-check-avl-condition tree) (unless (= (avl-size tree) (- n i)) (error-stop)) ;; Try deleting a second time. (set! tree (avl-delete < tree ix)) (avl-check-avl-condition tree) (unless (= (avl-size tree) (- n i)) (error-stop)) (do ((j 1 (+ j 1))) ((= j (+ n 1))) (let ((jx (vector-ref keys j))) (unless (eq? (avl-has-key? < tree jx) (< i j)) (error-stop)) (let ((data (avl-search < tree jx))) (unless (eq? (not (not data)) (< i j)) (error-stop)) (unless (or (not data) (= (string->number data) jx)) (error-stop))) (let-values (((data found?) (avl-search-values < tree jx))) (unless (eq? found? (< i j)) (error-stop)) (unless (or (and (not data) (<= j i)) (and data (= (string->number data) jx))) (error-stop))))))) (do ((i 1 (+ i 1))) ((= i (+ n 1))) ;; Is save-tree the persistent value of the tree we just ;; deleted? (let ((ix (vector-ref keys i))) (unless (equal? (avl-search < saved-tree ix) (number->string ix)) (error-stop))))   (display "forwards generator:\n") (let ((gen (avl-make-generator saved-tree))) (do ((pair (gen) (gen))) ((not pair)) (display-key-data (car pair) (cdr pair)) (newline)))   (display "----------------------------------------------------------------------\n")   (display "backwards generator:\n") (let ((gen (avl-make-generator saved-tree -1))) (do ((pair (gen) (gen))) ((not pair)) (display-key-data (car pair) (cdr pair)) (newline)))   (display "----------------------------------------------------------------------\n")   )) (else))
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
#Phix
Phix
with javascript_semantics function MeanAngle(sequence angles) atom x = 0, y = 0 for i=1 to length(angles) do atom ai_rad = angles[i]*PI/180 x += cos(ai_rad) y += sin(ai_rad) end for if abs(x)<1e-16 then return "not meaningful" end if return sprintf("%g",round(atan2(y,x)*180/PI,1e10)) end function constant AngleLists = {{350,10},{90,180,270,360},{10,20,30},{180},{0,180}} for i=1 to length(AngleLists) do sequence ai = AngleLists[i] printf(1,"%16V: Mean Angle is %s\n",{ai,MeanAngle(ai)}) end for
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
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Sub quicksort(a() As Double, first As Integer, last As Integer) Dim As Integer length = last - first + 1 If length < 2 Then Return Dim pivot As Double = a(first + length\ 2) Dim lft As Integer = first Dim rgt As Integer = last While lft <= rgt While a(lft) < pivot lft +=1 Wend While a(rgt) > pivot rgt -= 1 Wend If lft <= rgt Then Swap a(lft), a(rgt) lft += 1 rgt -= 1 End If Wend quicksort(a(), first, rgt) quicksort(a(), lft, last) End Sub   Function median(a() As Double) As Double Dim lb As Integer = LBound(a) Dim ub As Integer = UBound(a) Dim length As Integer = ub - lb + 1 If length = 0 Then Return 0.0/0.0 '' NaN If length = 1 Then Return a(ub) Dim mb As Integer = (lb + ub) \2 If length Mod 2 = 1 Then Return a(mb) Return (a(mb) + a(mb + 1))/2.0 End Function   Dim a(0 To 9) As Double = {4.4, 2.3, -1.7, 7.5, 6.6, 0.0, 1.9, 8.2, 9.3, 4.5} quicksort(a(), 0, 9) Print "Median for all 10 elements  : "; median(a()) ' now get rid of final element Dim b(0 To 8) As Double = {4.4, 2.3, -1.7, 7.5, 6.6, 0.0, 1.9, 8.2, 9.3} quicksort(b(), 0, 8) Print "Median for first 9 elements : "; median(b()) Print Print "Press any key to quit" Sleep
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
#Kotlin
Kotlin
import kotlin.math.round import kotlin.math.pow   fun Collection<Double>.geometricMean() = if (isEmpty()) Double.NaN else (reduce { n1, n2 -> n1 * n2 }).pow(1.0 / size)   fun Collection<Double>.harmonicMean() = if (isEmpty() || contains(0.0)) Double.NaN else size / fold(0.0) { n1, n2 -> n1 + 1.0 / n2 }   fun Double.toFixed(len: Int = 6) = round(this * 10.0.pow(len)) / 10.0.pow(len)   fun main() { val list = listOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0) val a = list.average() // arithmetic mean val g = list.geometricMean() val h = list.harmonicMean() println("A = $a G = ${g.toFixed()} H = ${h.toFixed()}") println("A >= G is ${a >= g}, G >= H is ${g >= h}") require(g in h..a) }
http://rosettacode.org/wiki/Balanced_ternary
Balanced ternary
Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0" Task Implement balanced ternary representation of integers with the following: Support arbitrarily large integers, both positive and negative; Provide ways to convert to and from text strings, using digits '+', '-' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5). Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type is balanced ternary). If your native integers can't support arbitrary length, overflows during conversion must be indicated. Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do not convert to native integers first. Make your implementation efficient, with a reasonable definition of "efficient" (and with a reasonable definition of "reasonable"). Test case With balanced ternaries a from string "+-0++0+", b from native integer -436, c "+-++-": write out a, b and c in decimal notation; calculate a × (b − c), write out the result in both ternary and decimal notations. Note: The pages generalised floating point addition and generalised floating point multiplication have code implementing arbitrary precision floating point balanced ternary.
#REXX
REXX
/*REXX program converts decimal ◄───► balanced ternary; it also performs arithmetic. */ numeric digits 10000 /*be able to handle gihugic numbers. */ Ao = '+-0++0+' ; Abt = Ao /* [↓] 2 literals used by subroutine*/ Bo = '-436' ; Bbt = d2bt(Bo); @ = "(decimal)" Co = '+-++-' ; Cbt = Co ; @@ = "balanced ternary =" call btShow '[a]', Abt call btShow '[b]', Bbt call btShow '[c]', Cbt say; $bt = btMul(Abt, btSub(Bbt, Cbt) ) call btShow '[a*(b-c)]', $bt exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ d2bt: procedure; parse arg x 1; x= x / 1; p= 0; $.= '-'; $.1= "+"; $.0= 0; #= do until x==0; _= (x // (3** (p+1) ) )  % 3**p if _== 2 then _= -1 else if _== -2 then _= 1 x= x - _ * (3**p); p= p + 1; #= $._ || # end /*until*/; return # /*──────────────────────────────────────────────────────────────────────────────────────*/ bt2d: procedure; parse arg x; r= reverse(x); $.= -1; $.0= 0; #= 0; _= '+'; $._= 1 do j=1 for length(x); _= substr(r, j, 1); #= # + $._ * 3 ** (j-1) end /*j*/; return # /*──────────────────────────────────────────────────────────────────────────────────────*/ btAdd: procedure; parse arg x,y; rx= reverse(x); ry= reverse(y); carry= 0 @.= 0; _= '-'; @._= -1; _= "+"; @._= 1; $.= '-'; $.0= 0; $.1= "+"; #= do j=1 for max( length(x), length(y) ) x_= substr(rx, j, 1); xn= @.x_ y_= substr(ry, j, 1); yn= @.y_ s= xn + yn + carry; carry= 0 if s== 2 then do; s=-1; carry= 1; end if s== 3 then do; s= 0; carry= 1; end if s==-2 then do; s= 1; carry=-1; end #= $.s || # end /*j*/ if carry\==0 then #= $.carry || #; return btNorm(#) /*──────────────────────────────────────────────────────────────────────────────────────*/ btMul: procedure; parse arg x 1 x1 2, y 1 y1 2; if x==0 | y==0 then return 0; S= 1; P=0 x= btNorm(x); y= btNorm(y); Lx= length(x); Ly= length(y) /*handle: 0-xxx values.*/ if x1=='-' then do; x= btNeg(x); S= -S; end /*positate the number. */ if y1=='-' then do; y= btNeg(y); S= -S; end /* " " " */ if Ly>Lx then parse value x y with y x /*optimize " " */ do until y==0 /*keep adding 'til done*/ P= btAdd(P, x ) /*multiple the hard way*/ y= btSub(y, '+') /*subtract 1 from Y.*/ end /*until*/ if S==-1 then P= btNeg(P); return P /*adjust the product's sign; return.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ btNeg: return translate( arg(1), '-+', "+-") /*negate bal_ternary #.*/ btNorm: _= strip(arg(1), 'L', 0); if _=='' then _=0; return _ /*normalize the number.*/ btSub: return btAdd( arg(1), btNeg( arg(2) ) ) /*subtract two BT args.*/ btShow: say center( arg(1), 9) right( arg(2), 20) @@ right( bt2d(arg(2)), 9) @; return
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.
#Scala
Scala
  object BabbageProblem { def main( args:Array[String] ): Unit = {   var x : Int = 524 // Sqrt of 269696 = 519.something   while( (x * x) % 1000000 != 269696 ){ if( x % 10 == 4 ) x = x + 2 else x = x + 8 }   println("The smallest positive integer whose square ends in 269696 = " + x ) } }  
http://rosettacode.org/wiki/Approximate_equality
Approximate equality
Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the difference in floating point calculations between different language implementations becomes significant. For example, a difference between 32 bit and 64 bit floating point calculations may appear by about the 8th significant digit in base 10 arithmetic. Task Create a function which returns true if two floating point numbers are approximately equal. The function should allow for differences in the magnitude of numbers, so that, for example, 100000000000000.01   may be approximately equal to   100000000000000.011, even though   100.01   is not approximately equal to   100.011. If the language has such a feature in its standard library, this may be used instead of a custom function. Show the function results with comparisons on the following pairs of values:     100000000000000.01,   100000000000000.011     (note: should return true)     100.01,   100.011                                                     (note: should return false)     10000000000000.001 / 10000.0,   1000000000.0000001000     0.001,   0.0010000001     0.000000000000000000000101,   0.0      sqrt(2) * sqrt(2),    2.0     -sqrt(2) * sqrt(2),   -2.0     3.14159265358979323846,   3.14159265358979324 Answers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.
#Raku
Raku
say 0.1 + 0.2 + 0.3 + 0.4 === 1.0000000000000000000000000000000000000000000000000000000000000000000000000; # True
http://rosettacode.org/wiki/Approximate_equality
Approximate equality
Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the difference in floating point calculations between different language implementations becomes significant. For example, a difference between 32 bit and 64 bit floating point calculations may appear by about the 8th significant digit in base 10 arithmetic. Task Create a function which returns true if two floating point numbers are approximately equal. The function should allow for differences in the magnitude of numbers, so that, for example, 100000000000000.01   may be approximately equal to   100000000000000.011, even though   100.01   is not approximately equal to   100.011. If the language has such a feature in its standard library, this may be used instead of a custom function. Show the function results with comparisons on the following pairs of values:     100000000000000.01,   100000000000000.011     (note: should return true)     100.01,   100.011                                                     (note: should return false)     10000000000000.001 / 10000.0,   1000000000.0000001000     0.001,   0.0010000001     0.000000000000000000000101,   0.0      sqrt(2) * sqrt(2),    2.0     -sqrt(2) * sqrt(2),   -2.0     3.14159265358979323846,   3.14159265358979324 Answers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.
#ReScript
ReScript
let approx_eq = (v1, v2, epsilon) => { abs_float (v1 -. v2) < epsilon }   let test = (a, b) => { let epsilon = 1e-18 Printf.printf("%g, %g => %b\n", a, b, approx_eq(a, b, epsilon)) }   { test(100000000000000.01, 100000000000000.011) test(100.01, 100.011) test(10000000000000.001 /. 10000.0, 1000000000.0000001000) test(0.001, 0.0010000001) test(0.000000000000000000000101, 0.0) test(sqrt(2.0) *. sqrt(2.0), 2.0) test(-. sqrt(2.0) *. sqrt(2.0), (-2.0)) test(3.14159265358979323846, 3.14159265358979324) }  
http://rosettacode.org/wiki/Approximate_equality
Approximate equality
Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the difference in floating point calculations between different language implementations becomes significant. For example, a difference between 32 bit and 64 bit floating point calculations may appear by about the 8th significant digit in base 10 arithmetic. Task Create a function which returns true if two floating point numbers are approximately equal. The function should allow for differences in the magnitude of numbers, so that, for example, 100000000000000.01   may be approximately equal to   100000000000000.011, even though   100.01   is not approximately equal to   100.011. If the language has such a feature in its standard library, this may be used instead of a custom function. Show the function results with comparisons on the following pairs of values:     100000000000000.01,   100000000000000.011     (note: should return true)     100.01,   100.011                                                     (note: should return false)     10000000000000.001 / 10000.0,   1000000000.0000001000     0.001,   0.0010000001     0.000000000000000000000101,   0.0      sqrt(2) * sqrt(2),    2.0     -sqrt(2) * sqrt(2),   -2.0     3.14159265358979323846,   3.14159265358979324 Answers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.
#REXX
REXX
/*REXX program mimics an "approximately equal to" for comparing floating point numbers*/ numeric digits 15 /*what other FP hardware normally uses.*/ @.= /*assign default for the @ array. */ parse arg @.1 /*obtain optional argument from the CL.*/ if @.1='' | @.1=="," then do; @.1= 100000000000000.01 100000000000000.011 @.2= 100.01 100.011 @.3= 10000000000000.001 / 10000 1000000000.0000001000 @.4= 0.001 0.0010000001 @.5= 0.00000000000000000000101 0.0 @.6= sqrt(2) * sqrt(2) 2.0 @.7= -sqrt(2) * sqrt(2) '-2.0' @.8= 3.14159265358979323846 3.14159265358979324 /* added ───► */ @.9= 100000000000000003.0 100000000000000004.0 end do j=1 while @.j\=='' /*process CL argument or the array #s. */ say say center(' processing pair ' j" ",71,'═') /*display a title for the pair of #s. */ parse value @.j with a b /*extract two values from a pair of #s.*/ say 'A=' a /*display the value of A to the term.*/ say 'B=' b /* " " " " B " " " */ say right('A approximately equal to B?', 65) word("false true", 1 + approxEQ(a,b) ) end /*j*/ /* [↑] right─justify text & true/false*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ approxEQ: procedure; parse arg x,y; return x=y /*floating point compare with 15 digits*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); numeric digits; h=d+6 numeric form; m.=9; parse value format(x,2,1,,0) 'E0' with g "E" _ .; g=g *.5'e'_ %2 do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; return g/1
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
#EchoLisp
EchoLisp
  (define (balance str) (for/fold (closed 0) ((par str)) #:break (< closed 0 ) => closed (+ closed (cond ((string=? par "[") 1) ((string=? par "]") -1) (else 0)))))   (define (task N) (define str (list->string (append (make-list N "[") (make-list N "]")))) (for ((i 10)) (set! str (list->string (shuffle (string->list str)))) (writeln (if (zero? (balance str)) '👍 '❌ ) str)))   (task 4)   ❌ "[]]][[][" ❌ "]][][[[]" ❌ "][[[]]][" 👍 "[][[[]]]" ❌ "]][[][][" ❌ "][][[[]]" 👍 "[][][[]]" ❌ "]][[][[]" ❌ "[[]]][[]" ❌ "[[][]]]["    
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.
#Go
Go
package main   import ( "bytes" "fmt" "io" "io/ioutil" "os" )   type pw struct { account, password string uid, gid uint gecos directory, shell string }   type gecos struct { fullname, office, extension, homephone, email string }   func (p *pw) encode(w io.Writer) (int, error) { return fmt.Fprintf(w, "%s:%s:%d:%d:%s,%s,%s,%s,%s:%s:%s\n", p.account, p.password, p.uid, p.gid, p.fullname, p.office, p.extension, p.homephone, p.email, p.directory, p.shell) }   // data cut and pasted from task description var p2 = []pw{ {"jsmith", "x", 1001, 1000, gecos{"Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "[email protected]"}, "/home/jsmith", "/bin/bash"}, {"jdoe", "x", 1002, 1000, gecos{"Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "[email protected]"}, "/home/jsmith", "/bin/bash"}, }   var pa = pw{"xyz", "x", 1003, 1000, gecos{"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "[email protected]"}, "/home/xyz", "/bin/bash"}   var expected = "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913," + "(234)555-0033,[email protected]:/home/xyz:/bin/bash"   const pfn = "mythical"   func main() { writeTwo() appendOneMore() checkResult() }   func writeTwo() { // overwrites any existing file f, err := os.Create(pfn) if err != nil { fmt.Println(err) return } defer func() { if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(cErr) } }() for _, p := range p2 { if _, err = p.encode(f); err != nil { fmt.Println(err) return } } }   func appendOneMore() { // file must already exist f, err := os.OpenFile(pfn, os.O_RDWR|os.O_APPEND, 0) if err != nil { fmt.Println(err) return } if _, err := pa.encode(f); err != nil { fmt.Println(err) } if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(cErr) } }   func checkResult() { // reads entire file then closes it b, err := ioutil.ReadFile(pfn) if err != nil { fmt.Println(err) return } if string(bytes.Split(b, []byte{'\n'})[2]) == expected { fmt.Println("append okay") } else { fmt.Println("it didn't work") } }
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
#AutoHotkey
AutoHotkey
associative_array := {key1: "value 1", "Key with spaces and non-alphanumeric characters !*+": 23} MsgBox % associative_array.key1 . "`n" associative_array["Key with spaces and non-alphanumeric characters !*+"]
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
#Common_Lisp
Common Lisp
(defun factors (n &aux (lows '()) (highs '())) (do ((limit (1+ (isqrt n))) (factor 1 (1+ factor))) ((= factor limit) (when (= n (* limit limit)) (push limit highs)) (remove-duplicates (nreconc lows highs))) (multiple-value-bind (quotient remainder) (floor n factor) (when (zerop remainder) (push factor lows) (push quotient highs)))))   (defun anti-prime () (format t "The first 20 anti-primes are :~%") (do ((dmax 0) (c 0) (i 0 (1+ i))) ((= c 20)) (setf facts (list-length (factors i))) (when (< dmax facts) (format t "~d " i) (setq dmax facts) (incf c))))
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.
#Oz
Oz
declare %% %% INIT %% NBuckets = 100 StartVal = 50 ExpectedSum = NBuckets * StartVal   %% Makes a tuple and calls Fun for every field fun {Make Label N Fun} R = {Tuple.make Label N} in for I in 1..N do R.I = {Fun} end R end   Buckets = {Make buckets NBuckets fun {$} {Cell.new StartVal} end} Locks = {Make locks NBuckets Lock.new} LockList = {Record.toList Locks}   %% %% DISPLAY %% proc {Display} Snapshot = {WithLocks LockList fun {$} {Record.map Buckets Cell.access} end } Sum = {Record.foldL Snapshot Number.'+' 0} in {Print Snapshot} {System.showInfo " sum: "#Sum} Sum = ExpectedSum %% assert end   %% Calls Fun with multiple locks locked and returns the result of Fun. fun {WithLocks Ls Fun} case Ls of L|Lr then lock L then {WithLocks Lr Fun} end [] nil then {Fun} end end   %% %% MANIPULATE %% proc {Smooth I J} Diff = @(Buckets.I) - @(Buckets.J) %% reading without lock: by design Amount = Diff div 4 in {Transfer I J Amount} end   proc {Roughen I J} Amount = @(Buckets.I) div 3 %% reading without lock: by design in {Transfer I J Amount} end   %% Atomically transfer an amount from From to To. %% Negative amounts are allowed; %% will never make a bucket negative. proc {Transfer From To Amount} if From \= To then %% lock in order (to avoid deadlocks) Smaller = {Min From To} Bigger = {Max From To} in lock Locks.Smaller then lock Locks.Bigger then FromBucket = Buckets.From ToBucket = Buckets.To NewFromValue = @FromBucket - Amount NewToValue = @ToBucket + Amount in if NewFromValue >= 0 andthen NewToValue >= 0 then FromBucket := NewFromValue ToBucket := NewToValue end end end end end   %% Returns a random bucket index. fun {Pick} {OS.rand} mod NBuckets + 1 end in %% %% START %% thread for do {Smooth {Pick} {Pick}} end end thread for do {Roughen {Pick} {Pick}} end end for do {Display} {Time.delay 50} 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.
#Liberty_BASIC
Liberty BASIC
  a=42 call assert a=42 print "passed"   a=41 call assert a=42 print "failed (we never get here)" end   sub assert cond if cond=0 then 'simulate error, mentioning "AssertionFailed" AssertionFailed(-1)=0 end if end sub  
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Lingo
Lingo
-- in a movie script on assert (ok, message) if not ok then if not voidP(message) then _player.alert(message) abort -- exits from current call stack, i.e. also from the caller function end if end   -- anywhere in the code on test x = 42 assert(x=42, "Assertion 'x=42' failed") put "this shows up" x = 23 assert(x=42, "Assertion 'x=42' failed") put "this will never show up" 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.
#Lisaac
Lisaac
? { n = 42 };
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Clio
Clio
[1 2 3 4] * 2 + 1 -> print
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.
#Clojure
Clojure
;; apply a named function, inc (map inc [1 2 3 4])
http://rosettacode.org/wiki/Averages/Mode
Averages/Mode
Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#ooRexx
ooRexx
  -- will work with just about any collection... call testMode .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1) call testMode .list~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11) call testMode .queue~of(30, 10, 20, 30, 40, 50, -100, 4.7, -11e2)   ::routine testMode use arg list say "list =" list~makearray~toString("l", ", ") say "mode =" mode(list) say   ::routine mode use arg list   -- this is a good application for a bag -- add all of the items to the bag collector = .bag~new collector~putAll(list) -- now get a list of unique items indexes = .set~new~~putall(collector) count = 0 -- this is used to keep track of the maximums -- now see how many of each element we ended up with loop index over indexes items = collector~allat(index) newCount = items~items if newCount > count then do mode = items[1] count = newCount end end   return mode  
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
#Dao
Dao
  dict = { 'def' => 1, 'abc' => 2 }   for( keyvalue in dict ) io.writeln( keyvalue ); for( key in dict.keys(); value in dict.values() ) io.writeln( key, value ) dict.iterate { [key, value] io.writeln( key, value ) }  
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Dart
Dart
  main(){ var fruits = { 'apples': 'red', 'oranges': 'orange', 'bananas': 'yellow', 'pears': 'green', 'plums': 'purple' };   print('Key Value pairs:'); fruits.forEach( (fruits, color) => print( '$fruits are $color' ) );   print('\nKeys only:'); fruits.keys.forEach( ( key ) => print( key ) );   print('\nValues only:'); fruits.values.forEach( ( value ) => print( value ) ); }  
http://rosettacode.org/wiki/Apply_a_digital_filter_(direct_form_II_transposed)
Apply a digital filter (direct form II transposed)
Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [1] Task Filter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667] The signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]
#Nim
Nim
  import strformat   func filter(a, b, signal: openArray[float]): seq[float] =   result.setLen(signal.len)   for i in 0..signal.high: var tmp = 0.0 for j in 0..min(i, b.high): tmp += b[j] * signal[i - j] for j in 1..min(i, a.high): tmp -= a[j] * result[i - j] tmp /= a[0] result[i] = tmp   #———————————————————————————————————————————————————————————————————————————————————————————————————   let a = [1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] let b = [0.16666667, 0.5, 0.5, 0.16666667]   let 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]   let result = filter(a, b, signal) for i in 0..result.high: stdout.write fmt"{result[i]: .8f}" stdout.write if (i + 1) mod 5 != 0: ", " else: "\n"
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]
#Objeck
Objeck
class DigitalFilter { function : Main(args : String[]) ~ Nil { 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); each(i : result) { System.IO.Console->Print(result[i])->Print(((i + 1) % 5 <> 0) ? ",\t" : "\n"); }; }   function : Filter(a : Float[], b : Float[], signal : Float[]) ~ Float[] { result := Float->New[signal->Size()];   each(i : signal) { tmp := 0.0;   each(j : b) { if(i-j >= 0) { tmp += b[j] * signal[i - j]; }; };   each(j : a) { if(i-j >= 0) { tmp -= a[j] * result[i - j]; }; };   tmp /= a[0]; result[i] := tmp; };   return result; } }
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
#EasyLang
EasyLang
func mean . f[] r . for i range len f[] s += f[i] . r = s / len f[] . f[] = [ 1 2 3 4 5 6 7 8 ] call mean f[] r print r
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
#EchoLisp
EchoLisp
  (lib 'math) (mean '(1 2 3 4)) ;; mean of a list → 2.5 (mean #(1 2 3 4)) ;; mean of a vector → 2.5   (lib 'sequences) (mean [1 3 .. 10]) ;; mean of a sequence → 5   ;; error handling (mean 'elvis) ⛔ error: mean : expected sequence : elvis (mean ()) 💣 error: mean : null is not an object (mean #()) 😐 warning: mean : zero-divide : empty-vector → 0 (mean [2 2 .. 2]) 😁 warning: mean : zero-divide : empty-sequence → 0  
http://rosettacode.org/wiki/Associative_array/Merging
Associative array/Merging
Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be: Key Value "name" "Rocket Skates" "price" 15.25 "color" "red" "year" 1974
#Wren
Wren
var mergeMaps = Fn.new { |m1, m2| var m3 = {} for (key in m1.keys) m3[key] = m1[key] for (key in m2.keys) m3[key] = m2[key] return m3 }   var base = { "name": "Rocket Skates" , "price": 12.75, "color": "yellow" } var update = { "price": 15.25, "color": "red", "year": 1974 } var merged = mergeMaps.call(base, update) System.print(merged)
http://rosettacode.org/wiki/Associative_array/Merging
Associative array/Merging
Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be: Key Value "name" "Rocket Skates" "price" 15.25 "color" "red" "year" 1974
#Vlang
Vlang
type Generic = int|string|f64 type Assoc = map[string]Generic   fn merge(base Assoc, update Assoc) Assoc { mut result := Assoc(map[string]Generic{}) for k, v in base { result[k] = v } for k, v in update { result[k] = v } return result }   fn main() { base := Assoc({"name": Generic("Rocket Skates"), "price": 12.75, "color": "yellow"}) update := Assoc({"price": Generic(15.25), "color": "red", "year": 1974}) result := merge(base, update) for k,v in result { println('$k: $v') } }
http://rosettacode.org/wiki/Associative_array/Merging
Associative array/Merging
Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be: Key Value "name" "Rocket Skates" "price" 15.25 "color" "red" "year" 1974
#Wren_2
Wren
var mergeMaps = Fn.new { |m1, m2| var m3 = {} for (key in m1.keys) m3[key] = m1[key] for (key in m2.keys) m3[key] = m2[key] return m3 }   var base = { "name": "Rocket Skates" , "price": 12.75, "color": "yellow" } var update = { "price": 15.25, "color": "red", "year": 1974 } var merged = mergeMaps.call(base, update) System.print(merged)
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%)
#Scala
Scala
  import scala.util.Random   object AverageLoopLength extends App {   val factorial: LazyList[Double] = 1 #:: factorial.zip(LazyList.from(1)).map(n => n._2 * factorial(n._2 - 1)) val results = for (n <- 1 to 20; avg = tested(n, 1000000); theory = expected(n) ) yield (n, avg, theory, (avg / theory - 1) * 100)   def expected(n: Int): Double = (for (i <- 1 to n) yield factorial(n) / Math.pow(n, i) / factorial(n - i)).sum   def tested(n: Int, times: Int): Double = (for (i <- 1 to times) yield trial(n)).sum / times   def trial(n: Int): Double = { var count = 0 var x = 1 var bits = 0   while ((bits & x) == 0) { count = count + 1 bits = bits | x x = 1 << Random.nextInt(n) } count }     println("n avg exp diff") println("------------------------------------") results foreach { n => { println(f"${n._1}%2d ${n._2}%2.6f ${n._3}%2.6f ${n._4}%2.3f%%") } }   }  
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
#Swift
Swift
struct SimpleMovingAverage { var period: Int var numbers = [Double]()   mutating func addNumber(_ n: Double) -> Double { numbers.append(n)   if numbers.count > period { numbers.removeFirst() }   guard !numbers.isEmpty else { return 0 }   return numbers.reduce(0, +) / Double(numbers.count) } }   for period in [3, 5] { print("Moving average with period \(period)")   var averager = SimpleMovingAverage(period: period)   for n in [1.0, 2, 3, 4, 5, 5, 4, 3, 2, 1] { print("n: \(n); average \(averager.addNumber(n))") } }
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.
#Maple
Maple
attractivenumbers := proc(n::posint) local an, i; an :=[]: for i from 1 to n do if isprime(NumberTheory:-NumberOfPrimeFactors(i)) then an := [op(an), i]: end if: end do: end proc: attractivenumbers(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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[AttractiveNumberQ] AttractiveNumberQ[n_Integer] := FactorInteger[n][[All, 2]] // Total // PrimeQ Reap[Do[If[AttractiveNumberQ[i], Sow[i]], {i, 120}]][[2, 1]]
http://rosettacode.org/wiki/Averages/Mean_time_of_day
Averages/Mean time of day
Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ideas of Averages/Mean angle compute and show the average time of the nocturnal activity to an accuracy of one second of time. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#PicoLisp
PicoLisp
(load "@lib/math.l")   (de meanTime (Lst) (let Tim (*/ (atan2 (sum '((S) (sin (*/ ($tim S) pi 43200))) Lst) (sum '((S) (cos (*/ ($tim S) pi 43200))) Lst) ) 43200 pi ) (tim$ (% (+ Tim 86400) 86400) T) ) )
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
#PL.2FI
PL/I
*process source attributes xref; avt: Proc options(main); /*-------------------------------------------------------------------- * 25.06.2014 Walter Pachl taken from REXX *-------------------------------------------------------------------*/ Dcl (addr,hbound,sin,cos,atan) Builtin; Dcl sysprint Print; Dcl times(4) Char(8) Init('23:00:17','23:40:20','00:12:45','00:17:19'); Dcl time Char(8); Dcl (alpha,x,y,ss,ww) Dec Float(18) Init(0); Dcl day Bin Fixed(31) Init(86400); Dcl pi Dec Float(18) Init(3.14159265358979323846); Dcl (i,h,m,s) bin Fixed(31) Init(0); Do i=1 To hbound(times); /* loop over times */ time=times(i); /* pick a time */ alpha=t2a(time); /* convert to angle (radians) */ x=x+sin(alpha); /* accumulate sines */ y=y+cos(alpha); /* accumulate cosines */ End; ww=atan(x/y); /* compute average angle */ ss=ww*day/(2*pi); /* convert to seconds */ If ss<0 Then ss=ss+day; /* avoid negative value */ m=ss/60; /* split into hh mm ss */ s=ss-m*60; h=m/60; m=m-h*60; Put Edit(h,':',m,':',s)(Skip,3(p'99',a));   t2a: Procedure(t) Returns(Bin Float(18)); /* convert time to angle */ Dcl t Char(8); Dcl 1 tt Based(addr(t)), 2 hh Pic'99', 2 * Char(1), 2 mm Pic'99', 2 * Char(1), 2 ss Pic'99'; Dcl sec Bin Fixed(31); Dcl a Bin Float(18); sec=(hh*60+mm)*60+ss; If sec>(day/2) Then sec=sec-day; a=2*pi*sec/day; Return (a); End;   End;
http://rosettacode.org/wiki/AVL_tree
AVL tree
This page uses content from Wikipedia. The original article was at AVL tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In computer science, an AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; at no time do they differ by more than one because rebalancing is done ensure this is the case. Lookup, insertion, and deletion all take O(log n) time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations. Note the tree of nodes comprise a set, so duplicate node keys are not allowed. AVL trees are often compared with red-black trees because they support the same set of operations and because red-black trees also take O(log n) time for the basic operations. Because AVL trees are more rigidly balanced, they are faster than red-black trees for lookup-intensive applications. Similar to red-black trees, AVL trees are height-balanced, but in general not weight-balanced nor μ-balanced; that is, sibling nodes can have hugely differing numbers of descendants. Task Implement an AVL tree in the language of choice, and provide at least basic operations.
#Sidef
Sidef
class AVLtree {   has root = nil   struct Node { Number key, Number balance = 0, Node left = nil, Node right = nil, Node parent = nil, }   method insert(key) { if (root == nil) { root = Node(key) return true }   var n = root var parent = nil   loop { if (n.key == key) { return false } parent = n var goLeft = (n.key > key) n = (goLeft ? n.left : n.right)   if (n == nil) { var tn = Node(key, parent: parent) if (goLeft) { parent.left = tn } else { parent.right = tn } self.rebalance(parent) break } }   return true }   method delete_key(delKey) { if (root == nil) { return nil }   var n = root var parent = root var delNode = nil var child = root   while (child != nil) { parent = n n = child child = (delKey >= n.key ? n.right : n.left) if (delKey == n.key) { delNode = n } }   if (delNode != nil) { delNode.key = n.key child = (n.left != nil ? n.left : n.right)   if (root.key == delKey) { root = child } else { if (parent.left == n) { parent.left = child } else { parent.right = child } self.rebalance(parent) } } }   method rebalance(n) { if (n == nil) { return nil } self.setBalance(n)   given (n.balance) { when (-2) { if (self.height(n.left.left) >= self.height(n.left.right)) { n = self.rotate(n, :right) } else { n = self.rotate_twice(n, :left, :right) } } when (2) { if (self.height(n.right.right) >= self.height(n.right.left)) { n = self.rotate(n, :left) } else { n = self.rotate_twice(n, :right, :left) } } }   if (n.parent != nil) { self.rebalance(n.parent) } else { root = n } }   method rotate(a, dir) { var b = (dir == :left ? a.right : a.left) b.parent = a.parent   (dir == :left) ? (a.right = b.left)  : (a.left = b.right)   if (a.right != nil) { a.right.parent = a }   b.$dir = a a.parent = b   if (b.parent != nil) { if (b.parent.right == a) { b.parent.right = b } else { b.parent.left = b } }   self.setBalance(a, b) return b }   method rotate_twice(n, dir1, dir2) { n.left = self.rotate(n.left, dir1) self.rotate(n, dir2) }   method height(n) { if (n == nil) { return -1 } 1 + Math.max(self.height(n.left), self.height(n.right)) }   method setBalance(*nodes) { nodes.each { |n| n.balance = (self.height(n.right) - self.height(n.left)) } }   method printBalance { self.printBalance(root) }   method printBalance(n) { if (n != nil) { self.printBalance(n.left) print(n.balance, ' ') self.printBalance(n.right) } } }   var tree = AVLtree()   say "Inserting values 1 to 10" {|i| tree.insert(i) } << 1..10 print "Printing balance: " tree.printBalance
http://rosettacode.org/wiki/Averages/Mean_angle
Averages/Mean angle
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the second was of 10 degrees then the average of the numbers is 180 degrees, whereas if you can note that 350 degrees is equivalent to -10 degrees and so you have two readings at 10 degrees either side of zero degrees leading to a more fitting mean angle of zero degrees. To calculate the mean angle of several angles: Assume all angles are on the unit circle and convert them to complex numbers expressed in real and imaginary form. Compute the mean of the complex numbers. Convert the complex mean to polar coordinates whereupon the phase of the complex mean is the required angular mean. (Note that, since the mean is the sum divided by the number of numbers, and division by a positive real number does not affect the angle, you can also simply compute the sum for step 2.) You can alternatively use this formula: Given the angles α 1 , … , α n {\displaystyle \alpha _{1},\dots ,\alpha _{n}} the mean is computed by α ¯ = atan2 ⁡ ( 1 n ⋅ ∑ j = 1 n sin ⁡ α j , 1 n ⋅ ∑ j = 1 n cos ⁡ α j ) {\displaystyle {\bar {\alpha }}=\operatorname {atan2} \left({\frac {1}{n}}\cdot \sum _{j=1}^{n}\sin \alpha _{j},{\frac {1}{n}}\cdot \sum _{j=1}^{n}\cos \alpha _{j}\right)} Task[edit] write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle. (You should use a built-in function if you have one that does this for degrees or radians). Use the function to compute the means of these lists of angles (in degrees):   [350, 10]   [90, 180, 270, 360]   [10, 20, 30] Show your output here. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#PHP
PHP
<?php $samples = array( '1st' => array(350, 10), '2nd' => array(90, 180, 270, 360), '3rd' => array(10, 20, 30) );   foreach($samples as $key => $sample){ echo 'Mean angle for ' . $key . ' sample: ' . meanAngle($sample) . ' degrees.' . PHP_EOL; }   function meanAngle ($angles){ $y_part = $x_part = 0; $size = count($angles); for ($i = 0; $i < $size; $i++){ $x_part += cos(deg2rad($angles[$i])); $y_part += sin(deg2rad($angles[$i])); } $x_part /= $size; $y_part /= $size; return rad2deg(atan2($y_part, $x_part)); } ?>
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
#GAP
GAP
Median := function(v) local n, w; w := SortedList(v); n := Length(v); return (w[QuoInt(n + 1, 2)] + w[QuoInt(n, 2) + 1]) / 2; end;   a := [41, 56, 72, 17, 93, 44, 32]; b := [41, 72, 17, 93, 44, 32];   Median(a); # 44 Median(b); # 85/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
#Go
Go
package main   import ( "fmt" "sort" )   func main() { fmt.Println(median([]float64{3, 1, 4, 1})) // prints 2 fmt.Println(median([]float64{3, 1, 4, 1, 5})) // prints 3 }   func median(a []float64) float64 { sort.Float64s(a) half := len(a) / 2 m := a[half] if len(a)%2 == 0 { m = (m + a[half-1]) / 2 } return m }
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
#Lasso
Lasso
define arithmetic_mean(a::staticarray)::decimal => { //sum of the list divided by its length return (with e in #a sum #e) / decimal(#a->size) } define geometric_mean(a::staticarray)::decimal => { // The geometric mean is the nth root of the product of the list local(prod = 1) with e in #a do => { #prod *= #e } return math_pow(#prod,1/decimal(#a->size)) } define harmonic_mean(a::staticarray)::decimal => { // The harmonic mean is n divided by the sum of the reciprocal of each item in the list return decimal(#a->size)/(with e in #a sum 1/decimal(#e)) }   arithmetic_mean(generateSeries(1,10)->asStaticArray) geometric_mean(generateSeries(1,10)->asStaticArray) harmonic_mean(generateSeries(1,10)->asStaticArray)
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.
#Ruby
Ruby
class BalancedTernary include Comparable def initialize(str = "") if str =~ /[^-+0]+/ raise ArgumentError, "invalid BalancedTernary number: #{str}" end @digits = trim0(str) end   I2BT = {0 => ["0",0], 1 => ["+",0], 2 => ["-",1]} def self.from_int(value) n = value.to_i digits = "" while n != 0 quo, rem = n.divmod(3) bt, carry = I2BT[rem] digits = bt + digits n = quo + carry end new(digits) end   BT2I = {"-" => -1, "0" => 0, "+" => 1} def to_int @digits.chars.inject(0) do |sum, char| sum = 3 * sum + BT2I[char] end end alias :to_i :to_int   def to_s @digits.dup # String is mutable end alias :inspect :to_s   def <=>(other) to_i <=> other.to_i end   ADDITION_TABLE = { "---" => ["-","0"], "--0" => ["-","+"], "--+" => ["0","-"], "-0-" => ["-","+"], "-00" => ["0","-"], "-0+" => ["0","0"], "-+-" => ["0","-"], "-+0" => ["0","0"], "-++" => ["0","+"], "0--" => ["-","+"], "0-0" => ["0","-"], "0-+" => ["0","0"], "00-" => ["0","-"], "000" => ["0","0"], "00+" => ["0","+"], "0+-" => ["0","0"], "0+0" => ["0","+"], "0++" => ["+","-"], "+--" => ["0","-"], "+-0" => ["0","0"], "+-+" => ["0","+"], "+0-" => ["0","0"], "+00" => ["0","+"], "+0+" => ["+","-"], "++-" => ["0","+"], "++0" => ["+","-"], "+++" => ["+","0"], }   def +(other) maxl = [to_s.length, other.to_s.length].max a = pad0_reverse(to_s, maxl) b = pad0_reverse(other.to_s, maxl) carry = "0" sum = a.zip( b ).inject("") do |sum, (c1, c2)| carry, digit = ADDITION_TABLE[carry + c1 + c2] sum = digit + sum end self.class.new(carry + sum) end   MULTIPLICATION_TABLE = { "-" => "+0-", "0" => "000", "+" => "-0+", }   def *(other) product = self.class.new other.to_s.each_char do |bdigit| row = to_s.tr("-0+", MULTIPLICATION_TABLE[bdigit]) product += self.class.new(row) product << 1 end product >> 1 end   # negation def -@() self.class.new(@digits.tr('-+','+-')) end   # subtraction def -(other) self + (-other) end   # shift left def <<(count) @digits = trim0(@digits + "0"*count) self end   # shift right def >>(count) @digits[-count..-1] = "" if count > 0 @digits = trim0(@digits) self end   private   def trim0(str) str = str.sub(/^0+/, "") str = "0" if str.empty? str end   def pad0_reverse(str, len) str.rjust(len, "0").reverse.chars end end   a = BalancedTernary.new("+-0++0+") b = BalancedTernary.from_int(-436) c = BalancedTernary.new("+-++-")   %w[a b c a*(b-c)].each do |exp| val = eval(exp) puts "%8s :%13s,%8d" % [exp, val, val.to_i] 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.
#Scheme
Scheme
  (define (digits n) (string->list (number->string n)))   (define (ends-with list tail) ;; does list end with tail? (starts-with (reverse list) (reverse tail)))   (define (starts-with list head) (cond ((null? head) #t) ((null? list) #f) ((equal? (car list) (car head)) (starts-with (cdr list) (cdr head))) (else #f)))   (let loop ((i 1)) (if (ends-with (digits (* i i)) (digits 269696)) i (loop (+ i 1))))   ;; 25264  
http://rosettacode.org/wiki/Approximate_equality
Approximate equality
Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the difference in floating point calculations between different language implementations becomes significant. For example, a difference between 32 bit and 64 bit floating point calculations may appear by about the 8th significant digit in base 10 arithmetic. Task Create a function which returns true if two floating point numbers are approximately equal. The function should allow for differences in the magnitude of numbers, so that, for example, 100000000000000.01   may be approximately equal to   100000000000000.011, even though   100.01   is not approximately equal to   100.011. If the language has such a feature in its standard library, this may be used instead of a custom function. Show the function results with comparisons on the following pairs of values:     100000000000000.01,   100000000000000.011     (note: should return true)     100.01,   100.011                                                     (note: should return false)     10000000000000.001 / 10000.0,   1000000000.0000001000     0.001,   0.0010000001     0.000000000000000000000101,   0.0      sqrt(2) * sqrt(2),    2.0     -sqrt(2) * sqrt(2),   -2.0     3.14159265358979323846,   3.14159265358979324 Answers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.
#Ruby
Ruby
require "bigdecimal"   testvalues = [[100000000000000.01, 100000000000000.011], [100.01, 100.011], [10000000000000.001 / 10000.0, 1000000000.0000001000], [0.001, 0.0010000001], [0.000000000000000000000101, 0.0], [(2**0.5) * (2**0.5), 2.0], [-(2**0.5) * (2**0.5), -2.0], [BigDecimal("3.14159265358979323846"), 3.14159265358979324], [Float::NAN, Float::NAN,], [Float::INFINITY, Float::INFINITY], ]   class Numeric def close_to?(num, tol = Float::EPSILON) return true if self == num return false if (self.to_f.nan? or num.to_f.nan?) # NaN is not even close to itself return false if [self, num].count( Float::INFINITY) == 1 # Infinity is only close to itself return false if [self, num].count(-Float::INFINITY) == 1 (self-num).abs <= tol * ([self.abs, num.abs].max) end end   testvalues.each do |a,b| puts "#{a} #{a.close_to?(b) ? '≈' : '≉'} #{b}" end  
http://rosettacode.org/wiki/Approximate_equality
Approximate equality
Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the difference in floating point calculations between different language implementations becomes significant. For example, a difference between 32 bit and 64 bit floating point calculations may appear by about the 8th significant digit in base 10 arithmetic. Task Create a function which returns true if two floating point numbers are approximately equal. The function should allow for differences in the magnitude of numbers, so that, for example, 100000000000000.01   may be approximately equal to   100000000000000.011, even though   100.01   is not approximately equal to   100.011. If the language has such a feature in its standard library, this may be used instead of a custom function. Show the function results with comparisons on the following pairs of values:     100000000000000.01,   100000000000000.011     (note: should return true)     100.01,   100.011                                                     (note: should return false)     10000000000000.001 / 10000.0,   1000000000.0000001000     0.001,   0.0010000001     0.000000000000000000000101,   0.0      sqrt(2) * sqrt(2),    2.0     -sqrt(2) * sqrt(2),   -2.0     3.14159265358979323846,   3.14159265358979324 Answers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.
#Rust
Rust
/// Return whether the two numbers `a` and `b` are close. /// Closeness is determined by the `epsilon` parameter - /// the numbers are considered close if the difference between them /// is no more than epsilon * max(abs(a), abs(b)). fn isclose(a: f64, b: f64, epsilon: f64) -> bool { (a - b).abs() <= a.abs().max(b.abs()) * epsilon }   fn main() { fn sqrt(x: f64) -> f64 { x.sqrt() } macro_rules! test { ($a: expr, $b: expr) => { let operator = if isclose($a, $b, 1.0e-9) { '≈' } else { '≉' }; println!("{:>28} {} {}", stringify!($a), operator, stringify!($b)) } }   test!(100000000000000.01, 100000000000000.011); test!(100.01, 100.011); test!(10000000000000.001/10000.0, 1000000000.0000001000); test!(0.001, 0.0010000001); test!(0.000000000000000000000101, 0.0); test!( sqrt(2.0) * sqrt(2.0), 2.0); test!(-sqrt(2.0) * sqrt(2.0), -2.0); test!(3.14159265358979323846, 3.14159265358979324); }
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#Elena
Elena
import system'routines; import extensions; import extensions'text;   randomBrackets(len) { if (0 == len) { ^emptyString } else { var brackets := Array.allocate(len).populate:(i => $91) + Array.allocate(len).populate:(i => $93);   brackets := brackets.randomize(len * 2);   ^ brackets.summarize(new StringWriter()).toString() } }   extension op { get isBalanced() { var counter := new Integer(0);   self.seekEach:(ch => counter.append((ch==$91).iif(1,-1)) < 0);   ^ (0 == counter) } }   public program() { for(int len := 0, len < 9, len += 1) { var str := randomBrackets(len);   console.printLine("""",str,"""",str.isBalanced ? " is balanced" : " is not balanced") };   console.readChar() }
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.
#Groovy
Groovy
class PasswdRecord { String account, password, directory, shell int uid, gid SourceRecord source   private static final fs = ':' private static final fieldNames = ['account', 'password', 'uid', 'gid', 'source', 'directory', 'shell'] private static final stringFields = ['account', 'password', 'directory', 'shell'] private static final intFields = ['uid', 'gid']   PasswdRecord(String line = null) { if (!line) return def fields = line.split(fs) if (fields.size() != fieldNames.size()) { throw new IllegalArgumentException( "Passwd record must have exactly ${fieldNames.size()} '${fs}'-delimited fields") } (0..<fields.size()).each { i -> switch (fieldNames[i]) { case stringFields: this[fieldNames[i]] = fields[i]; break case intFields: this[fieldNames[i]] = fields[i] as Integer; break default /* source */: this.source = new SourceRecord(fields[i]); break } } }   @Override String toString() { fieldNames.collect { "${this[it]}${fs}" }.sum()[0..-2] } }   class SourceRecord { String fullname, office, extension, homephone, email   private static final fs = ',' private static final fieldNames = ['fullname', 'office', 'extension', 'homephone', 'email']   SourceRecord(String line = null) { if (!line) return def fields = line.split(fs) if (fields.size() != fieldNames.size()) { throw new IllegalArgumentException( "Source record must have exactly ${fieldNames.size()} '${fs}'-delimited fields") } (0..<fields.size()).each { i -> this[fieldNames[i]] = fields[i] } }   @Override String toString() { fieldNames.collect { "${this[it]}${fs}" }.sum()[0..-2] } }   def appendNewPasswdRecord = { PasswdRecord pwr = new PasswdRecord().with { p -> (account, password, uid, gid) = ['xyz', 'x', 1003, 1000] source = new SourceRecord().with { s -> (fullname, office, extension, homephone, email) = ['X Yz', 'Room 1003', '(234)555-8913', '(234)555-0033', '[email protected]'] s } (directory, shell) = ['/home/xyz', '/bin/bash'] p };   new File('passwd.txt').withWriterAppend { w -> w.append(pwr as String) w.append('\r\n') } }
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
#AutoIt
AutoIt
; Associative arrays in AutoIt. ; All the required functions are below the examples.   ; Initialize an error handler to deal with any COM errors.. global $oMyError = ObjEvent("AutoIt.Error", "AAError")   ; first example, simple. global $simple   ; Initialize your array ... AAInit($simple)   AAAdd($simple, "Appple", "fruit") AAAdd($simple, "Dog", "animal") AAAdd($simple, "Silicon", "tetravalent metalloid semiconductor")   ConsoleWrite("It is well-known that Silicon is a " & AAGetItem($simple, "Silicon") & "." & @CRLF) ConsoleWrite(@CRLF)     ; A more interesting example..   $ini_path = "AA_Test.ini" ; Put this prefs section in your ini file.. ; [test] ; foo=foo value ; foo2=foo2 value ; bar=bar value ; bar2=bar2 value     global $associative_array AAInit($associative_array)   ; We are going to convert this 2D array into a cute associative array where we ; can access the values by simply using their respective key names.. $test_array = IniReadSection($ini_path, "test")   for $z = 1 to 2 ; do it twice, to show that the items are *really* there! for $i = 1 to $test_array[0][0] $key_name = $test_array[$i][0] ConsoleWrite("Adding '" & $key_name & "'.." & @CRLF) ; key already exists in "$associative_array", use the pre-determined value.. if AAExists($associative_array, $key_name) then $this_value = AAGetItem($associative_array, $key_name) ConsoleWrite("key_name ALREADY EXISTS! : =>" & $key_name & "<=" & @CRLF) else $this_value = $test_array[$i][1] ; store left=right value pair in AA if $this_value then AAAdd($associative_array, $key_name, $this_value) endif endif next next   ConsoleWrite(@CRLF & "Array Count: =>" & AACount($associative_array) & "<=" & @CRLF) AAList($associative_array)   ConsoleWrite(@CRLF & "Removing 'foo'..") AARemove($associative_array, "foo")   ConsoleWrite(@CRLF & "Array Count: =>" & AACount($associative_array) & "<=" & @CRLF) AAList($associative_array)     AAWipe($associative_array)     ; end       func AAInit(ByRef $dict_obj) $dict_obj = ObjCreate("Scripting.Dictionary") endfunc   ; Adds a key and item pair to a Dictionary object.. func AAAdd(ByRef $dict_obj, $key, $val) $dict_obj.Add($key, $val) If @error Then return SetError(1, 1, -1) endfunc   ; Removes a key and item pair from a Dictionary object.. func AARemove(ByRef $dict_obj, $key) $dict_obj.Remove($key) If @error Then return SetError(1, 1, -1) endfunc   ; Returns true if a specified key exists in the associative array, false if not.. func AAExists(ByRef $dict_obj, $key) return $dict_obj.Exists($key) endfunc   ; Returns a value for a specified key name in the associative array.. func AAGetItem(ByRef $dict_obj, $key) return $dict_obj.Item($key) endfunc   ; Returns the total number of keys in the array.. func AACount(ByRef $dict_obj) return $dict_obj.Count endfunc   ; List all the "Key" > "Item" pairs in the array.. func AAList(ByRef $dict_obj) ConsoleWrite("AAList: =>" & @CRLF) local $k = $dict_obj.Keys ; Get the keys ; local $a = $dict_obj.Items ; Get the items (for reference) for $i = 0 to AACount($dict_obj) -1 ; Iterate the array ConsoleWrite($k[$i] & " ==> " & AAGetItem($dict_obj, $k[$i]) & @CRLF) next endfunc   ; Wipe the array, obviously. func AAWipe(ByRef $dict_obj) $dict_obj.RemoveAll() endfunc   ; Oh oh! func AAError() Local $err = $oMyError.number If $err = 0 Then $err = -1 SetError($err) ; to check for after this function returns endfunc   ;; End AA Functions.  
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
#Cowgol
Cowgol
include "cowgol.coh"; const AMOUNT := 20;   sub countFactors(n: uint16): (count: uint16) is var i: uint16 := 1; count := 1; while i <= n/2 loop if n%i == 0 then count := count + 1; end if; i := i + 1; end loop; end sub;   var max: uint16 := 0; var seen: uint8 := 0; var n: uint16 := 1; var f: uint16 := 0;   while seen < AMOUNT loop; f := countFactors(n); if f > max then print_i16(n); print_char(' '); max := f; seen := seen + 1; end if; n := n + 1; end loop; print_nl();
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Crystal
Crystal
def count_divisors(n : Int64) : Int64 return 1_i64 if n < 2 count = 2_i64   i = 2 while i <= n // 2 count += 1 if n % i == 0 i += 1 end   count end   max_div = 0_i64 count = 0_i64   print "The first 20 anti-primes are: "   n = 1_i64 while count < 20 d = count_divisors n   if d > max_div print "#{n} " max_div = d count += 1 end   n += 1 end   puts ""  
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.
#PARI.2FGP
PARI/GP
use strict; use 5.10.0;   use threads 'yield'; use threads::shared;   my @a :shared = (100) x 10; my $stop :shared = 0;   sub pick2 { my $i = int(rand(10)); my $j; $j = int(rand(10)) until $j != $i; ($i, $j) }   sub even { lock @a; my ($i, $j) = pick2; my $sum = $a[$i] + $a[$j]; $a[$i] = int($sum / 2); $a[$j] = $sum - $a[$i]; }   sub rand_move { lock @a; my ($i, $j) = pick2;   my $x = int(rand $a[$i]); $a[$i] -= $x; $a[$j] += $x; }   sub show { lock @a; my $sum = 0; $sum += $_ for (@a); printf "%4d", $_ for @a; print " total $sum\n"; }   my $t1 = async { even until $stop } my $t2 = async { rand_move until $stop } my $t3 = async { for (1 .. 10) { show; sleep(1); } $stop = 1; };   $t1->join; $t2->join; $t3->join;
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Lua
Lua
a = 5 assert (a == 42) assert (a == 42,'\''..a..'\' is not the answer to life, the universe, and everything')
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.
#M2000_Interpreter
M2000 Interpreter
  Module Assert { \\ This is a global object named Rec Global Group Rec { Private: document doc$="Error List at "+date$(today)+" "+time$(now)+{ } Public: lastfilename$="noname.err" Module Error(a$) { if a$="" then exit .doc$<=" "+a$+{ } flush error } Module Reset { Clear .doc$ } Module Display { Report .doc$ } Module SaveIt { .lastfilename$<=replace$("/", "-","Err"+date$(today)+time$(now)+".err") Save.Doc .doc$,.lastfilename$ } } Module Checkit { Function Error1 (x) { if x<10 then Print "Normal" : exit =130 ' error code } Call Error1(5) Try ok { Call Error1(100) } If not Ok then Rec.Error Error$ : Flush Error   Test "breakpoint A" ' open Control form, show code as executed, press next or close it   Try { Report "Run this" Error "Hello" Report "Not run this" } Rec.Error Error$   Module Error1 (x) { if x<10 then Print "Normal" : exit Error "Big Error" } Try ok { Error1 100 } If Error then Rec.Error Error$ } Checkit Rec.Display Rec.SaveIt win "notepad.exe", dir$+Rec.lastfilename$ } Assert  
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.
#Maple
Maple
a := 5: ASSERT( a = 42 ); ASSERT( a = 42, "a is not the answer to life, the universe, and everything" );
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.
#CLU
CLU
% This procedure will call a given procedure with each element % of the given array. Thanks to CLU's type parameterization, % it will work for any type of element. apply_to_all = proc [T: type] (a: array[T], f: proctype(int,T)) for i: int in array[T]$indexes(a) do f(i, a[i]) end end apply_to_all   % Callbacks for both string and int show_int = proc (i, val: int) po: stream := stream$primary_output() stream$putl(po, "array[" || int$unparse(i) || "] = " || int$unparse(val)); end show_int   show_string = proc (i: int, val: string) po: stream := stream$primary_output() stream$putl(po, "array[" || int$unparse(i) || "] = " || val); end show_string   % Here's how to use them start_up = proc () po: stream := stream$primary_output()   ints: array[int] := array[int]$[2, 3, 5, 7, 11] strings: array[string] := array[string]$ ["enemy", "lasagna", "robust", "below", "wax"]   stream$putl(po, "Ints: ") apply_to_all[int](ints, show_int)   stream$putl(po, "\nStrings: ") apply_to_all[string](strings, show_string) end start_up
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.
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. Map.   DATA DIVISION. WORKING-STORAGE SECTION. 01 Table-Size CONSTANT 30.   LOCAL-STORAGE SECTION. 01 I USAGE UNSIGNED-INT.   LINKAGE SECTION. 01 Table-Param. 03 Table-Values USAGE COMP-2 OCCURS Table-Size TIMES.   01 Func-Id PIC X(30).   PROCEDURE DIVISION USING Table-Param Func-Id. PERFORM VARYING I FROM 1 BY 1 UNTIL Table-Size < I CALL Func-Id USING BY REFERENCE Table-Values (I) END-PERFORM   GOBACK .
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
#Oz
Oz
declare fun {Mode Xs} Freq = {Dictionary.new} for X in Xs do Freq.X := {CondSelect Freq X 0} + 1 end MaxCount = {FoldL {Dictionary.items Freq} Max 0} in for Value#Count in {Dictionary.entries Freq} collect:C do if Count == MaxCount then {C Value} end end end in {Show {Mode [1 2 3 3 2 1 1]}} {Show {Mode [1 2 3 3 2 1]}}
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
#Delphi
Delphi
program AssociativeArrayIteration;   {$APPTYPE CONSOLE}   uses SysUtils, Generics.Collections;   var i: Integer; s: string; lDictionary: TDictionary<string, Integer>; lPair: TPair<string, Integer>; begin lDictionary := TDictionary<string, Integer>.Create; try lDictionary.Add('foo', 5); lDictionary.Add('bar', 10); lDictionary.Add('baz', 15); lDictionary.AddOrSetValue('foo', 6);   for lPair in lDictionary do Writeln(Format('Pair: %s = %d', [lPair.Key, lPair.Value])); for s in lDictionary.Keys do Writeln('Key: ' + s); for i in lDictionary.Values do Writeln('Value: ', i); finally lDictionary.Free; end; end.
http://rosettacode.org/wiki/Apply_a_digital_filter_(direct_form_II_transposed)
Apply a digital filter (direct form II transposed)
Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [1] Task Filter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667] The signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]
#ooRexx
ooRexx
/* REXX */ a=.array~of(1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17) b=.array~of(0.16666667, 0.5, 0.5, 0.16666667) s=.array~of(-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)   ret=.array~new(s~items)~~fill(0) /* create array and fill with zeroes */   Call filter a,b,s,ret Do i=1 To ret~items Say format(i,2) format(ret[i],2,12) End Exit   ::Routine filter Use Arg a,b,s,ret Do i=1 To s~items temp=0 Do j=1 To b~items if i-j>=0 Then temp=temp+b[j]*s[i-j+1] End Do j=1 To a~items if i-j>=0 Then Do u=i-j+1 temp=temp-a[j]*ret[u] End End ret[i]=temp/a[1] End Return   ::OPTIONS digits 24 /* Numeric Digits 24, everywhere */  
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]
#Perl
Perl
use strict; use List::AllUtils 'natatime';   sub TDF_II_filter { our(@signal,@a,@b); local(*signal,*a,*b) = (shift, shift, shift); my @out = (0) x $#signal; for my $i (0..@signal-1) { my $this; map { $this += $b[$_] * $signal[$i-$_] if $i-$_ >= 0 } 0..@b; map { $this -= $a[$_] * $out[$i-$_] if $i-$_ >= 0 } 0..@a; $out[$i] = $this / $a[0]; } @out }   my @signal = ( -0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589 ); my @a = ( 1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17 ); my @b = ( 0.16666667, 0.5, 0.5, 0.16666667 );   my @filtered = TDF_II_filter(\@signal, \@a, \@b); my $iter = natatime 5, @filtered; while( my @values = $iter->() ) { printf(' %10.6f' x 5 . "\n", @values); }  
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#ECL
ECL
  AveVal(SET OF INTEGER s) := AVE(s);   //example usage   SetVals := [14,9,16,20,91]; AveVal(SetVals) //returns 30.0 ;  
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#Elena
Elena
import extensions;   extension op { average() { real sum := 0; int count := 0;   var enumerator := self.enumerator();   while (enumerator.next()) { sum += enumerator.get(); count += 1; };   ^ sum / count } }   public program() { var array := new int[]{1, 2, 3, 4, 5, 6, 7, 8}; console.printLine( "Arithmetic mean of {",array.asEnumerable(),"} is ", array.average()).readChar() }
http://rosettacode.org/wiki/Associative_array/Merging
Associative array/Merging
Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be: Key Value "name" "Rocket Skates" "price" 15.25 "color" "red" "year" 1974
#zkl
zkl
base:=Dictionary( "name", "Rocket Skates", "price", 12.75, "color", "yellow",); update:=Dictionary( "price", 15.25, "color", "red", "year", 1974,);   update.pump( new:=base.copy() );   new.pump(Void,fcn([(k,v)]){ println("%s\t%s".fmt(k,v)) });
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%)
#Scheme
Scheme
  (import (scheme base) (scheme write) (srfi 1 lists) (only (srfi 13 strings) string-pad-right) (srfi 27 random-bits))   (define (analytical-function n) (define (factorial n) (fold * 1 (iota n 1))) ; (fold (lambda (i sum) (+ sum (/ (factorial n) (expt n i) (factorial (- n i))))) 0 (iota n 1)))   (define (simulation n runs) (define (single-simulation) (random-source-randomize! default-random-source) (let ((vec (make-vector n #f))) (let loop ((count 0) (num (random-integer n))) (if (vector-ref vec num) count (begin (vector-set! vec num #t) (loop (+ 1 count) (random-integer n))))))) ;; (let loop ((total 0) (run runs)) (if (zero? run) (/ total runs) (loop (+ total (single-simulation)) (- run 1)))))   (display " N average formula (error) \n") (display "=== ========= ========= =========\n") (for-each (lambda (n) (let ((simulation (inexact (simulation n 10000))) (formula (inexact (analytical-function n)))) (display (string-append " " (string-pad-right (number->string n) 3) " " (string-pad-right (number->string simulation) 6) " " (string-pad-right (number->string formula) 6) " (" (string-pad-right (number->string (* 100 (/ (- simulation formula) formula))) 5) "%)")) (newline))) (iota 20 1))  
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
#Tcl
Tcl
oo::class create SimpleMovingAverage { variable vals idx constructor {{period 3}} { set idx end-[expr {$period-1}] set vals {} } method val x { set vals [lrange [list {*}$vals $x] $idx end] expr {[tcl::mathop::+ {*}$vals]/double([llength $vals])} } }
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.
#Modula-2
Modula-2
MODULE AttractiveNumbers; FROM InOut IMPORT WriteCard, WriteLn;   CONST Max = 120;   VAR n, col: CARDINAL; Prime: ARRAY [1..Max] OF BOOLEAN;   PROCEDURE Sieve; VAR i, j: CARDINAL; BEGIN Prime[1] := FALSE; FOR i := 2 TO Max DO Prime[i] := TRUE; END;   FOR i := 2 TO Max DIV 2 DO IF Prime[i] THEN j := i*2; WHILE j <= Max DO Prime[j] := FALSE; j := j + i; END; END; END; END Sieve;   PROCEDURE Factors(n: CARDINAL): CARDINAL; VAR i, factors: CARDINAL; BEGIN factors := 0; FOR i := 2 TO Max DO IF i > n THEN RETURN factors; END; IF Prime[i] THEN WHILE n MOD i = 0 DO n := n DIV i; factors := factors + 1; END; END; END; RETURN factors; END Factors;   BEGIN Sieve(); col := 0; FOR n := 2 TO Max DO IF Prime[Factors(n)] THEN WriteCard(n, 4); col := col + 1; IF col MOD 15 = 0 THEN WriteLn(); END; END; END; WriteLn(); END AttractiveNumbers.
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
#PowerShell
PowerShell
  function Get-MeanTimeOfDay { [CmdletBinding()] [OutputType([timespan])] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [ValidatePattern("(?:2[0-3]|[01]?[0-9])[:.][0-5]?[0-9][:.][0-5]?[0-9]")] [string[]] $Time )   Begin { [double[]]$angles = @()   function ConvertFrom-Time ([timespan]$Time) { [double]((360 * $Time.Hours / 24) + (360 * $Time.Minutes / (24 * 60)) + (360 * $Time.Seconds / (24 * 3600))) }   function ConvertTo-Time ([double]$Angle) { $t = New-TimeSpan -Hours ([int](24 * 60 * 60 * $Angle / 360) / 3600) ` -Minutes (([int](24 * 60 * 60 * $Angle / 360) % 3600 - [int](24 * 60 * 60 * $Angle / 360) % 60) / 60) ` -Seconds ([int]((24 * 60 * 60 * $Angle / 360) % 60))   if ($t.Days -gt 0) { return ($t - (New-TimeSpan -Hours 1)) }   $t }   function Get-MeanAngle ([double[]]$Angles) { [double]$x,$y = 0   for ($i = 0; $i -lt $Angles.Count; $i++) { $x += [Math]::Cos($Angles[$i] * [Math]::PI / 180) $y += [Math]::Sin($Angles[$i] * [Math]::PI / 180) }   $result = [Math]::Atan2(($y / $Angles.Count), ($x / $Angles.Count)) * 180 / [Math]::PI   if ($result -lt 0) { return ($result + 360) }   $result } } Process { $angles += ConvertFrom-Time $_ } End { ConvertTo-Time (Get-MeanAngle $angles) } }  
http://rosettacode.org/wiki/AVL_tree
AVL tree
This page uses content from Wikipedia. The original article was at AVL tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In computer science, an AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; at no time do they differ by more than one because rebalancing is done ensure this is the case. Lookup, insertion, and deletion all take O(log n) time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations. Note the tree of nodes comprise a set, so duplicate node keys are not allowed. AVL trees are often compared with red-black trees because they support the same set of operations and because red-black trees also take O(log n) time for the basic operations. Because AVL trees are more rigidly balanced, they are faster than red-black trees for lookup-intensive applications. Similar to red-black trees, AVL trees are height-balanced, but in general not weight-balanced nor μ-balanced; that is, sibling nodes can have hugely differing numbers of descendants. Task Implement an AVL tree in the language of choice, and provide at least basic operations.
#Simula
Simula
CLASS AVL; BEGIN    ! AVL TREE ADAPTED FROM JULIENNE WALKER'S PRESENTATION AT ;  ! HTTP://ETERNALLYCONFUZZLED.COM/TUTS/DATASTRUCTURES/JSW_TUT_AVL.ASPX. ;  ! THIS PORT USES SIMILAR INDENTIFIER NAMES. ;    ! THE KEY INTERFACE MUST BE SUPPORTED BY DATA STORED IN THE AVL TREE. ; CLASS KEY; VIRTUAL: PROCEDURE LESS IS BOOLEAN PROCEDURE LESS (K); REF(KEY) K;; PROCEDURE EQUAL IS BOOLEAN PROCEDURE EQUAL(K); REF(KEY) K;; BEGIN END KEY;    ! NODE IS A NODE IN AN AVL TREE. ; CLASS NODE(DATA); REF(KEY) DATA;  ! ANYTHING COMPARABLE WITH LESS AND EQUAL. ; BEGIN INTEGER BALANCE;  ! BALANCE FACTOR ; REF(NODE) ARRAY LINK(0:1);  ! CHILDREN, INDEXED BY "DIRECTION", 0 OR 1. ; END NODE;    ! A LITTLE READABILITY FUNCTION FOR RETURNING THE OPPOSITE OF A DIRECTION, ;  ! WHERE A DIRECTION IS 0 OR 1. ;  ! WHERE JW WRITES !DIR, THIS CODE HAS OPP(DIR). ; INTEGER PROCEDURE OPP(DIR); INTEGER DIR; BEGIN OPP := 1 - DIR; END OPP;    ! SINGLE ROTATION ; REF(NODE) PROCEDURE SINGLE(ROOT, DIR); REF(NODE) ROOT; INTEGER DIR; BEGIN REF(NODE) SAVE; SAVE :- ROOT.LINK(OPP(DIR)); ROOT.LINK(OPP(DIR)) :- SAVE.LINK(DIR); SAVE.LINK(DIR) :- ROOT; SINGLE :- SAVE; END SINGLE;    ! DOUBLE ROTATION ; REF(NODE) PROCEDURE DOUBLE(ROOT, DIR); REF(NODE) ROOT; INTEGER DIR; BEGIN REF(NODE) SAVE; SAVE :- ROOT.LINK(OPP(DIR)).LINK(DIR);   ROOT.LINK(OPP(DIR)).LINK(DIR) :- SAVE.LINK(OPP(DIR)); SAVE.LINK(OPP(DIR)) :- ROOT.LINK(OPP(DIR)); ROOT.LINK(OPP(DIR)) :- SAVE;   SAVE :- ROOT.LINK(OPP(DIR)); ROOT.LINK(OPP(DIR)) :- SAVE.LINK(DIR); SAVE.LINK(DIR) :- ROOT; DOUBLE :- SAVE; END DOUBLE;    ! ADJUST BALANCE FACTORS AFTER DOUBLE ROTATION ; PROCEDURE ADJUSTBALANCE(ROOT, DIR, BAL); REF(NODE) ROOT; INTEGER DIR, BAL; BEGIN REF(NODE) N, NN; N :- ROOT.LINK(DIR); NN :- N.LINK(OPP(DIR)); IF NN.BALANCE = 0 THEN BEGIN ROOT.BALANCE := 0; N.BALANCE := 0; END ELSE IF NN.BALANCE = BAL THEN BEGIN ROOT.BALANCE := -BAL; N.BALANCE := 0; END ELSE BEGIN ROOT.BALANCE := 0; N.BALANCE := BAL; END; NN.BALANCE := 0; END ADJUSTBALANCE;   REF(NODE) PROCEDURE INSERTBALANCE(ROOT, DIR); REF(NODE) ROOT; INTEGER DIR; BEGIN REF(NODE) N; INTEGER BAL; N :- ROOT.LINK(DIR); BAL := 2*DIR - 1; IF N.BALANCE = BAL THEN BEGIN ROOT.BALANCE := 0; N.BALANCE := 0; INSERTBALANCE :- SINGLE(ROOT, OPP(DIR)); END ELSE BEGIN ADJUSTBALANCE(ROOT, DIR, BAL); INSERTBALANCE :- DOUBLE(ROOT, OPP(DIR)); END; END INSERTBALANCE;   CLASS TUPLE(N,B); REF(NODE) N; BOOLEAN B;;   REF(TUPLE) PROCEDURE INSERTR(ROOT, DATA); REF(NODE) ROOT; REF(KEY) DATA; BEGIN IF ROOT == NONE THEN INSERTR :- NEW TUPLE(NEW NODE(DATA), FALSE) ELSE BEGIN REF(TUPLE) T; BOOLEAN DONE; INTEGER DIR; DIR := 0; IF ROOT.DATA.LESS(DATA) THEN DIR := 1; T :- INSERTR(ROOT.LINK(DIR), DATA); ROOT.LINK(DIR) :- T.N; DONE := T.B; IF DONE THEN INSERTR :- NEW TUPLE(ROOT, TRUE) ELSE BEGIN ROOT.BALANCE := ROOT.BALANCE + 2*DIR - 1; IF ROOT.BALANCE = 0 THEN INSERTR :- NEW TUPLE(ROOT, TRUE) ELSE IF ROOT.BALANCE = 1 OR ROOT.BALANCE = -1 THEN INSERTR :- NEW TUPLE(ROOT, FALSE) ELSE INSERTR :- NEW TUPLE(INSERTBALANCE(ROOT, DIR), TRUE); END; END; END INSERTR;    ! INSERT A NODE INTO THE AVL TREE. ;  ! DATA IS INSERTED EVEN IF OTHER DATA WITH THE SAME KEY ALREADY EXISTS. ; PROCEDURE INSERT(TREE, DATA); NAME TREE; REF(NODE) TREE; REF(KEY) DATA; BEGIN REF(TUPLE) T; T :- INSERTR(TREE, DATA); TREE :- T.N; END INSERT;   REF(TUPLE) PROCEDURE REMOVEBALANCE(ROOT, DIR); REF(NODE) ROOT; INTEGER DIR; BEGIN REF(NODE) N; INTEGER BAL; N :- ROOT.LINK(OPP(DIR)); BAL := 2*DIR - 1;   IF N.BALANCE = -BAL THEN BEGIN ROOT.BALANCE := 0; N.BALANCE := 0; REMOVEBALANCE :- NEW TUPLE(SINGLE(ROOT, DIR), FALSE); END ELSE   IF N.BALANCE = BAL THEN BEGIN ADJUSTBALANCE(ROOT, OPP(DIR), -BAL); REMOVEBALANCE :- NEW TUPLE(DOUBLE(ROOT, DIR), FALSE); END ELSE   BEGIN ROOT.BALANCE := -BAL; N.BALANCE := BAL; REMOVEBALANCE :- NEW TUPLE(SINGLE(ROOT, DIR), TRUE); END END REMOVEBALANCE;   REF(TUPLE) PROCEDURE REMOVER(ROOT, DATA); REF(NODE) ROOT; REF(KEY) DATA; BEGIN INTEGER DIR; BOOLEAN DONE; REF(TUPLE) T;   IF ROOT == NONE THEN REMOVER :- NEW TUPLE(NONE, FALSE) ELSE IF ROOT.DATA.EQUAL(DATA) THEN BEGIN IF ROOT.LINK(0) == NONE THEN BEGIN REMOVER :- NEW TUPLE(ROOT.LINK(1), FALSE); GOTO L; END   ELSE IF ROOT.LINK(1) == NONE THEN BEGIN REMOVER :- NEW TUPLE(ROOT.LINK(0), FALSE); GOTO L; END   ELSE BEGIN REF(NODE) HEIR; HEIR :- ROOT.LINK(0); WHILE HEIR.LINK(1) =/= NONE DO HEIR :- HEIR.LINK(1); ROOT.DATA :- HEIR.DATA; DATA :- HEIR.DATA; END; END; DIR := 0; IF ROOT.DATA.LESS(DATA) THEN DIR := 1; T :- REMOVER(ROOT.LINK(DIR), DATA); ROOT.LINK(DIR) :- T.N; DONE := T.B; IF DONE THEN BEGIN REMOVER :- NEW TUPLE(ROOT, TRUE); GOTO L; END; ROOT.BALANCE := ROOT.BALANCE + 1 - 2*DIR; IF ROOT.BALANCE = 1 OR ROOT.BALANCE = -1 THEN REMOVER :- NEW TUPLE(ROOT, TRUE)   ELSE IF ROOT.BALANCE = 0 THEN REMOVER :- NEW TUPLE(ROOT, FALSE)   ELSE REMOVER :- REMOVEBALANCE(ROOT, DIR); L: END REMOVER;    ! REMOVE A SINGLE ITEM FROM AN AVL TREE. ;  ! IF KEY DOES NOT EXIST, FUNCTION HAS NO EFFECT. ; PROCEDURE REMOVE(TREE, DATA); NAME TREE; REF(NODE) TREE; REF(KEY) DATA; BEGIN REF(TUPLE) T; T :- REMOVER(TREE, DATA); TREE :- T.N; END REMOVEM;   END.
http://rosettacode.org/wiki/Averages/Mean_angle
Averages/Mean angle
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the second was of 10 degrees then the average of the numbers is 180 degrees, whereas if you can note that 350 degrees is equivalent to -10 degrees and so you have two readings at 10 degrees either side of zero degrees leading to a more fitting mean angle of zero degrees. To calculate the mean angle of several angles: Assume all angles are on the unit circle and convert them to complex numbers expressed in real and imaginary form. Compute the mean of the complex numbers. Convert the complex mean to polar coordinates whereupon the phase of the complex mean is the required angular mean. (Note that, since the mean is the sum divided by the number of numbers, and division by a positive real number does not affect the angle, you can also simply compute the sum for step 2.) You can alternatively use this formula: Given the angles α 1 , … , α n {\displaystyle \alpha _{1},\dots ,\alpha _{n}} the mean is computed by α ¯ = atan2 ⁡ ( 1 n ⋅ ∑ j = 1 n sin ⁡ α j , 1 n ⋅ ∑ j = 1 n cos ⁡ α j ) {\displaystyle {\bar {\alpha }}=\operatorname {atan2} \left({\frac {1}{n}}\cdot \sum _{j=1}^{n}\sin \alpha _{j},{\frac {1}{n}}\cdot \sum _{j=1}^{n}\cos \alpha _{j}\right)} Task[edit] write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle. (You should use a built-in function if you have one that does this for degrees or radians). Use the function to compute the means of these lists of angles (in degrees):   [350, 10]   [90, 180, 270, 360]   [10, 20, 30] Show your output here. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#PicoLisp
PicoLisp
(load "@lib/math.l")   (de meanAngle (Lst) (*/ (atan2 (sum '((A) (sin (*/ A pi 180.0))) Lst) (sum '((A) (cos (*/ A pi 180.0))) Lst) ) 180.0 pi ) )   (for L '((350.0 10.0) (90.0 180.0 270.0 360.0) (10.0 20.0 30.0)) (prinl "The mean angle of [" (glue ", " (mapcar round L '(0 .))) "] is: " (round (meanAngle L))) )
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
#PL.2FI
PL/I
averages: procedure options (main); /* 31 August 2012 */ declare b1(2) fixed initial (350, 10); declare b2(4) fixed initial (90, 180, 270, 360); declare b3(3) fixed initial (10, 20, 30);   put edit ( b1) (f(7)); put edit ( ' mean=', mean(b1) ) (a, f(7) ); put skip edit ( b3) (f(7)); put edit ( ' mean=', mean(b3) ) (a, f(7) ); put skip edit ( b2) (f(7)); put edit ( ' mean=', mean(b2) ) (a, f(7) );   mean: procedure (a) returns (fixed); declare a(*) float (18); return ( atand(sum(sind(a))/hbound(a), sum(cosd(a))/hbound(a) ) ); end mean;   end averages;
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
#PowerShell
PowerShell
  function Get-MeanAngle ([double[]]$Angles) { $x = ($Angles | ForEach-Object {[Math]::Cos($_ * [Math]::PI / 180)} | Measure-Object -Average).Average $y = ($Angles | ForEach-Object {[Math]::Sin($_ * [Math]::PI / 180)} | Measure-Object -Average).Average   [Math]::Atan2($y, $x) * 180 / [Math]::PI }  
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
#Groovy
Groovy
def median(Iterable col) { def s = col as SortedSet if (s == null) return null if (s.empty) return 0 def n = s.size() def m = n.intdiv(2) def l = s.collect { it } n%2 == 1 ? l[m] : (l[m] + l[m-1])/2 }
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
#Liberty_BASIC
Liberty BASIC
for i = 1 to 10 a = a + i next ArithmeticMean = a/10   b = 1 for i = 1 to 10 b = b * i next GeometricMean = b ^ (1/10)   for i = 1 to 10 c = c + (1/i) next HarmonicMean = 10/c   print "ArithmeticMean: ";ArithmeticMean print "Geometric Mean: ";GeometricMean print "Harmonic Mean: ";HarmonicMean   if (ArithmeticMean>=GeometricMean) and (GeometricMean>=HarmonicMean) then print "True" else print "False" end if  
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.
#Rust
Rust
use std::{ cmp::min, convert::{TryFrom, TryInto}, fmt, ops::{Add, Mul, Neg}, str::FromStr, };   fn main() -> Result<(), &'static str> { let a = BalancedTernary::from_str("+-0++0+")?; let b = BalancedTernary::from(-436); let c = BalancedTernary::from_str("+-++-")?; println!("a = {} = {}", a, i128::try_from(a.clone())?); println!("b = {} = {}", b, i128::try_from(b.clone())?); println!("c = {} = {}", c, i128::try_from(c.clone())?);   let d = a * (b + -c); println!("a * (b - c) = {} = {}", d, i128::try_from(d.clone())?);   let e = BalancedTernary::from_str( "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++", )?; assert_eq!(i128::try_from(e).is_err(), true);   Ok(()) }   #[derive(Clone, Copy, PartialEq)] enum Trit { Zero, Pos, Neg, }   impl TryFrom<char> for Trit { type Error = &'static str;   fn try_from(value: char) -> Result<Self, Self::Error> { match value { '0' => Ok(Self::Zero), '+' => Ok(Self::Pos), '-' => Ok(Self::Neg), _ => Err("Invalid character for balanced ternary"), } } }   impl From<Trit> for char { fn from(x: Trit) -> Self { match x { Trit::Zero => '0', Trit::Pos => '+', Trit::Neg => '-', } } }   impl Add for Trit { // (Carry, Current) type Output = (Self, Self);   fn add(self, rhs: Self) -> Self::Output { use Trit::{Neg, Pos, Zero}; match (self, rhs) { (Zero, x) | (x, Zero) => (Zero, x), (Pos, Neg) | (Neg, Pos) => (Zero, Zero), (Pos, Pos) => (Pos, Neg), (Neg, Neg) => (Neg, Pos), } } }   impl Mul for Trit { type Output = Self;   fn mul(self, rhs: Self) -> Self::Output { use Trit::{Neg, Pos, Zero}; match (self, rhs) { (Zero, _) | (_, Zero) => Zero, (Pos, Pos) | (Neg, Neg) => Pos, (Pos, Neg) | (Neg, Pos) => Neg, } } }   impl Neg for Trit { type Output = Self;   fn neg(self) -> Self::Output { match self { Trit::Zero => Trit::Zero, Trit::Pos => Trit::Neg, Trit::Neg => Trit::Pos, } } }   // The vector is stored in reverse from how it would be viewed, as // operations tend to work backwards #[derive(Clone)] struct BalancedTernary(Vec<Trit>);   impl fmt::Display for BalancedTernary { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}", self.0 .iter() .rev() .map(|&d| char::from(d)) .collect::<String>() ) } }   impl Add for BalancedTernary { type Output = Self;   fn add(self, rhs: Self) -> Self::Output { use Trit::Zero;   // Trim leading zeroes fn trim(v: &mut Vec<Trit>) { while let Some(last_elem) = v.pop() { if last_elem != Zero { v.push(last_elem); break; } } }   if rhs.0.is_empty() { // A balanced ternary shouldn't be empty if self.0.is_empty() { return BalancedTernary(vec![Zero]); } return self; }   let length = min(self.0.len(), rhs.0.len()); let mut sum = Vec::new(); let mut carry = vec![Zero];   for i in 0..length { let (carry_dig, digit) = self.0[i] + rhs.0[i]; sum.push(digit); carry.push(carry_dig); } // At least one of these two loops will be ignored for i in length..self.0.len() { sum.push(self.0[i]); } for i in length..rhs.0.len() { sum.push(rhs.0[i]); }   trim(&mut sum); trim(&mut carry);   BalancedTernary(sum) + BalancedTernary(carry) } }   // This version of `Mul` requires an implementation of the `Add` trait impl Mul for BalancedTernary { type Output = Self;   fn mul(self, rhs: Self) -> Self::Output { let mut results = Vec::with_capacity(rhs.0.len()); for i in 0..rhs.0.len() { let mut digits = vec![Trit::Zero; i]; for j in 0..self.0.len() { digits.push(self.0[j] * rhs.0[i]); } results.push(BalancedTernary(digits)); } #[allow(clippy::suspicious_arithmetic_impl)] results .into_iter() .fold(BalancedTernary(vec![Trit::Zero]), |acc, x| acc + x) } }   impl Neg for BalancedTernary { type Output = Self;   fn neg(self) -> Self::Output { BalancedTernary(self.0.iter().map(|&x| -x).collect()) } }   impl FromStr for BalancedTernary { type Err = &'static str;   fn from_str(s: &str) -> Result<Self, Self::Err> { s.chars() .rev() .map(|c| c.try_into()) .collect::<Result<_, _>>() .map(BalancedTernary) } }   impl From<i128> for BalancedTernary { fn from(x: i128) -> Self { let mut v = Vec::new(); let mut curr = x;   loop { let rem = curr % 3;   match rem { 0 => v.push(Trit::Zero), 1 | -2 => v.push(Trit::Pos), 2 | -1 => v.push(Trit::Neg), _ => unreachable!(), }   let offset = (rem as f64 / 3.0).round() as i128; curr = curr / 3 + offset;   if curr == 0 { break; } }   BalancedTernary(v) } }   impl TryFrom<BalancedTernary> for i128 { type Error = &'static str;   fn try_from(value: BalancedTernary) -> Result<Self, Self::Error> { value .0 .iter() .enumerate() .try_fold(0_i128, |acc, (i, character)| { let size_err = "Balanced ternary string is too large to fit into 16 bytes"; let index: u32 = i.try_into().map_err(|_| size_err)?;   match character { Trit::Zero => Ok(acc), Trit::Pos => 3_i128 .checked_pow(index) .and_then(|x| acc.checked_add(x)) .ok_or(size_err), Trit::Neg => 3_i128 .checked_pow(index) .and_then(|x| acc.checked_sub(x)) .ok_or(size_err), } }) } }  
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.
#Scilab
Scilab
n=2; flag=%F while ~flag n = n+2; if pmodulo(n*n,1000000)==269696 then flag=%T; end end disp(n);
http://rosettacode.org/wiki/Babbage_problem
Babbage problem
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125. He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain. Task[edit] The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand. As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred. For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L]. Motivation The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local var integer: current is 0; begin while current ** 2 rem 1000000 <> 269696 do incr(current); end while; writeln("The square of " <& current <& " is " <& current ** 2); end func;
http://rosettacode.org/wiki/Approximate_equality
Approximate equality
Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the difference in floating point calculations between different language implementations becomes significant. For example, a difference between 32 bit and 64 bit floating point calculations may appear by about the 8th significant digit in base 10 arithmetic. Task Create a function which returns true if two floating point numbers are approximately equal. The function should allow for differences in the magnitude of numbers, so that, for example, 100000000000000.01   may be approximately equal to   100000000000000.011, even though   100.01   is not approximately equal to   100.011. If the language has such a feature in its standard library, this may be used instead of a custom function. Show the function results with comparisons on the following pairs of values:     100000000000000.01,   100000000000000.011     (note: should return true)     100.01,   100.011                                                     (note: should return false)     10000000000000.001 / 10000.0,   1000000000.0000001000     0.001,   0.0010000001     0.000000000000000000000101,   0.0      sqrt(2) * sqrt(2),    2.0     -sqrt(2) * sqrt(2),   -2.0     3.14159265358979323846,   3.14159265358979324 Answers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.
#Scala
Scala
object Approximate extends App { val (ok, notOk, ε) = ("👌", "❌", 1e-18d)   private def approxEquals(value: Double, other: Double, epsilon: Double) = scala.math.abs(value - other) < epsilon   private def test(a: BigDecimal, b: BigDecimal, expected: Boolean): Unit = { val result = approxEquals(a.toDouble, b.toDouble, ε) println(f"$a%40.24f ≅ $b%40.24f => $result%5s ${if (expected == result) ok else notOk}") }   test(BigDecimal("100000000000000.010"), BigDecimal("100000000000000.011"), true) test(BigDecimal("100.01"), BigDecimal("100.011"), false) test(BigDecimal(10000000000000.001 / 10000.0), BigDecimal("1000000000.0000001000"), false) test(BigDecimal("0.001"), BigDecimal("0.0010000001"), false) test(BigDecimal("0.000000000000000000000101"), BigDecimal(0), true) test(BigDecimal(math.sqrt(2) * math.sqrt(2d)), BigDecimal(2.0), false) test(BigDecimal(-Math.sqrt(2) * Math.sqrt(2)), BigDecimal(-2.0), false) test(BigDecimal("3.14159265358979323846"), BigDecimal("3.14159265358979324"), true) }
http://rosettacode.org/wiki/Approximate_equality
Approximate equality
Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the difference in floating point calculations between different language implementations becomes significant. For example, a difference between 32 bit and 64 bit floating point calculations may appear by about the 8th significant digit in base 10 arithmetic. Task Create a function which returns true if two floating point numbers are approximately equal. The function should allow for differences in the magnitude of numbers, so that, for example, 100000000000000.01   may be approximately equal to   100000000000000.011, even though   100.01   is not approximately equal to   100.011. If the language has such a feature in its standard library, this may be used instead of a custom function. Show the function results with comparisons on the following pairs of values:     100000000000000.01,   100000000000000.011     (note: should return true)     100.01,   100.011                                                     (note: should return false)     10000000000000.001 / 10000.0,   1000000000.0000001000     0.001,   0.0010000001     0.000000000000000000000101,   0.0      sqrt(2) * sqrt(2),    2.0     -sqrt(2) * sqrt(2),   -2.0     3.14159265358979323846,   3.14159265358979324 Answers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.
#Sidef
Sidef
[ 100000000000000.01, 100000000000000.011, 100.01, 100.011, 10000000000000.001 / 10000.0, 1000000000.0000001000, 0.001, 0.0010000001, 0.000000000000000000000101, 0.0, sqrt(2) * sqrt(2), 2.0, -sqrt(2) * sqrt(2), -2.0, sqrt(-2) * sqrt(-2), -2.0, cbrt(3)**3, 3, cbrt(-3)**3, -3, 100000000000000003.0, 100000000000000004.0, 3.14159265358979323846, 3.14159265358979324 ].each_slice(2, {|a,b| say ("#{a} ≅ #{b}: ", a ≅ b) })
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
#Elixir
Elixir
defmodule Balanced_brackets do def task do Enum.each(0..5, fn n -> brackets = generate(n) result = is_balanced(brackets) |> task_balanced IO.puts "#{brackets} is #{result}" end) end   defp generate( 0 ), do: [] defp generate( n ) do for _ <- 1..2*n, do: Enum.random ["[", "]"] end   def is_balanced( brackets ), do: is_balanced_loop( brackets, 0 )   defp is_balanced_loop( _, n ) when n < 0, do: false defp is_balanced_loop( [], 0 ), do: true defp is_balanced_loop( [], _n ), do: false defp is_balanced_loop( ["[" | t], n ), do: is_balanced_loop( t, n + 1 ) defp is_balanced_loop( ["]" | t], n ), do: is_balanced_loop( t, n - 1 )   defp task_balanced( true ), do: "OK" defp task_balanced( false ), do: "NOT OK" end   Balanced_brackets.task
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.
#Haskell
Haskell
  {-# LANGUAGE RecordWildCards #-}   import System.IO import Data.List (intercalate)   data Gecos = Gecos { fullname :: String , office :: String , extension :: String , homephone :: String , email :: String }   data Record = Record { account :: String , password :: String , uid :: Int , gid :: Int , directory :: String , shell :: String , gecos :: Gecos }   instance Show Gecos where show (Gecos {..}) = intercalate "," [fullname, office, extension, homephone, email]   instance Show Record where show (Record {..}) = intercalate ":" [account, password, show uid, show gid, show gecos, directory, shell]   addRecord :: String -> Record -> IO () addRecord path r = appendFile path (show r)  
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
#AWK
AWK
BEGIN { a["red"] = 0xff0000 a["green"] = 0x00ff00 a["blue"] = 0x0000ff for (i in a) { printf "%8s %06x\n", i, a[i] } # deleting a key/value delete a["red"] for (i in a) { print i } # check if a key exists print ( "red" in a ) # print 0 print ( "blue" in a ) # print 1 }
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#D
D
import std.stdio;   int countDivisors(int n) { if (n < 2) { return 1; } int count = 2; // 1 and n for (int i = 2; i <= n/2; ++i) { if (n % i == 0) { ++count; } } return count; }   void main() { int maxDiv, count; writeln("The first 20 anti-primes are:"); for (int n = 1; count < 20; ++n) { int d = countDivisors(n); if (d > maxDiv) { write(n, ' '); maxDiv = d; count++; } } writeln; }
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
#Delphi
Delphi
defmodule AntiPrimes do def divcount(n) when is_integer(n), do: divcount(n, 1, 0)   def divcount(n, d, count) when d * d > n, do: count def divcount(n, d, count) do divs = case rem(n, d) do 0 -> case n - d * d do 0 -> 1 _ -> 2 end _ -> 0 end divcount(n, d + 1, count + divs) end   def antiprimes(n), do: antiprimes(n, 1, 0, [])   def antiprimes(0, _, _, l), do: Enum.reverse(l) def antiprimes(n, m, max, l) do count = divcount(m) case count > max do true -> antiprimes(n-1, m+1, count, [m|l]) false -> antiprimes(n, m+1, max, l) end end   def main() do :io.format("The first 20 anti-primes are ~w~n", [antiprimes(20)]) end end
http://rosettacode.org/wiki/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.
#Perl
Perl
use strict; use 5.10.0;   use threads 'yield'; use threads::shared;   my @a :shared = (100) x 10; my $stop :shared = 0;   sub pick2 { my $i = int(rand(10)); my $j; $j = int(rand(10)) until $j != $i; ($i, $j) }   sub even { lock @a; my ($i, $j) = pick2; my $sum = $a[$i] + $a[$j]; $a[$i] = int($sum / 2); $a[$j] = $sum - $a[$i]; }   sub rand_move { lock @a; my ($i, $j) = pick2;   my $x = int(rand $a[$i]); $a[$i] -= $x; $a[$j] += $x; }   sub show { lock @a; my $sum = 0; $sum += $_ for (@a); printf "%4d", $_ for @a; print " total $sum\n"; }   my $t1 = async { even until $stop } my $t2 = async { rand_move until $stop } my $t3 = async { for (1 .. 10) { show; sleep(1); } $stop = 1; };   $t1->join; $t2->join; $t3->join;
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Assert[var===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.
#MATLAB_.2F_Octave
MATLAB / Octave
assert(x == 42,'x = %d, not 42.',x);
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.
#Metafont
Metafont
def assert(expr t) = if not (t): errmessage("assertion failed") fi enddef;