task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#CoffeeScript
CoffeeScript
  map = (arr, f) -> (f(e) for e in arr) arr = [1, 2, 3, 4, 5] f = (x) -> x * x console.log map arr, f # prints [1, 4, 9, 16, 25]  
http://rosettacode.org/wiki/Averages/Mode
Averages/Mode
Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat...
#PARI.2FGP
PARI/GP
mode(v)={ my(count=1,r=1,b=v[1]); v=vecsort(v); for(i=2,#v, if(v[i]==v[i-1], count++ , if(count>r, r=count; b=v[i-1] ); count=1 ) ); if(count>r,v[#v],b) };
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Dyalect
Dyalect
var t = (x: 1, y: 2, z: 3)   for x in t.Keys() { print("\(x)=\(t[x])") }
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#E
E
def map := [ "a" => 1, "b" => 2, "c" => 3, ]   for key => value in map { println(`$key $value`) }   for value in map { # ignore keys println(`. $value`) }   for key => _ in map { # ignore values println(`$key .`) }   for key in map.domain() { # iterate over the set whose values are the keys print...
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 Filt...
#Phix
Phix
with javascript_semantics function direct_form_II_transposed_filter(sequence a, b, signal) sequence result = repeat(0,length(signal)) for i=1 to length(signal) do atom tmp = 0 for j=1 to min(i,length(b)) do tmp += b[j]*signal[i-j+1] end for for j=2 to min(i,length(a)) do tmp -= a[j]*resu...
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 conveyin...
#Elixir
Elixir
defmodule Average do def mean(list), do: Enum.sum(list) / length(list) end
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#Emacs_Lisp
Emacs Lisp
(defun mean (lst) (/ (float (apply '+ lst)) (length lst))) (mean '(1 2 3 4))
http://rosettacode.org/wiki/Average_loop_length
Average loop length
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i";   const integer: TESTS is 1000000;   const func float: factorial (in integer: number) is func result var float: factorial is 1.0; local var integer: i is 0; begin for i range 2 to number do factorial *:= flt(i); end for; end func;   const fu...
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 t...
#Sidef
Sidef
func find_loop(n) { var seen = Hash() loop { with (irand(1, n)) { |r| seen.has(r) ? (return seen.len) : (seen{r} = true) } } }   print " N empiric theoric (error)\n"; print "=== ========= ============ =========\n";   define MAX = 20 define TRIALS = 1000   for n...
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 avera...
#TI-83_BASIC
TI-83 BASIC
:1->C :While 1 :Prompt I :C->dim(L1) :I->L1(C) :Disp mean(L1) :1+C->C :End
http://rosettacode.org/wiki/Attractive_numbers
Attractive numbers
A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show sequence items up to   120....
#Nanoquery
Nanoquery
MAX = 120   def is_prime(n) d = 5 if (n < 2) return false end if (n % 2) = 0 return n = 2 end if (n % 3) = 0 return n = 3 end   while (d * d) <= n if n % d = 0 return false end d += 2 if n % d = 0 return false end d += 4 end   return true end   def count_prime_factors(n) count = 0; f ...
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....
#NewLisp
NewLisp
  (define (prime? n) (= (length (factor n)) 1)) (define (attractive? n) (prime? (length (factor n)))) ; (filter attractive? (sequence 2 120))  
http://rosettacode.org/wiki/Averages/Mean_time_of_day
Averages/Mean time of day
Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ideas of Averages/Mean angle compute ...
#Python
Python
from cmath import rect, phase from math import radians, degrees     def mean_angle(deg): return degrees(phase(sum(rect(1, radians(d)) for d in deg)/len(deg)))   def mean_time(times): t = (time.split(':') for time in times) seconds = ((float(s) + int(m) * 60 + int(h) * 3600) for h, m, s in t)...
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....
#Tcl
Tcl
package require TclOO   namespace eval AVL { # Class for the overall tree; manages real public API oo::class create Tree { variable root nil class constructor {{nodeClass AVL::Node}} { set class [oo::class create Node [list superclass $nodeClass]]   # Create a nil instance to act as a leaf sentinel ...
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 ...
#Processing
Processing
void setup() { println(meanAngle(350, 10)); println(meanAngle(90, 180, 270, 360)); println(meanAngle(10, 20, 30)); }   float meanAngle(float... angles) { float sum1 = 0, sum2 = 0; for (int i = 0; i < angles.length; i++) { sum1 += sin(radians(angles[i])) / angles.length; sum2 += cos(radians(angles[i]))...
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 ...
#PureBasic
PureBasic
NewList angle.d()   Macro AE(x) AddElement(angle()) : angle()=x EndMacro   Procedure.d atan3(y.d,x.d) If x<=0.0 : ProcedureReturn Sign(y)*#PI/2 : EndIf If x>0.0  : ProcedureReturn ATan(y/x)  : EndIf If y>0.0  : ProcedureReturn ATan(y/x)+#PI : EndIf ProcedureReturn ATan(y/x)-#PI EndProcedure   Procedure.d m...
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 ...
#Haskell
Haskell
import Data.List (partition)   nth :: Ord t => [t] -> Int -> t nth (x:xs) n | k == n = x | k > n = nth ys n | otherwise = nth zs $ n - k - 1 where (ys, zs) = partition (< x) xs k = length ys   medianMay :: (Fractional a, Ord a) => [a] -> Maybe a medianMay xs | n < 1 = Nothing | even n = Just ((nth x...
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 p...
#Logo
Logo
to compute_means :count local "sum make "sum 0 local "product make "product 1 local "reciprocal_sum make "reciprocal_sum 0   repeat :count [ make "sum sum :sum repcount make "product product :product repcount make "reciprocal_sum sum :reciprocal_sum (quotient repcount) ]   output (sen...
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" ...
#Scala
Scala
  object TernaryBit { val P = TernaryBit(+1) val M = TernaryBit(-1) val Z = TernaryBit( 0)   implicit def asChar(t: TernaryBit): Char = t.charValue implicit def valueOf(c: Char): TernaryBit = { c match { case '0' => 0 case '+' => 1 case '-' => -1 case nc => throw new Illegal...
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....
#SenseTalk
SenseTalk
  (* Answer Charles Babbage's question: What is the smallest positive integer whose square ends in the digits 269,696? *)   put 1 into int   repeat forever if int squared ends with "269696" then put "The smallest positive integer whose square ends in the digits 269696 is" && int exit all -- don't keep repeating fo...
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....
#SequenceL
SequenceL
main() := babbage(0);   babbage(current) := current when current * current mod 1000000 = 269696 else babbage(current + 1);
http://rosettacode.org/wiki/Approximate_equality
Approximate equality
Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the difference in floating point calculations between different language implementations becomes significant. For example, a difference between 32 bit and 64 bit floating point calculations may appear by about the 8t...
#Smalltalk
Smalltalk
{ #(100000000000000.01 100000000000000.011) . #(100.01 100.011) . {10000000000000.001 / 10000.0 . 1000000000.0000001000} . #(0.001 0.0010000001) . #(0.000000000000000000000101 0.0) . { 2 sqrt * 2 sqrt . 2.0} . { 2 sqrt negated * 2 sqrt . -2.0} . #(3.14159265358979323846 3.14159265358979324) } pairsDo:[:v...
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 8t...
#Swift
Swift
import Foundation   extension FloatingPoint { @inlinable public func isAlmostEqual( to other: Self, tolerance: Self = Self.ulpOfOne.squareRoot() ) -> Bool { // tolerances outside of [.ulpOfOne,1) yield well-defined but useless results, // so this is enforced by an assert rathern than a preconditio...
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 8t...
#Tcl
Tcl
catch {namespace delete test_almost_equal_decimal} ;# Start with a clean namespace   namespace eval test_almost_equal_decimal { package require Tcl 8.5 ;# required by tcllib package require math::decimal ;# from tcllib namespace import ::math::decimal::* ;# for: setVariable, fromstr, and compare   array...
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) ...
#Erlang
Erlang
  -module( balanced_brackets ). -export( [generate/1, is_balanced/1, task/0] ).   generate( N ) -> [generate_bracket(random:uniform()) || _X <- lists:seq(1, 2*N)].   is_balanced( String ) -> is_balanced_loop( String, 0 ).   task() -> lists:foreach( fun (N) -> String = generate( N ), Result = is_balanced( String...
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,...
#Icon_and_Unicon
Icon and Unicon
procedure main() orig := [ "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash", "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jsmith:/bin/bash" ] new := [ "xyz:x:1003:1000:X:Y...
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 ins...
#Babel
Babel
  (("foo" 13) ("bar" 42) ("baz" 77)) ls2map !
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Elixir
Elixir
defmodule AntiPrimes do def divcount(n) when is_integer(n), do: divcount(n, 1, 0)   def divcount(n, d, count) when d * d > n, do: count def divcount(n, d, count) do divs = case rem(n, d) do 0 -> case n - d * d do 0 -> 1 _ -> 2 end _ -> 0 end divcount(n, d + 1, count + divs) end   def ...
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Erlang
Erlang
divcount(N) -> divcount(N, 1, 0).   divcount(N, D, Count) when D*D > N -> Count; divcount(N, D, Count) -> Divs = case N rem D of 0 -> case N - D*D of 0 -> 1; _ -> 2 end; _ -> 0 end, divcount(N, D + 1, Count + Divs).     antiprimes(N) ->...
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 t...
#Phix
Phix
without js -- (no threads or critical sections in JavaScript) constant nBuckets = 20 sequence buckets = tagset(nBuckets) -- {1,2,3,..,20} constant bucket_cs = init_cs() -- critical section atom equals = 0, rands = 0 -- operation counts integer terminate = 0 -- control flag...
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Modula-3
Modula-3
<*ASSERT a = 42*>
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Nanoquery
Nanoquery
a = 5 assert (a = 42)
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Nemerle
Nemerle
assert (foo == 42, $"foo == $foo, not 42.")
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#NGS
NGS
a = 42   assert(a==42) assert(a, 42) assert(a==42, "Not 42!") assert(a, 42, "Not 42!")
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Common_Lisp
Common Lisp
(map nil #'print #(1 2 3 4 5))
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Component_Pascal
Component Pascal
  MODULE Callback; IMPORT StdLog;   TYPE Callback = PROCEDURE (x: INTEGER;OUT doubled: INTEGER); Callback2 = PROCEDURE (x: INTEGER): INTEGER;   PROCEDURE Apply(proc: Callback; VAR x: ARRAY OF INTEGER); VAR i: INTEGER; BEGIN FOR i := 0 TO LEN(x) - 1 DO; proc(x[i],x[i]); END END Apply;   PROCEDURE Apply2(...
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 appropriat...
#Perl
Perl
use strict; use List::Util qw(max);   sub mode { my %c; foreach my $e ( @_ ) { $c{$e}++; } my $best = max(values %c); return grep { $c{$_} == $best } keys %c; }
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#EchoLisp
EchoLisp
  (lib 'hash) ;; load hash.lib (define H (make-hash)) ;; fill hash table (hash-set H 'Simon 42) (hash-set H 'Albert 666) (hash-set H 'Antoinette 33)   ;; iterate over (key . value ) pairs (for ([kv H]) (writeln kv)) (Simon . 42) (Albert . 666) (Antoinette . 33)   ;; iterate over keys (for ([k (hash-keys H)]...
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 Filt...
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   ( 1.00000000 -2.77555756e-16 3.33333333e-01 -1.85037171e-17 ) var a ( 0.16666667 0.5 0.5 0.16666667 ) var b ( -0.917843918645 0.141984778794 1.20536903482 0.190286794412 -0.662370894973 -1.00700480494 -0.404707073677 0.800482325044 0.743500089861 ...
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 Filt...
#Python
Python
#!/bin/python from __future__ import print_function from scipy import signal import matplotlib.pyplot as plt   if __name__=="__main__": sig = [-0.917843918645,0.141984778794,1.20536903482,0.190286794412,-0.662370894973,-1.00700480494, -0.404707073677,0.800482325044,0.743500089861,1.01090520172,0.741527555207, 0.27...
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 conveyin...
#Erlang
Erlang
mean([]) -> 0; mean(L) -> lists:sum(L)/erlang:length(L).
http://rosettacode.org/wiki/Average_loop_length
Average loop length
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t...
#Simula
Simula
BEGIN   REAL PROCEDURE FACTORIAL(N); INTEGER N; BEGIN REAL RESULT; INTEGER I; RESULT := 1.0; FOR I := 2 STEP 1 UNTIL N DO RESULT := RESULT * I; FACTORIAL := RESULT; END FACTORIAL;   REAL PROCEDURE ANALYTICAL (N); INTEGER N; BEGIN REAL SUM, RN; INTEGER I;...
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 t...
#Tcl
Tcl
# Generate a list of the numbers increasing from $a to $b proc range {a b} { for {set result {}} {$a <= $b} {incr a} {lappend result $a} return $result }   # Computing the expected value analytically proc tcl::mathfunc::factorial n {  ::tcl::mathop::* {*}[range 2 $n] } proc Analytical {n} { set sum 0.0 ...
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 avera...
#TI-89_BASIC
TI-89 BASIC
movinavg(list,p) Func Local r, i, z   For i,1,dim(list) max(i-p,0)→z sum(mid(list,z+1,i-z))/(i-z)→r[i] EndFor r EndFunc    
http://rosettacode.org/wiki/Attractive_numbers
Attractive numbers
A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show sequence items up to   120....
#Nim
Nim
import strformat   const MAX = 120   proc isPrime(n: int): bool = var d = 5 if n < 2: return false if n mod 2 == 0: return n == 2 if n mod 3 == 0: return n == 3 while d * d <= n: if n mod d == 0: return false inc d, 2 if n mod d == 0: return false inc d, 4 return true...
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....
#Objeck
Objeck
class AttractiveNumber { function : Main(args : String[]) ~ Nil { max := 120; "The attractive numbers up to and including {$max} are:"->PrintLine();   count := 0; for(i := 1; i <= max; i += 1;) { n := CountPrimeFactors(i); if(IsPrime(n)) { " {$i}"->Print(); if(++count %...
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 ...
#Racket
Racket
  #lang racket (define (mean-angle/radians as) (define n (length as)) (atan (* (/ 1 n) (for/sum ([αj as]) (sin αj))) (* (/ 1 n) (for/sum ([αj as]) (cos αj))))) (define (mean-time times) (define secs/day (* 60 60 24)) (define (time->deg time) (/ (for/fold ([sum 0]) ([t (map string->number (string-spl...
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 ...
#Raku
Raku
sub tod2rad($_) { [+](.comb(/\d+/) Z* 3600,60,1) * tau / 86400 }   sub rad2tod ($r) { my $x = $r * 86400 / tau; (($x xx 3 Z/ 3600,60,1) Z% 24,60,60).fmt('%02d',':'); }   sub phase ($c) { $c.polar[1] }   sub mean-time (@t) { rad2tod phase [+] map { cis tod2rad $_ }, @t }   my @times = ["23:00:17", "23:40:20", "0...
http://rosettacode.org/wiki/AVL_tree
AVL tree
This page uses content from Wikipedia. The original article was at AVL tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In computer science, an AVL tree is a self-balancing binary search tree....
#TypeScript
TypeScript
/** A single node in an AVL tree */ class AVLnode <T> { balance: number left: AVLnode<T> right: AVLnode<T>   constructor(public key: T, public parent: AVLnode<T> = null) { this.balance = 0 this.left = null this.right = null } }   /** The balanced AVL tree */ class AVLtree <T>...
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 ...
#Python
Python
>>> from cmath import rect, phase >>> from math import radians, degrees >>> def mean_angle(deg): ... return degrees(phase(sum(rect(1, radians(d)) for d in deg)/len(deg))) ... >>> for angles in [[350, 10], [90, 180, 270, 360], [10, 20, 30]]: ... print('The mean angle of', angles, 'is:', round(mean_angle(angles)...
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 ...
#R
R
  deg2rad <- function(x) { x * pi/180 }   rad2deg <- function(x) { x * 180/pi }   deg2vec <- function(x) { c(sin(deg2rad(x)), cos(deg2rad(x))) }   vec2deg <- function(x) { res <- rad2deg(atan2(x[1], x[2])) if (res < 0) { 360 + res } else { res } }   mean_vec <- function(x) { y <- lapply(x, deg2v...
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 ...
#HicEst
HicEst
REAL :: n=10, vec(n)   vec = RAN(1) SORT(Vector=vec, Sorted=vec) ! in-place Merge-Sort   IF( MOD(n,2) ) THEN ! odd n median = vec( CEILING(n/2) ) ELSE median = ( vec(n/2) + vec(n/2 + 1) ) / 2 ENDIF
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#Lua
Lua
function fsum(f, a, ...) return a and f(a) + fsum(f, ...) or 0 end function pymean(t, f, finv) return finv(fsum(f, unpack(t)) / #t) end nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}   --arithmetic a = pymean(nums, function(n) return n end, function(n) return n end) --geometric g = pymean(nums, math.log, math.exp) --harmonic h...
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" ...
#Tcl
Tcl
package require Tcl 8.5   proc bt-int b { set n 0 foreach c [split $b ""] { set n [expr {$n * 3}] switch -- $c { + { incr n 1 } - { incr n -1 } } } return $n } proc int-bt n { if {$n == 0} { return "0" } while {$n != 0} { lappend result [lindex {0 + -} [expr {$n % 3}]] set n...
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....
#Shen
Shen
(define babbage N -> N where (= 269696 (shen.mod (* N N) 1000000))) N -> (babbage (+ N 1))   (babbage 1)
http://rosettacode.org/wiki/Babbage_problem
Babbage problem
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p....
#Sidef
Sidef
var n = 0 while (n*n % 1000000 != 269696) { n += 2 } say n
http://rosettacode.org/wiki/Approximate_equality
Approximate equality
Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the difference in floating point calculations between different language implementations becomes significant. For example, a difference between 32 bit and 64 bit floating point calculations may appear by about the 8t...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Runtime.CompilerServices   Module Module1   <Extension()> Function ApproxEquals(ByVal value As Double, other As Double, epsilon As Double) Return Math.Abs(value - other) < epsilon End Function   Sub Test(a As Double, b As Double) Dim epsilon = 1.0E-18 Console.Write...
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 8t...
#Wren
Wren
var tol = 1e-16 var pairs = [ [100000000000000.01, 100000000000000.011], [100.01, 100.011], [10000000000000.001 / 10000.0, 1000000000.0000001000], [0.001, 0.0010000001], [0.000000000000000000000101, 0.0], [2.sqrt * 2.sqrt, 2.0], [-2.sqrt * 2.sqrt, -2.0], [3.14159265358979323846, 3.141592...
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) ...
#Euphoria
Euphoria
function check_brackets(sequence s) integer level level = 0 for i = 1 to length(s) do if s[i] = '[' then level += 1 elsif s[i] = ']' then level -= 1 if level < 0 then return 0 end if end if end for return level =...
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,...
#J
J
require'strings ~system/packages/misc/xenos.ijs' record=: [:|: <@deb;._1@(':',]);._2@do bind '0 :0'   passfields=: <;._1':username:password:gid:uid:gecos:home:shell'   passrec=: LF,~ [: }.@;@ , ':';"0 (passfields i. {. ) { a:,~ {:   R1=: passrec record'' username: jsmith password: x gid: 1001 uid: 1000 g...
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 ins...
#BaCon
BaCon
DECLARE associative ASSOC STRING   associative("abc") = "first three" associative("xyz") = "last three"   PRINT associative("xyz")
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#F.23
F#
  // Find Antı-Primes. Nigel Galloway: Secember 10th., 2018 let N=200000000000000000000000000I let fI,_=Seq.scan(fun (_,g) e->(e,e*g)) (2I,4I) (primes|>Seq.skip 1|>Seq.map bigint)|>Seq.takeWhile(fun(_,n)->n<N)|>List.ofSeq|>List.unzip let fG g=Seq.unfold(fun ((n,i,e) as z)->Some(z,(n+1,i+1,(e*g)))) (1,2,g)|>Seq.takeWhi...
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 t...
#PicoLisp
PicoLisp
(seed (in "/dev/urandom" (rd 8)))   (de *Buckets . 15) # Number of buckets   # E/R model (class +Bucket +Entity) (rel key (+Key +Number)) # Key 1 .. *Buckets (rel val (+Number)) # Value 1 .. 999   # Create new DB file (pool (tmp "buckets.db"))   # Create *Buckets buckets with values between 1 and 999 (for K...
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 t...
#PureBasic
PureBasic
#Buckets=9 #TotalAmount=200 Global Dim Buckets(#Buckets) Global BMutex=CreateMutex() Global Quit=#False   Procedure max(x,y) If x>=y: ProcedureReturn x Else: ProcedureReturn y EndIf EndProcedure   Procedure Move(WantedAmount, From, Dest) Protected RealAmount If from<>Dest LockMutex(BMutex) RealAm...
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Nim
Nim
var a = 42 assert(a == 42, "Not 42!")
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Oberon-2
Oberon-2
  MODULE Assertions; VAR a: INTEGER; BEGIN a := 40; ASSERT(a = 42); END Assertions.  
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Objeck
Objeck
class Test { function : Main(args : String[]) ~ Nil { if(args->Size() = 1) { a := args[0]->ToInt(); Runtime->Assert(a = 42); }; } }  
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Crystal
Crystal
values = [1, 2, 3]   new_values = values.map do |number| number * 2 end   puts new_values #=> [2, 4, 6]
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#D
D
import std.stdio, std.algorithm;   void main() { auto items = [1, 2, 3, 4, 5]; auto m = items.map!(x => x + 5)(); writeln(m); }
http://rosettacode.org/wiki/Averages/Mode
Averages/Mode
Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat...
#Phix
Phix
function mode(sequence s) -- returns a list of the most common values, each of which occurs the same number of times integer nxt = 1, count = 1, maxc = 1 sequence res = {} if length(s)!=0 then s = sort(s) object prev = s[1] for i=2 to length(s) do if s[i]!=prev then ...
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 ...
#Elena
Elena
import system'collections; import system'routines; import extensions;   public program() { // 1. Create var map := Dictionary.new(); map["key"] := "foox"; map["key"] := "foo"; map["key2"]:= "foo2"; map["key3"]:= "foo3"; map["key4"]:= "foo4";   // Enumerate map.forEach: (keyVa...
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 ...
#Elixir
Elixir
IO.inspect d = Map.new([foo: 1, bar: 2, baz: 3]) Enum.each(d, fn kv -> IO.inspect kv end) Enum.each(d, fn {k,v} -> IO.puts "#{inspect k} => #{v}" end) Enum.each(Map.keys(d), fn key -> IO.inspect key end) Enum.each(Map.values(d), fn value -> IO.inspect value end)
http://rosettacode.org/wiki/Apply_a_digital_filter_(direct_form_II_transposed)
Apply a digital filter (direct form II transposed)
Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [1] Task Filt...
#Racket
Racket
#lang racket   (define a (vector 1.00000000E0 -2.77555756E-16 3.33333333E-01 -1.85037171E-17)) (define b (vector 0.16666667E0 0.50000000E0 0.50000000E0 0.16666667E0)) (define s (vector -0.917843918645 0.141984778794 1.20536903482 0.190286794412 -0.662370894973 -1.00700480494 -0.404707073677 0.800...
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 Filt...
#Raku
Raku
sub TDF-II-filter ( @signal, @a, @b ) { my @out = 0 xx @signal; for ^@signal -> $i { my $this; $this += @b[$_] * @signal[$i-$_] if $i-$_ >= 0 for ^@b; $this -= @a[$_] * @out[$i-$_] if $i-$_ >= 0 for ^@a; @out[$i] = $this / @a[0]; } @out }   my @signal = [ -0.917843...
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 conveyin...
#Euphoria
Euphoria
function mean(sequence s) atom sum if length(s) = 0 then return 0 else sum = 0 for i = 1 to length(s) do sum += s[i] end for return sum/length(s) end if end function   sequence test test = {1.0, 2.0, 5.0, -5.0, 9.5, 3.14159} ? mean(test)
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#Excel
Excel
=AVERAGE(A1:A10)
http://rosettacode.org/wiki/Average_loop_length
Average loop length
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t...
#Unicon
Unicon
link printf, factors   $define MAX_N 20 $define TIMES 1000000 $define RAND_MAX 2147483647   procedure expected(n) local sum := 0 every i := 1 to n do sum +:= factorial(n) / (n ^ i) / factorial(n - i) return sum end   procedure test(n, times) local i, count := 0, x, bits every i := 0 to times...
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 t...
#VBA
VBA
Const MAX = 20 Const ITER = 1000000   Function expected(n As Long) As Double Dim sum As Double For i = 1 To n sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i) Next i expected = sum End Function   Function test(n As Long) As Double Dim count As Long Dim x As L...
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 avera...
#VBA
VBA
Class sma 'to be stored in a class module with name "sma" Private n As Integer 'period Private arr() As Double 'circular list Private index As Integer 'pointer into arr Private oldsma As Double   Public Sub init(size As Integer) n = size ReDim arr(n - 1) index = 0 End Sub   Public Function sma(number As Dou...
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....
#Pascal
Pascal
program AttractiveNumbers; { numbers with count of factors = prime * using modified sieve of erathosthes * by adding the power of the prime to multiples * of the composite number } {$IFDEF FPC} {$MODE DELPHI} {$ELSE} {$APPTYPE CONSOLE} {$ENDIF} uses sysutils;//timing const cTextMany = ' with many factors '...
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 ...
#REXX
REXX
/* REXX --------------------------------------------------------------- * 25.06.2014 Walter Pachl * taken from ooRexx using my very aged sin/cos/artan functions *--------------------------------------------------------------------*/ times='23:00:17 23:40:20 00:12:45 00:17:19' sum=0 day=86400 pi=3.1415926535897932384626...
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....
#Wren
Wren
class Node { construct new(key, parent) { _key = key _parent = parent _balance = 0 _left = null _right = null }   key { _key } parent { _parent } balance { _balance } left { _left } right { _right }   key=(k) { _key = k ...
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 ...
#Racket
Racket
  #lang racket   (define (mean-angle αs) (radians->degrees (mean-angle/radians (map degrees->radians αs))))   (define (mean-angle/radians αs) (define n (length αs)) (atan (* (/ 1 n) (for/sum ([α_j αs]) (sin α_j))) (* (/ 1 n) (for/sum ([α_j αs]) (cos α_j)))))   (mean-angle '(350 0 10)) (mean-angle '...
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 ...
#Raku
Raku
# Of course, you can still use pi and 180. sub deg2rad { $^d * tau / 360 } sub rad2deg { $^r * 360 / tau }   sub phase ($c) { my ($mag,$ang) = $c.polar; return NaN if $mag < 1e-16; $ang; }   sub meanAngle { rad2deg phase [+] map { cis deg2rad $_ }, @^angles }   say meanAngle($_).fmt("%.2f\tis the mean angl...
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 ...
#Icon_and_Unicon
Icon and Unicon
procedure main(args) write(median(args)) end   procedure median(A) A := sort(A) n := *A return if n % 2 = 1 then A[n/2+1] else (A[n/2]+A[n/2+1])/2.0 | 0 # 0 if empty list end
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#J
J
require 'stats/base' median 1 9 2 4 3
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { sum=lambda -> { Read m as array if len(m)=0 then =0 : exit sum=Array(m, Dimension(m,0)) If len(m)=1 then =sum : exit k=each(m,2,-1) While k { sum+=Array(k) } =sum ...
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" ...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Text   Module Module1 Sub Main() Dim a As New BalancedTernary("+-0++0+") Console.WriteLine("a: {0} = {1}", a, a.ToLong) Dim b As New BalancedTernary(-436) Console.WriteLine("b: {0} = {1}", b, b.ToLong) Dim c As New BalancedTernary("+-++-") Console.Write...
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....
#Simula
Simula
BEGIN INTEGER PROBE, SQUARE; BOOLEAN DONE;   WHILE NOT DONE DO BEGIN PROBE := PROBE + 1; SQUARE := PROBE * PROBE; IF MOD(SQUARE, 1000000) = 269696 THEN BEGIN   OUTTEXT("THE SMALLEST NUMBER: "); OUTINT(PROBE,0); OUTIMAGE;   OUTTEXT("THE ...
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....
#Smalltalk
Smalltalk
"We use one variable, called n. Let it initially be equal to 1. Then keep increasing it by 1 for only as long as the remainder after dividing by a million is not equal to 269,696; finally, show the value of n." | n | n := 1. [ n squared \\ 1000000 = 269696 ] whileFalse: [ n := n + 1 ]. n
http://rosettacode.org/wiki/Approximate_equality
Approximate equality
Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the difference in floating point calculations between different language implementations becomes significant. For example, a difference between 32 bit and 64 bit floating point calculations may appear by about the 8t...
#XPL0
XPL0
func ApproxEqual(A, B); \Return 'true' if approximately equal real A, B; real Epsilon; [Epsilon:= abs(A) * 1E-15; return abs(A-B) < Epsilon; ];   real Data; int I; [Format(0, 16); Data:=[ [100000000000000.01, 100000000000000.011], \should return true [100.01, 100.011], ...
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 8t...
#zkl
zkl
testValues:=T( T(100000000000000.01,100000000000000.011), T(100.01, 100.011), T(10000000000000.001 / 10000.0, 1000000000.0000001), T(0.001, 0.0010000001), T(0.00000000000000000101, 0.0), T( (2.0).sqrt()*(2.0).sqrt(), 2.0), T( -(2.0).sqrt()*(2.0).sqrt(), -2.0), T(100000000000000003.0, 10000000...
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) ...
#Excel
Excel
bracketReport =LAMBDA(bracketPair, LAMBDA(s, LET( depths, SCANLCOLS( LAMBDA(depth, charDelta, depth + charDelta ) )(0)( codesFromBrackets(bracketPair)( MID(s, SEQUENCE(1,...
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file
Append a record to the end of a text file
Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. This feature is most useful in the case of log files,...
#Java
Java
import static java.util.Objects.requireNonNull;   import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; impo...
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 ins...
#BASIC256
BASIC256
global values$, keys$ dim values$[1] dim keys$[1]   call updateKey("a","apple") call updateKey("b","banana") call updateKey("c","cucumber")   gosub show   print "I like to eat a " + getValue$("c") + " on my salad."   call deleteKey("b") call updateKey("c","carrot") call updateKey("e","endive") gosub show   end   show: ...
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Factor
Factor
USING: assocs formatting kernel locals make math math.primes.factors sequences.extras ; IN: rosetta-code.anti-primes   <PRIVATE   : count-divisors ( n -- m ) dup 1 = [ group-factors values [ 1 + ] map-product ] unless ;   : (n-anti-primes) ( md n count -- ?md' n' ?count' ) dup 0 > [| max-div! n count! | ...
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Forth
Forth
  include ./factors.fs   : max-count ( n1 n2 -- n f ) \ n is max(n1, factor-count n2); if n is new maximum then f = true. \ count-factors 2dup < if nip true else drop false then ;   : .anti-primes ( n -- ) 0 1 rot \ stack: max, candidate, count begin >r dup >r max-count ...
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 t...
#Python
Python
from __future__ import with_statement # required for Python 2.5 import threading import random import time   terminate = threading.Event()   class Buckets: def __init__(self, nbuckets): self.nbuckets = nbuckets self.values = [random.randrange(10) for i in range(nbuckets)] self.lock = threadi...
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Objective-C
Objective-C
NSAssert(a == 42, @"Error message");
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#OCaml
OCaml
let a = get_some_value () in assert (a = 42); (* throws Assert_failure when a is not 42 *) (* evaluate stuff to return here when a is 42 *)