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/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.
#Processing
Processing
// Lines that begin with two slashes, thus, are comments: they // will be ignored by the machine.   // First we must declare a variable, n, suitable to store an integer:   int n;   // Each statement we address to the machine must end with a semicolon.   // To begin with, the value of n will be zero:   n = 0;   // Now we must repeatedly increase it by one, checking each time to see // whether its square ends in 269,696.   // We shall do this by seeing whether the remainder, when n squared // is divided by one million, is equal to 269,696.   do { n = n + 1; } while (n * n % 1000000 != 269696);   // To read this formula, it is necessary to know the following // elements of the notation: // * means 'multiplied by' //  % means 'modulo', or remainder after division //  != means 'is not equal to'   // Now that we have our result, we need to display it.   // println is short for 'print line'   println(n);
http://rosettacode.org/wiki/Approximate_equality
Approximate equality
Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the difference in floating point calculations between different language implementations becomes significant. For example, a difference between 32 bit and 64 bit floating point calculations may appear by about the 8th significant digit in base 10 arithmetic. Task Create a function which returns true if two floating point numbers are approximately equal. The function should allow for differences in the magnitude of numbers, so that, for example, 100000000000000.01   may be approximately equal to   100000000000000.011, even though   100.01   is not approximately equal to   100.011. If the language has such a feature in its standard library, this may be used instead of a custom function. Show the function results with comparisons on the following pairs of values:     100000000000000.01,   100000000000000.011     (note: should return true)     100.01,   100.011                                                     (note: should return false)     10000000000000.001 / 10000.0,   1000000000.0000001000     0.001,   0.0010000001     0.000000000000000000000101,   0.0      sqrt(2) * sqrt(2),    2.0     -sqrt(2) * sqrt(2),   -2.0     3.14159265358979323846,   3.14159265358979324 Answers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.
#Groovy
Groovy
class Approximate { private static boolean approxEquals(double value, double other, double epsilon) { return Math.abs(value - other) < epsilon }   private static void test(double a, double b) { double epsilon = 1e-18 System.out.printf("%f, %f => %s\n", a, b, approxEquals(a, b, epsilon)) }   static void main(String[] args) { test(100000000000000.01, 100000000000000.011) test(100.01, 100.011) test(10000000000000.001 / 10000.0, 1000000000.0000001000) test(0.001, 0.0010000001) test(0.000000000000000000000101, 0.0) test(Math.sqrt(2.0) * Math.sqrt(2.0), 2.0) test(-Math.sqrt(2.0) * Math.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.
#Haskell
Haskell
class (Num a, Ord a, Eq a) => AlmostEq a where eps :: a   infix 4 ~= (~=) :: AlmostEq a => a -> a -> Bool a ~= b = or [ a == b , abs (a - b) < eps * abs(a + b) , abs (a - b) < eps ]   instance AlmostEq Int where eps = 0 instance AlmostEq Integer where eps = 0 instance AlmostEq Double where eps = 1e-14 instance AlmostEq Float where eps = 1e-5
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
#CLU
CLU
% This program needs the random number generator from % "misc.lib" that comes with PCLU.   shuffle = proc [T: type] (a: array[t]) aT = array[t] for i: int in int$from_to_by(aT$size(a)-1,0,-1) do x: int := aT$low(a) + i y: int := aT$low(a) + random$next(i+1) temp: T := a[x] a[x] := a[y] a[y] := temp end end shuffle   brackets = proc (n: int) returns (string) br: array[char] := array[char]$[] for i: int in int$from_to(1,2*n) do if i<=n then array[char]$addh(br, '[') else array[char]$addh(br, ']') end end shuffle[char](br) return(string$ac2s(br)) end brackets   balanced = proc (br: string) returns (bool) depth: int := 0 for c: char in string$chars(br) do if c='[' then depth := depth + 1 elseif c=']' then depth := depth - 1 end if depth<0 then return(false) end end return(depth = 0) end balanced   start_up = proc () po: stream := stream$primary_output() d: date := now() random$seed(d.second + 60*(d.minute + 60*d.hour))   for size: int in int$from_to(0, 10) do b: string := brackets(size) stream$puts(po, "\"" || b || "\": ") if balanced(b) then stream$putl(po, "balanced") else stream$putl(po, "not balanced") end end end start_up
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.
#Batch_File
Batch File
  @echo off   ( echo jsmith:x:1001:1000:Joe Smith,Room 1007,^(234^)555-8917,^(234^)555-0077,[email protected]:/home/jsmith:/bin/bash echo jdoe:x:1002:1000:Jane Doe,Room 1004,^(234^)555-8914,^(234^)555-0044,[email protected]:/home/jdoe:/bin/bash ) > append.txt   echo Current contents of append.txt: type append.txt echo.   echo xyz:x:1003:1000:X Yz,Room 1003,^(234^)555-8913,^(234^)555-0033,[email protected]:/home/xyz:/bin/bash >> append.txt   echo New contents of append.txt: type append.txt pause>nul  
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.
#C
C
#include <stdio.h> #include <string.h> /* note that UID & GID are of type "int" */ typedef const char *STRING; typedef struct{STRING fullname, office, extension, homephone, email; } gecos_t; typedef struct{STRING account, password; int uid, gid; gecos_t gecos; STRING directory, shell; } passwd_t;   #define GECOS_FMT "%s,%s,%s,%s,%s" #define PASSWD_FMT "%s:%s:%d:%d:"GECOS_FMT":%s:%s"   passwd_t passwd_list[]={ {"jsmith", "x", 1001, 1000, /* UID and GID are type int */ {"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"} };   main(){ /**************************** * Create a passwd text file * ****************************/ FILE *passwd_text=fopen("passwd.txt", "w"); int rec_num; for(rec_num=0; rec_num < sizeof passwd_list/sizeof(passwd_t); rec_num++) fprintf(passwd_text, PASSWD_FMT"\n", passwd_list[rec_num]); fclose(passwd_text);   /******************************** * Load text ready for appending * ********************************/ passwd_text=fopen("passwd.txt", "a+"); char passwd_buf[BUFSIZ]; /* warning: fixed length */ passwd_t new_rec = {"xyz", "x", 1003, 1000, /* UID and GID are type int */ {"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "[email protected]"}, "/home/xyz", "/bin/bash"}; sprintf(passwd_buf, PASSWD_FMT"\n", new_rec); /* An atomic append without a file lock, Note: wont work on some file systems, eg NFS */ write(fileno(passwd_text), passwd_buf, strlen(passwd_buf)); close(passwd_text);   /*********************************************** * Finally reopen and check record was appended * ***********************************************/ passwd_text=fopen("passwd.txt", "r"); while(!feof(passwd_text)) fscanf(passwd_text, "%[^\n]\n", passwd_buf, "\n"); if(strstr(passwd_buf, "xyz")) printf("Appended record: %s\n", passwd_buf); }
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
#Aikido
Aikido
  var names = {} // empty map names["foo"] = "bar" names[3] = 4   // initialized map var names2 = {"foo": bar, 3:4}   // lookup map var name = names["foo"] if (typeof(name) == "none") { println ("not found") } else { println (name) }   // remove from map delete names["foo"]      
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
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program antiprime64.s */   /************************************/ /* Constantes */ /************************************/ .include "../includeConstantesARM64.inc"   .equ NMAXI, 20 .equ MAXLINE, 5 /*********************************/ /* Initialized data */ /*********************************/ .data sMessResult: .asciz " @ " szCarriageReturn: .asciz "\n" /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 /*********************************/ /* code section */ /*********************************/ .text .global main main: // entry of program ldr x3,qNMaxi // load limit mov x5,#0 // maxi mov x6,#0 // result counter mov x7,#0 // display counter mov x4,#1 // number begin 1: mov x0,x4 // number bl decFactor // compute number factors cmp x0,x5 // maxi ? cinc x4,x4,le // no -> increment indice //addle x4,x4,#1 // no -> increment indice ble 1b // and loop mov x5,x0 mov x0,x4 bl displayResult add x7,x7,#1 // increment display counter cmp x7,#MAXLINE // line maxi ? blt 2f mov x7,#0 ldr x0,qAdrszCarriageReturn bl affichageMess // display message 2: add x6,x6,#1 // increment result counter add x4,x4,#1 // increment number cmp x6,x3 // end ? blt 1b   100: // standard end of the program mov x0, #0 // return code mov x8,EXIT svc #0 // perform the system call qAdrszCarriageReturn: .quad szCarriageReturn qNMaxi: .quad NMAXI /***************************************************/ /* display message number */ /***************************************************/ /* x0 contains number 1 */ /* x1 contains number 2 */ displayResult: stp x1,lr,[sp,-16]! // save registers ldr x1,qAdrsZoneConv bl conversion10 // call décimal conversion ldr x0,qAdrsMessResult ldr x1,qAdrsZoneConv // insert conversion in message bl strInsertAtCharInc   bl affichageMess // display message ldp x1,lr,[sp],16 // restaur registers ret qAdrsMessResult: .quad sMessResult qAdrsZoneConv: .quad sZoneConv /***************************************************/ /* compute factors sum */ /***************************************************/ /* x0 contains the number */ decFactor: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers stp x4,x5,[sp,-16]! // save registers mov x5,#0 // init number factors mov x4,x0 // save number mov x1,#1 // start factor -> divisor 1: mov x0,x4 // dividende udiv x2,x0,x1 msub x3,x2,x1,x0 cmp x1,x2 // divisor > quotient ? bgt 3f cmp x3,#0 // remainder = 0 ? bne 2f add x5,x5,#1 // increment counter factors cmp x1,x2 // divisor = quotient ? beq 3f // yes -> end add x5,x5,#1 // no -> increment counter factors 2: add x1,x1,#1 // increment factor b 1b // and loop 3: mov x0,x5 // return counter ldp x4,x5,[sp],16 // restaur registers ldp x2,x3,[sp],16 // restaur registers ldp x1,lr,[sp],16 // restaur registers ret /***************************************************/ /* ROUTINES INCLUDE */ /***************************************************/ .include "../includeARM64.inc"  
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
#Action.21
Action!
BYTE FUNC CountDivisors(INT a) INT i BYTE prod,count   prod=1 count=0 WHILE a MOD 2=0 DO count==+1 a==/2 OD prod==*(1+count)   i=3 WHILE i*i<=a DO count=0 WHILE a MOD i=0 DO count==+1 a==/i OD prod==*(1+count) i==+2 OD   IF a>2 THEN prod==*2 FI RETURN (prod)   PROC Main() BYTE toFind=[20],found=[0],count,max=[0] INT i=[1]   PrintF("The first %B Anti-primes are:%E",toFind) WHILE found<toFind DO count=CountDivisors(i) IF count>max THEN max=count found==+1 PrintI(i) IF found<toFind THEN Print(", ") FI FI i==+1 OD RETURN
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.
#FreeBASIC
FreeBASIC
Randomize Timer Dim Shared As Uinteger cubo(1 To 10), a, i For i As Uinteger = 1 To 10 cubo(i) = Int(Rnd * 90) Next i   Function Display(cadena As String) As Uinteger Dim As Uinteger valor Print cadena; Spc(2); For i As Uinteger = 1 To 10 valor += cubo(i) Print Using "###"; cubo(i); Next i Print " Total:"; valor Return valor End Function   Sub Flatten(f As Uinteger) Dim As Uinteger f1 = Int((f / 10) + .5), f2 For i As Uinteger = 1 To 10 cubo(i) = f1 f2 += f1 Next i cubo(10) += f - f2 End Sub   Sub Transfer(a1 As Uinteger, a2 As Uinteger) Dim As Uinteger temp = Int(Rnd * cubo(a1)) cubo(a1) -= temp cubo(a2) += temp End Sub   a = Display(" Display:") ' show original array Flatten(a) ' flatten the array a = Display(" Flatten:") ' show flattened array Transfer(3, 5) ' transfer some amount from 3 to 5 Display(" 19 from 3 to 5:") ' show transfer array Sleep
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.
#Dyalect
Dyalect
var x = 42 assert(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.
#E
E
require(a == 42) # default message, "Required condition failed"   require(a == 42, "The Answer is Wrong.") # supplied message   require(a == 42, fn { `Off by ${a - 42}.` }) # computed only on failure
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.
#EchoLisp
EchoLisp
  (assert (integer? 42)) → #t ;; success returns true   ;; error and return to top level if not true; (assert (integer? 'quarante-deux)) ⛔ error: assert : assertion failed : (#integer? 'quarante-deux)   ;; assertion with message (optional) (assert (integer? 'quarante-deux) "☝️ expression must evaluate to the integer 42") 💥 error: ☝️ expression must evaluate to the integer 42 : assertion failed : (#integer? 'quarante-deux)  
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.
#Ada
Ada
with Ada.Text_Io; with Ada.Integer_text_IO;   procedure Call_Back_Example is -- Purpose: Apply a callback to an array -- Output: Prints the squares of an integer array to the console   -- Define the callback procedure procedure Display(Location : Positive; Value : Integer) is begin Ada.Text_Io.Put("array("); Ada.Integer_Text_Io.Put(Item => Location, Width => 1); Ada.Text_Io.Put(") = "); Ada.Integer_Text_Io.Put(Item => Value * Value, Width => 1); Ada.Text_Io.New_Line; end Display;   -- Define an access type matching the signature of the callback procedure type Call_Back_Access is access procedure(L : Positive; V : Integer);   -- Define an unconstrained array type type Value_Array is array(Positive range <>) of Integer;   -- Define the procedure performing the callback procedure Map(Values : Value_Array; Worker : Call_Back_Access) is begin for I in Values'range loop Worker(I, Values(I)); end loop; end Map;   -- Define and initialize the actual array Sample : Value_Array := (5,4,3,2,1);   begin Map(Sample, Display'access); end Call_Back_Example;
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
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { \\ find mode Function GetMode { Inventory N Inventory ALLMODES m=1 While not empty { if islet then { Read A$ if Exist(N, A$) then { k=Eval(N) k++ if m=k then { Append ALLMODES, A$ } if m<k then m=k : Clear ALLMODES : Append ALLMODES, A$ return N, A$:=k } Else Append N, A$:=1 : if m=1 then Append ALLMODES, A$   } else { Read A if Exist(N, A) then { k=Eval(N) k++ if m=k then { Append ALLMODES, A } if m<k then m=k : Clear ALLMODES : Append ALLMODES, A return N, A:=k } Else Append N, A:=1 : if m=1 then Append ALLMODES, A } } =ALLMODES } Print GetMode(1, 2, 3, 1, 2, 4, 2, 5, 2, 3, 3, 1, 3, 6) ' print 2 3 Dim A() A()=(1, 2, 3, 1, 2, 4, 2, 5, 2, 3, 3, 1, 3, 6) \\ get a pointer from A m=A() Print GetMode(!m) ' print 2 3 z=stack:=1, 2,"B", 3, 1, 2, "B", 4, 2, 5,"B", 2, 3, 3, 1, 3, 6, "B" Print GetMode(!z) ' print 2 3 B } Checkit  
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
#Maple
Maple
Statistics:-Mode([1, 2.1, 2.1, 3]); Statistics:-Mode([1, 2.1, 2.1, 3.2, 3.2, 5]);
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
#BASIC256
BASIC256
REM Store some values with their keys: PROCputdict(mydict$, "FF0000", "red") PROCputdict(mydict$, "00FF00", "green") PROCputdict(mydict$, "0000FF", "blue")   REM Iterate through the dictionary: i% = 1 REPEAT i% = FNdict(mydict$, i%, v$, k$) PRINT v$, k$ UNTIL i% = 0 END   DEF PROCputdict(RETURN dict$, value$, key$) IF dict$ = "" dict$ = CHR$(0) dict$ += key$ + CHR$(1) + value$ + CHR$(0) ENDPROC   DEF FNdict(dict$, I%, RETURN value$, RETURN key$) LOCAL J%, K% J% = INSTR(dict$, CHR$(1), I%) K% = INSTR(dict$, CHR$(0), J%) value$ = MID$(dict$, I%+1, J%-I%-1) key$ = MID$(dict$, J%+1, K%-J%-1) IF K% >= LEN(dict$) THEN K% = 0 = K%
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
#BBC_BASIC
BBC BASIC
REM Store some values with their keys: PROCputdict(mydict$, "FF0000", "red") PROCputdict(mydict$, "00FF00", "green") PROCputdict(mydict$, "0000FF", "blue")   REM Iterate through the dictionary: i% = 1 REPEAT i% = FNdict(mydict$, i%, v$, k$) PRINT v$, k$ UNTIL i% = 0 END   DEF PROCputdict(RETURN dict$, value$, key$) IF dict$ = "" dict$ = CHR$(0) dict$ += key$ + CHR$(1) + value$ + CHR$(0) ENDPROC   DEF FNdict(dict$, I%, RETURN value$, RETURN key$) LOCAL J%, K% J% = INSTR(dict$, CHR$(1), I%) K% = INSTR(dict$, CHR$(0), J%) value$ = MID$(dict$, I%+1, J%-I%-1) key$ = MID$(dict$, J%+1, K%-J%-1) IF K% >= LEN(dict$) THEN K% = 0 = K%
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]
#Common_Lisp
Common Lisp
(defparameter a #(1.00000000L0 -2.77555756L-16 3.33333333L-01 -1.85037171L-17)) (defparameter b #(0.16666667L0 0.50000000L0 0.50000000L0 0.16666667L0)) (defparameter s #(-0.917843918645 0.141984778794 1.20536903482 0.190286794412 -0.662370894973 -1.00700480494 -0.404707073677 0.800482325044 0.743500089861 1.01090520172 0.741527555207 0.277841675195 0.400833448236 -0.2085993586 -0.172842103641 -0.134316096293 0.0259303398477 0.490105989562 0.549391221511 0.9047198589))   (loop with out = (make-array (length s) :initial-element 0.0D0) for i below (length s) do (setf (svref out i) (/ (- (loop for j below (length b) when (>= i j) sum (* (svref b j) (svref s (- i j)))) (loop for j below (length a) when (>= i j) sum (* (svref a j) (svref out (- i j))))) (svref a 0))) (format t "~%~16,8F" (svref out i)))
http://rosettacode.org/wiki/Apply_a_digital_filter_(direct_form_II_transposed)
Apply a digital filter (direct form II transposed)
Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [1] Task Filter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667] The signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]
#D
D
import std.stdio;   alias T = real; alias AT = T[];   AT filter(const AT a, const AT b, const AT signal) { AT result = new T[signal.length];   foreach (int i; 0..signal.length) { T tmp = 0.0; foreach (int j; 0..b.length) { if (i-j<0) continue; tmp += b[j] * signal[i-j]; } foreach (int j; 1..a.length) { if (i-j<0) continue; tmp -= a[j] * result[i-j]; } tmp /= a[0]; result[i] = tmp; }   return result; }   void main() { AT a = [1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17]; AT b = [0.16666667, 0.5, 0.5, 0.16666667];   AT 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 ];   AT result = filter(a,b,signal); foreach (i; 0..result.length) { writef("% .8f", result[i]); if ((i+1)%5 != 0) { write(", "); } else { writeln; } } }
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
#BQN
BQN
Avg ← +´÷≠   Avg 1‿2‿3‿4
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
#C
C
#include <stdio.h>   double mean(double *v, int len) { double sum = 0; int i; for (i = 0; i < len; i++) sum += v[i]; return sum / len; }   int main(void) { double v[] = {1, 2, 2.718, 3, 3.142}; int i, len; for (len = 5; len >= 0; len--) { printf("mean["); for (i = 0; i < len; i++) printf(i ? ", %g" : "%g", v[i]); printf("] = %g\n", mean(v, len)); }   return 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
#Lua
Lua
base = {name="Rocket Skates", price=12.75, color="yellow"} update = {price=15.25, color="red", year=1974}   --[[ clone the base data ]]-- result = {} for key,val in pairs(base) do result[key] = val end   --[[ copy in the update data ]]-- for key,val in pairs(update) do result[key] = val end   --[[ print the result ]]-- for key,val in pairs(result) do print(string.format("%s: %s", key, val)) end
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
a1 = <|"name" -> "Rocket Skates", "price" -> 12.75, "color" -> "yellow"|>; a2 = <|"price" -> 15.25, "color" -> "red", "year" -> 1974|>; Merge[{a1, a2}, Last]
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
#MiniScript
MiniScript
base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"} update = {"price":15.25, "color":"red", "year":1974}   result = base + update   print result
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%)
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Grid@Prepend[ Table[{n, #[[1]], #[[2]], Row[{Round[10000 Abs[#[[1]] - #[[2]]]/#[[2]]]/100., "%"}]} &@ N[{Mean[Array[ Length@NestWhileList[#, 1, UnsameQ[##] &, All] - 1 &[# /. MapIndexed[#2[[1]] -> #1 &, RandomInteger[{1, n}, n]] &] &, 10000]], Sum[n! n^(n - k - 1)/(n - k)!, {k, n}]/n^(n - 1)}, 5], {n, 1, 20}], {"N", "average", "analytical", "error"}]
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%)
#Nim
Nim
import random, math, strformat randomize()   const maxN = 20 times = 1_000_000   proc factorial(n: int): float = result = 1 for i in 1 .. n: result *= i.float   proc expected(n: int): float = for i in 1 .. n: result += factorial(n) / pow(n.float, i.float) / factorial(n - i)   proc test(n, times: int): int = for i in 1 .. times: var x = 1 bits = 0 while (bits and x) == 0: inc result bits = bits or x x = 1 shl rand(n - 1)   echo " n\tavg\texp.\tdiff" echo "-------------------------------" for n in 1 .. maxN: let cnt = test(n, times) let avg = cnt.float / times let theory = expected(n) let diff = (avg / theory - 1) * 100 echo fmt"{n:2} {avg:8.4f} {theory:8.4f} {diff:6.3f}%"
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%)
#Oberon-2
Oberon-2
  MODULE AvgLoopLen; (* Oxford Oberon-2 *) IMPORT Random, Out;   PROCEDURE Fac(n: INTEGER; f: REAL): REAL; BEGIN IF n = 0 THEN RETURN f ELSE RETURN Fac(n - 1,n*f) END END Fac;   PROCEDURE Power(n,i: INTEGER): REAL; VAR p: REAL; BEGIN p := 1.0; WHILE i > 0 DO p := p * n; DEC(i) END; RETURN p END Power;   PROCEDURE Abs(x: REAL): REAL; BEGIN IF x < 0 THEN RETURN -x ELSE RETURN x END END Abs;   PROCEDURE Analytical(n: INTEGER): REAL; VAR i: INTEGER; res: REAL; BEGIN res := 0.0; FOR i := 1 TO n DO res := res + (Fac(n,1.0) / Power(n,i) / Fac(n - i,1.0)); END; RETURN res END Analytical;   PROCEDURE Averages(n: INTEGER): REAL; CONST times = 100000; VAR rnds: SET; r,count,i: INTEGER; BEGIN count := 0; i := 0; WHILE i < times DO rnds := {}; LOOP r := Random.Roll(n); IF r IN rnds THEN EXIT ELSE INCL(rnds,r); INC(count) END END; INC(i) END;   RETURN count / times END Averages;   VAR i: INTEGER; av,an,df: REAL; BEGIN Random.Randomize; Out.String(" Averages Analytical Diff% ");Out.Ln; FOR i := 1 TO 20 DO Out.Int(i,3); Out.String(": "); av := Averages(i);an := Analytical(i);df := Abs(av - an) / an * 100.0; Out.Fixed(av,10,4);Out.Fixed(an,11,4);Out.Fixed(df,10,4);Out.Ln END END AvgLoopLen.  
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
#REXX
REXX
/*REXX program illustrates and displays a simple moving average using a constructed list*/ parse arg p q n . /*obtain optional arguments from the CL*/ if p=='' | p=="," then p= 3 /*Not specified? Then use the default.*/ if q=='' | q=="," then q= 5 /* " " " " " " */ if n=='' | n=="," then n= 10 /* " " " " " " */ @.= 0 /*default value, only needed for odd N.*/ do j=1 for n%2; @.j= j /*build 1st half of list, increasing #s*/ end /*j*/   do k=n%2 by -1 to 1; @.j= k; j= j+1 /* " 2nd " " " decreasing " */ end /*k*/ say ' number ' " SMA with period" p' ' " SMA with period" q say ' ──────── ' "───────────────────" '───────────────────' pad=' ' do m=1 for n; say center(@.m, 10) pad left(SMA(p, m), 19) left(SMA(q, m), 19) end /*m*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ SMA: procedure expose @.; parse arg p,j; i= 0  ; $= 0 do k=max(1, j-p+1) to j+p for p while k<=j; i= i + 1; $= $ + @.k end /*k*/ return $/i /*SMA ≡ simple moving average. */
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.
#Go
Go
package main   import "fmt"   func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false } d += 2 if n%d == 0 { return false } d += 4 } return true } }   func countPrimeFactors(n int) int { switch { case n == 1: return 0 case isPrime(n): return 1 default: count, f := 0, 2 for { if n%f == 0 { count++ n /= f if n == 1 { return count } if isPrime(n) { f = n } } else if f >= 3 { f += 2 } else { f = 3 } } return count } }   func main() { const max = 120 fmt.Println("The attractive numbers up to and including", max, "are:") count := 0 for i := 1; i <= max; i++ { n := countPrimeFactors(i) if isPrime(n) { fmt.Printf("%4d", i) count++ if count % 20 == 0 { fmt.Println() } } } fmt.Println() }
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
#Lua
Lua
  local times = {"23:00:17","23:40:20","00:12:45","00:17:19"}   -- returns time converted to a radian format local function timeToAngle(str) local h,m,s = str:match("(..):(..):(..)") return (h + m / 60 + s / 3600)/12 * math.pi end   -- computes the mean of the angles inside a list local function meanAngle(angles) local sumSin,sumCos = 0,0 for k,v in pairs(angles) do sumSin = sumSin + math.sin(v) sumCos = sumCos + math.cos(v) end return math.atan2(sumSin,sumCos) end   -- converts and angle back to a time string local function angleToTime(angle) local abs = angle % (math.pi * 2) local time = abs / math.pi * 12 local h = math.floor(time) local m = math.floor(time * 60) % 60 local s = math.floor(time * 3600) % 60 return string.format("%02d:%02d:%02d", h, m, s) end   -- convert times to angles for k,v in pairs(times) do times[k] = timeToAngle(v) end   print(angleToTime(meanAngle(times)))  
http://rosettacode.org/wiki/AVL_tree
AVL tree
This page uses content from Wikipedia. The original article was at AVL tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In computer science, an AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; at no time do they differ by more than one because rebalancing is done ensure this is the case. Lookup, insertion, and deletion all take O(log n) time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations. Note the tree of nodes comprise a set, so duplicate node keys are not allowed. AVL trees are often compared with red-black trees because they support the same set of operations and because red-black trees also take O(log n) time for the basic operations. Because AVL trees are more rigidly balanced, they are faster than red-black trees for lookup-intensive applications. Similar to red-black trees, AVL trees are height-balanced, but in general not weight-balanced nor μ-balanced; that is, sibling nodes can have hugely differing numbers of descendants. Task Implement an AVL tree in the language of choice, and provide at least basic operations.
#Objeck
Objeck
class AVLNode { @key : Int; @balance : Int; @height : Int; @left : AVLNode; @right : AVLNode; @above : AVLNode;   New(key : Int, above : AVLNode) { @key := key; @above := above; }   method : public : GetKey() ~ Int { return @key; }   method : public : GetLeft() ~ AVLNode { return @left; }   method : public : GetRight() ~ AVLNode { return @right; }   method : public : GetAbove() ~ AVLNode { return @above; }   method : public : GetBalance() ~ Int { return @balance; }   method : public : GetHeight() ~ Int { return @height; }   method : public : SetBalance(balance : Int) ~ Nil { @balance := balance; }   method : public : SetHeight(height : Int) ~ Nil { @height := height; }   method : public : SetAbove(above : AVLNode) ~ Nil { @above := above; }   method : public : SetLeft(left : AVLNode) ~ Nil { @left := left; }   method : public : SetRight(right : AVLNode) ~ Nil { @right := right; }   method : public : SetKey(key : Int) ~ Nil { @key := key; } }   class AVLTree { @root : AVLNode;   New() {}   method : public : Insert(key : Int) ~ Bool { if(@root = Nil) { @root := AVLNode->New( key, Nil); return true; };   n := @root; while(true) { if(n->GetKey() = key) { return false; };   parent := n; goLeft := n->GetKey() > key; n := goLeft ? n->GetLeft() : n->GetRight();   if(n = Nil) { if(goLeft) { parent->SetLeft(AVLNode->New( key, parent)); } else { parent->SetRight(AVLNode->New( key, parent)); }; Rebalance(parent); break; }; };   return true; }   method : Delete(node : AVLNode) ~ Nil { if (node->GetLeft() = Nil & node->GetRight() = Nil) { if (node ->GetAbove() = Nil) { @root := Nil; } else { parent := node ->GetAbove(); if (parent->GetLeft() = node) { parent->SetLeft(Nil); } else { parent->SetRight(Nil); }; Rebalance(parent); }; return; };   if (node->GetLeft() <> Nil) { child := node->GetLeft(); while (child->GetRight() <> Nil) { child := child->GetRight(); }; node->SetKey(child->GetKey()); Delete(child); } else { child := node->GetRight(); while (child->GetLeft() <> Nil) { child := child->GetLeft(); }; node->SetKey(child->GetKey()); Delete(child); }; }   method : public : Delete(delKey : Int) ~ Nil { if (@root = Nil) { return; };   child := @root; while (child <> Nil) { node := child; child := delKey >= node->GetKey() ? node->GetRight() : node->GetLeft(); if (delKey = node->GetKey()) { Delete(node); return; }; }; }   method : Rebalance(n : AVLNode) ~ Nil { SetBalance(n);   if (n->GetBalance() = -2) { if (Height(n->GetLeft()->GetLeft()) >= Height(n->GetLeft()->GetRight())) { n := RotateRight(n); } else { n := RotateLeftThenRight(n); };   } else if (n->GetBalance() = 2) { if(Height(n->GetRight()->GetRight()) >= Height(n->GetRight()->GetLeft())) { n := RotateLeft(n); } else { n := RotateRightThenLeft(n); }; };   if(n->GetAbove() <> Nil) { Rebalance(n->GetAbove()); } else { @root := n; }; }   method : RotateLeft(a : AVLNode) ~ AVLNode { b := a->GetRight(); b->SetAbove(a->GetAbove());   a->SetRight(b->GetLeft());   if(a->GetRight() <> Nil) { a->GetRight()->SetAbove(a); };   b->SetLeft(a); a->SetAbove(b);   if (b->GetAbove() <> Nil) { if (b->GetAbove()->GetRight() = a) { b->GetAbove()->SetRight(b); } else { b->GetAbove()->SetLeft(b); }; };   SetBalance(a); SetBalance(b);   return b; }   method : RotateRight(a : AVLNode) ~ AVLNode { b := a->GetLeft(); b->SetAbove(a->GetAbove());   a->SetLeft(b->GetRight());   if (a->GetLeft() <> Nil) { a->GetLeft()->SetAbove(a); };   b->SetRight(a); a->SetAbove(b);   if (b->GetAbove() <> Nil) { if (b->GetAbove()->GetRight() = a) { b->GetAbove()->SetRight(b); } else { b->GetAbove()->SetLeft(b); }; };   SetBalance(a); SetBalance(b);   return b; }   method : RotateLeftThenRight(n : AVLNode) ~ AVLNode { n->SetLeft(RotateLeft(n->GetLeft())); return RotateRight(n); }   method : RotateRightThenLeft(n : AVLNode) ~ AVLNode { n->SetRight(RotateRight(n->GetRight())); return RotateLeft(n); }   method : SetBalance(n : AVLNode) ~ Nil { Reheight(n); n->SetBalance(Height(n->GetRight()) - Height(n->GetLeft())); }   method : Reheight(node : AVLNode) ~ Nil { if(node <> Nil) { node->SetHeight(1 + Int->Max(Height(node->GetLeft()), Height(node->GetRight()))); }; }   method : Height(n : AVLNode) ~ Int { if(n = Nil) { return -1; };   return n->GetHeight(); }   method : public : PrintBalance() ~ Nil { PrintBalance(@root); }   method : PrintBalance(n : AVLNode) ~ Nil { if (n <> Nil) { PrintBalance(n->GetLeft()); balance := n->GetBalance(); "{$balance} "->Print(); PrintBalance(n->GetRight()); }; } }   class Test { function : Main(args : String[]) ~ Nil { tree := AVLTree->New();   "Inserting values 1 to 10"->PrintLine(); for(i := 1; i < 10; i+=1;) { tree->Insert(i); };   "Printing balance: "->Print(); 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
#Kotlin
Kotlin
// version 1.0.5-2   fun meanAngle(angles: DoubleArray): Double { val sinSum = angles.sumByDouble { Math.sin(it * Math.PI / 180.0) } val cosSum = angles.sumByDouble { Math.cos(it * Math.PI / 180.0) } return Math.atan2(sinSum / angles.size, cosSum / angles.size) * 180.0 / Math.PI }   fun main(args: Array<String>) { val angles1 = doubleArrayOf(350.0, 10.0) val angles2 = doubleArrayOf(90.0, 180.0, 270.0, 360.0) val angles3 = doubleArrayOf(10.0, 20.0, 30.0) val fmt = "%.2f degrees" // format results to 2 decimal places println("Mean for angles 1 is ${fmt.format(meanAngle(angles1))}") println("Mean for angles 2 is ${fmt.format(meanAngle(angles2))}") println("Mean for angles 3 is ${fmt.format(meanAngle(angles3))}") }
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
#Liberty_BASIC
Liberty BASIC
global Pi Pi =3.1415926535   print "Mean Angle( "; chr$( 34); "350,10"; chr$( 34); ") = "; using( "###.#", meanAngle( "350,10")); " degrees." ' 0 print "Mean Angle( "; chr$( 34); "90,180,270,360"; chr$( 34); ") = "; using( "###.#", meanAngle( "90,180,270,360")); " degrees." ' -90 print "Mean Angle( "; chr$( 34); "10,20,30"; chr$( 34); ") = "; using( "###.#", meanAngle( "10,20,30")); " degrees." ' 20   end   function meanAngle( angles$) term =1 while word$( angles$, term, ",") <>"" angle =val( word$( angles$, term, ",")) sumSin = sumSin +sin( degRad( angle)) sumCos = sumCos +cos( degRad( angle)) term =term +1 wend meanAngle= radDeg( atan2( sumSin, sumCos)) if abs( sumSin) +abs( sumCos) <0.001 then notice "Not Available." +_ chr$( 13) +"(" +angles$ +")" +_ chr$( 13) +"Result nearly equals zero vector." +_ chr$( 13) +"Displaying '666'.": meanAngle =666   end function   function degRad( theta) degRad =theta *Pi /180 end function   function radDeg( theta) radDeg =theta *180 /Pi end function   function atan2( y, x) if x >0 then at =atn( y /x) if y >=0 and x <0 then at =atn( y /x) +pi if y <0 and x <0 then at =atn( y /x) -pi if y >0 and x =0 then at = pi /2 if y <0 and x =0 then at = 0 -pi /2 if y =0 and x =0 then notice "undefined": end atan2 =at end function
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
#EasyLang
EasyLang
func quickselect k . list[] res . # subr partition swap list[(left + right) / 2] list[left] mid = left for i = left + 1 to right if list[i] < list[left] mid += 1 swap list[i] list[mid] . . swap list[left] list[mid] . left = 0 right = len list[] - 1 while left < right call partition if mid < k left = mid + 1 elif mid > k right = mid - 1 else left = right . . res = list[k] . func median . list[] res . h = len list[] / 2 call quickselect h list[] res if len list[] mod 2 = 0 call quickselect h - 1 list[] h res = (res + h) / 2 . . test[] = [ 4.1 5.6 7.2 1.7 9.3 4.4 3.2 ] call median test[] med print med test[] = [ 4.1 7.2 1.7 9.3 4.4 3.2 ] call median test[] med print med
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
#EchoLisp
EchoLisp
  (define (median L) ;; O(n log(n)) (set! L (vector-sort! < (list->vector L))) (define dim (// (vector-length L) 2)) (if (integer? dim) (// (+ [L dim] [L (1- dim)]) 2) [L (floor dim)]))   (median '( 3 4 5)) → 4 (median '(6 5 4 3)) → 4.5 (median (iota 10000)) → 4999.5 (median (iota 10001)) → 5000  
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
#Icon_and_Unicon
Icon and Unicon
link numbers # for a/g/h means   procedure main() every put(x := [], 1 to 10) writes("x := [ "); every writes(!x," "); write("]")   write("Arithmetic mean:", a := amean!x) write("Geometric mean:",g := gmean!x) write("Harmonic mean:", h := hmean!x) write(" a >= g >= h is ", if a >= g >= h then "true" else "false") end  
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.
#OCaml
OCaml
type btdigit = Pos | Zero | Neg type btern = btdigit list   let to_string n = String.concat "" (List.rev_map (function Pos -> "+" | Zero -> "0" | Neg -> "-") n)   let from_string s = let sl = ref [] in let digit = function '+' -> Pos | '-' -> Neg | '0' -> Zero | _ -> failwith "invalid digit" in String.iter (fun c -> sl := (digit c) :: !sl) s; !sl   let rec to_int = function | [Zero] | [] -> 0 | Pos :: t -> 1 + 3 * to_int t | Neg :: t -> -1 + 3 * to_int t | Zero :: t -> 3 * to_int t   let rec from_int n = if n = 0 then [] else match n mod 3 with | 0 -> Zero :: from_int (n/3) | 1 | -2 -> Pos :: from_int ((n-1)/3) | 2 | -1 -> Neg :: from_int ((n+1)/3)   let rec (+~) n1 n2 = match (n1,n2) with | ([], a) | (a,[]) -> a | (Pos::t1, Neg::t2) | (Neg::t1, Pos::t2) | (Zero::t1, Zero::t2) -> let sum = t1 +~ t2 in if sum = [] then [] else Zero :: sum | (Pos::t1, Pos::t2) -> Neg :: t1 +~ t2 +~ [Pos] | (Neg::t1, Neg::t2) -> Pos :: t1 +~ t2 +~ [Neg] | (Zero::t1, h::t2) | (h::t1, Zero::t2) -> h :: t1 +~ t2   let neg = List.map (function Pos -> Neg | Neg -> Pos | Zero -> Zero) let (-~) a b = a +~ (neg b)   let rec ( *~) n1 = function | [] -> [] | [Pos] -> n1 | [Neg] -> neg n1 | Pos::t -> (Zero :: t *~ n1) +~ n1 | Neg::t -> (Zero :: t *~ n1) -~ n1 | Zero::t -> Zero :: t *~ n1   let a = from_string "+-0++0+" let b = from_int (-436) let c = from_string "+-++-" let d = a *~ (b -~ c) let _ = Printf.printf "a = %d\nb = %d\nc = %d\na * (b - c) = %s = %d\n" (to_int a) (to_int b) (to_int c) (to_string d) (to_int d);
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.
#Prolog
Prolog
:- use_module(library(clpfd)).   babbage_(B, B, Sq) :- B * B #= Sq, number_chars(Sq, R), append(_, ['2','6','9','6','9','6'], R). babbage_(B, R, Sq) :- N #= B + 1, babbage_(N, R, Sq).   babbage :- once(babbage_(1, Num, Square)), format('lowest number is ~p which squared becomes ~p~n', [Num, Square]).
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.
#J
J
  NB. default comparison tolerance matches the python result ".;._2]0 :0 100000000000000.01 = 100000000000000.011 100.01 = 100.011 (10000000000000.001 % 10000.0) = 1000000000.0000001000 0.001 = 0.0010000001 0.000000000000000000000101 = 0.0 (= ([: *~ %:)) 2 NB. sqrt(2)*sqrt(2) ((= -)~ ([: (* -) %:)) 2 NB. -sqrt(2) * sqrt(2), -2.0 3.14159265358979323846 = 3.14159265358979324 ) 1 0 1 0 0 1 1 1     NB. tolerance of 1e_12 matches the python result ".;._2]0 :0[CT=:1e_12 100000000000000.01 =!.CT 100000000000000.011 100.01 =!.CT 100.011 (10000000000000.001 % 10000.0) =!.CT 1000000000.0000001000 0.001 =!.CT 0.0010000001 0.000000000000000000000101 =!.CT 0.0 (=!.CT ([: *~ %:)) 2 NB. sqrt(2)*sqrt(2) ((=!.CT -)~ ([: (* -) %:)) 2 NB. -sqrt(2) * sqrt(2), -2.0 3.14159265358979323846 =!.CT 3.14159265358979324 ) 1 0 1 0 0 1 1 1     NB. tight tolerance ".;._2]0 :0[CT=:1e_18 100000000000000.01 =!.CT 100000000000000.011 100.01 =!.CT 100.011 (10000000000000.001 % 10000.0) =!.CT 1000000000.0000001000 0.001 =!.CT 0.0010000001 0.000000000000000000000101 =!.CT 0.0 (=!.CT ([: *~ %:)) 2 NB. sqrt(2)*sqrt(2) ((=!.CT -)~ ([: (* -) %:)) 2 NB. -sqrt(2) * sqrt(2), -2.0 3.14159265358979323846 =!.CT 3.14159265358979324 ) 1 0 0 0 0 0 0 1   2 (=!.1e_8) 9 |domain error | 2(=  !.1e_8)9  
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.
#Java
Java
public class Approximate { private static boolean approxEquals(double value, double other, double epsilon) { return Math.abs(value - other) < epsilon; }   private static void test(double a, double b) { double epsilon = 1e-18; System.out.printf("%f, %f => %s\n", a, b, approxEquals(a, b, epsilon)); }   public static void main(String[] args) { test(100000000000000.01, 100000000000000.011); test(100.01, 100.011); test(10000000000000.001 / 10000.0, 1000000000.0000001000); test(0.001, 0.0010000001); test(0.000000000000000000000101, 0.0); test(Math.sqrt(2.0) * Math.sqrt(2.0), 2.0); test(-Math.sqrt(2.0) * Math.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
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. test-balanced-brackets.   DATA DIVISION. WORKING-STORAGE SECTION. 01 True-Val CONSTANT 0. 01 False-Val CONSTANT 1.   LOCAL-STORAGE SECTION. 01 current-time PIC 9(10).   01 bracket-type PIC 9. 88 add-open-bracket VALUE 1.   01 bracket-string-area. 03 bracket-string PIC X(10) OCCURS 10 TIMES.   01 i PIC 999. 01 j PIC 999.   PROCEDURE DIVISION. *> Seed RANDOM(). MOVE FUNCTION CURRENT-DATE (7:10) TO current-time MOVE FUNCTION RANDOM(current-time) TO current-time     *> Generate random strings of brackets. PERFORM VARYING i FROM 1 BY 1 UNTIL 10 < i PERFORM VARYING j FROM 1 BY 1 UNTIL i < j COMPUTE bracket-type = FUNCTION REM(FUNCTION RANDOM * 1000, 2)   IF add-open-bracket MOVE "[" TO bracket-string (i) (j:1) ELSE MOVE "]" TO bracket-string (i) (j:1) END-IF END-PERFORM END-PERFORM   *> Display if the strings are balanced or not. PERFORM VARYING i FROM 1 BY 1 UNTIL 10 < i CALL "check-if-balanced" USING bracket-string (i) IF RETURN-CODE = True-Val DISPLAY FUNCTION TRIM(bracket-string (i)) " is balanced." ELSE DISPLAY FUNCTION TRIM(bracket-string (i)) " is not balanced." END-IF END-PERFORM   GOBACK .   END PROGRAM test-balanced-brackets.   IDENTIFICATION DIVISION. PROGRAM-ID. check-if-balanced.   DATA DIVISION. WORKING-STORAGE SECTION. 01 True-Val CONSTANT 0. 01 False-Val CONSTANT 1.   LOCAL-STORAGE SECTION. 01 nesting-level PIC S999. 01 i PIC 999.   LINKAGE SECTION. 01 bracket-string PIC X(100).   PROCEDURE DIVISION USING bracket-string. PERFORM VARYING i FROM 1 BY 1 UNTIL (100 < i) OR (bracket-string (i:1) = SPACE) OR (nesting-level < 0) IF bracket-string (i:1) = "[" ADD 1 TO nesting-level ELSE SUBTRACT 1 FROM nesting-level IF nesting-level < 0 MOVE False-Val TO RETURN-CODE GOBACK END-IF END-IF END-PERFORM   IF nesting-level = 0 MOVE True-Val TO RETURN-CODE ELSE MOVE False-Val TO RETURN-CODE END-IF   GOBACK .   END PROGRAM check-if-balanced.
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file
Append a record to the end of a text file
Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. This feature is most useful in the case of log files, where many jobs may be appending to the log file at the same time, or where care must be taken to avoid concurrently overwriting the same record from another job. Task Given a two record sample for a mythical "passwd" file: Write these records out in the typical system format. Ideally these records will have named fields of various types. Close the file, then reopen the file for append. Append a new record to the file and close the file again. Take appropriate care to avoid concurrently overwrites from another job. Open the file and demonstrate the new record has indeed written to the end. Source record field types and contents. account password UID GID fullname,office,extension,homephone,email directory shell string string int int struct(string,string,string,string,string) string string jsmith x 1001 1000 Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected] /home/jsmith /bin/bash jdoe x 1002 1000 Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected] /home/jdoe /bin/bash Record to be appended. account password UID GID fullname,office,extension,homephone,email directory shell string string int int struct(string,string,string,string,string) string string xyz x 1003 1000 X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected] /home/xyz /bin/bash Resulting file format: should mimic Linux's /etc/passwd file format with particular attention to the "," separator used in the GECOS field. But if the specific language has a particular or unique format of storing records in text file, then this format should be named and demonstrated with an additional example. Expected output: Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash Finally: Provide a summary of the language's "append record" capabilities in a table. eg. Append Capabilities. Data Representation IO Library Append Possible Automatic Append Multi-tasking Safe In core On disk C struct CSV text file glibc/stdio ☑ ☑ ☑ (Not all, eg NFS) Alternatively: If the language's appends can not guarantee its writes will always append, then note this restriction in the table. If possible, provide an actual code example (possibly using file/record locking) to guarantee correct concurrent appends.
#C.23
C#
using System; using System.IO;   namespace AppendPwdRosetta { class PasswordRecord { public string account, password, fullname, office, extension, homephone, email, directory, shell; public int UID, GID; public PasswordRecord(string account, string password, int UID, int GID, string fullname, string office, string extension, string homephone, string email, string directory, string shell) { this.account = account; this.password = password; this.UID = UID; this.GID = GID; this.fullname = fullname; this.office = office; this.extension = extension; this.homephone = homephone; this.email = email; this.directory = directory; this.shell = shell; } public override string ToString() { var gecos = string.Join(",", new string[] { fullname, office, extension, homephone, email }); return string.Join(":", new string[] { account, password, UID.ToString(), GID.ToString(), gecos, directory, shell }); } } class Program { static void Main(string[] args) { var jsmith = new PasswordRecord("jsmith", "x", 1001, 1000, "Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "[email protected]", "/home/jsmith", "/bin/bash"); var jdoe = new PasswordRecord("jdoe", "x", 1002, 1000, "Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "[email protected]", "/home/jdoe", "/bin/bash"); var xyz = new PasswordRecord("xyz", "x", 1003, 1000, "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "[email protected]", "/home/xyz", "/bin/bash");   // Write these records out in the typical system format. File.WriteAllLines("passwd.txt", new string[] { jsmith.ToString(), jdoe.ToString() });   // Append a new record to the file and close the file again. File.AppendAllText("passwd.txt", xyz.ToString());   // Open the file and demonstrate the new record has indeed written to the end. string[] lines = File.ReadAllLines("passwd.txt"); Console.WriteLine("Appended record: " + lines[2]); } } }  
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
#Aime
Aime
record r;
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
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Antiprimes is   function Count_Divisors (N : Integer) return Integer is Count : Integer := 1; begin for i in 1 .. N / 2 loop if N mod i = 0 then Count := Count + 1; end if; end loop; return Count; end Count_Divisors;   Results  : array (1 .. 20) of Integer; Candidate  : Integer := 1; Divisors  : Integer; Max_Divisors : Integer := 0;   begin for i in Results'Range loop loop Divisors := Count_Divisors (Candidate); if Max_Divisors < Divisors then Results (i)  := Candidate; Max_Divisors := Divisors; exit; end if; Candidate := Candidate + 1; end loop; end loop; Put_Line ("The first 20 anti-primes are:"); for I in Results'Range loop Put (Integer'Image (Results (I))); end loop; New_Line; end Antiprimes;
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
#ALGOL_68
ALGOL 68
BEGIN # find some anti-primes: numbers with more divisors than the # # previous numbers # INT max number := 10 000; INT max divisors := 0; # construct a table of the divisor counts # [ 1 : max number ]INT ndc; FOR i FROM 1 TO UPB ndc DO ndc[ i ] := 1 OD; FOR i FROM 2 TO UPB ndc DO FOR j FROM i BY i TO UPB ndc DO ndc[ j ] +:= 1 OD OD; # show the numbers with more divisors than their predecessors # INT a count := 0; FOR i TO UPB ndc WHILE a count < 20 DO INT divisor count = ndc[ i ]; IF divisor count > max divisors THEN print( ( " ", whole( i, 0 ) ) ); max divisors := divisor count; a count +:= 1 FI OD; print( ( newline ) ) 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.
#Go
Go
package main   import ( "fmt" "math/rand" "sync" "time" )   const nBuckets = 10   type bucketList struct { b [nBuckets]int // bucket data specified by task   // transfer counts for each updater, not strictly required by task but // useful to show that the two updaters get fair chances to run. tc [2]int   sync.Mutex // synchronization }   // Updater ids, to track number of transfers by updater. // these can index bucketlist.tc for example. const ( idOrder = iota idChaos )   const initialSum = 1000 // sum of all bucket values   // Constructor. func newBucketList() *bucketList { var bl bucketList // Distribute initialSum across buckets. for i, dist := nBuckets, initialSum; i > 0; { v := dist / i i-- bl.b[i] = v dist -= v } return &bl }   // method 1 required by task, get current value of a bucket func (bl *bucketList) bucketValue(b int) int { bl.Lock() // lock before accessing data r := bl.b[b] bl.Unlock() return r }   // method 2 required by task func (bl *bucketList) transfer(b1, b2, a int, ux int) { // Get access. bl.Lock() // Clamping maintains invariant that bucket values remain nonnegative. if a > bl.b[b1] { a = bl.b[b1] } // Transfer. bl.b[b1] -= a bl.b[b2] += a bl.tc[ux]++ // increment transfer count bl.Unlock() }   // additional useful method func (bl *bucketList) snapshot(s *[nBuckets]int, tc *[2]int) { bl.Lock() *s = bl.b *tc = bl.tc bl.tc = [2]int{} // clear transfer counts bl.Unlock() }   var bl = newBucketList()   func main() { // Three concurrent tasks. go order() // make values closer to equal go chaos() // arbitrarily redistribute values buddha() // display total value and individual values of each bucket }   // The concurrent tasks exercise the data operations by calling bucketList // methods. The bucketList methods are "threadsafe", by which we really mean // goroutine-safe. The conconcurrent tasks then do no explicit synchronization // and are not responsible for maintaining invariants.   // Exercise 1 required by task: make values more equal. func order() { r := rand.New(rand.NewSource(time.Now().UnixNano())) for { b1 := r.Intn(nBuckets) b2 := r.Intn(nBuckets - 1) if b2 >= b1 { b2++ } v1 := bl.bucketValue(b1) v2 := bl.bucketValue(b2) if v1 > v2 { bl.transfer(b1, b2, (v1-v2)/2, idOrder) } else { bl.transfer(b2, b1, (v2-v1)/2, idOrder) } } }   // Exercise 2 required by task: redistribute values. func chaos() { r := rand.New(rand.NewSource(time.Now().Unix())) for { b1 := r.Intn(nBuckets) b2 := r.Intn(nBuckets - 1) if b2 >= b1 { b2++ } bl.transfer(b1, b2, r.Intn(bl.bucketValue(b1)+1), idChaos) } }   // Exercise 3 requred by task: display total. func buddha() { var s [nBuckets]int var tc [2]int var total, nTicks int   fmt.Println("sum ---updates--- mean buckets") tr := time.Tick(time.Second / 10) for { <-tr bl.snapshot(&s, &tc) var sum int for _, l := range s { if l < 0 { panic("sob") // invariant not preserved } sum += l } // Output number of updates per tick and cummulative mean // updates per tick to demonstrate "as often as possible" // of task exercises 1 and 2. total += tc[0] + tc[1] nTicks++ fmt.Printf("%d %6d %6d %7d  %3d\n", sum, tc[0], tc[1], total/nTicks, s) if sum != initialSum { panic("weep") // invariant not preserved } } }
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.
#ECL
ECL
  ASSERT(a = 42,'A is not 42!',FAIL);
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.
#Eiffel
Eiffel
class MAIN creation main feature main is local test: TEST; do create test;   io.read_integer; test.assert(io.last_integer); end end
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Elixir
Elixir
ExUnit.start   defmodule AssertionTest do use ExUnit.Case   def return_5, do: 5   test "not equal" do assert 42 == return_5 end end
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.
#Aime
Aime
void map(list l, void (*fp)(object)) { l.ucall(fp, 0); }   void out(object o) { o_(o, "\n"); }   integer main(void) { list(0, 1, 2, 3).map(out);   return 0; }
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.
#ALGOL_68
ALGOL 68
PROC call back proc = (INT location, INT value)VOID: ( printf(($"array["g"] = "gl$, location, value)) );   PROC map = (REF[]INT array, PROC (INT,INT)VOID call back)VOID: ( FOR i FROM LWB array TO UPB array DO call back(i, array[i]) OD );   main: ( [4]INT array := ( 1, 4, 9, 16 ); map(array, call back proc) )
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Commonest[{b, a, c, 2, a, b, 1, 2, 3}] Commonest[{1, 3, 2, 3}]
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
#MATLAB
MATLAB
function modeValue = findmode(setOfValues) modeValue = mode(setOfValues); end
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
#Bracmat
Bracmat
( new$hash:?myhash & (myhash..insert)$(title."Some title") & (myhash..insert)$(formula.a+b+x^7) & (myhash..insert)$(fruit.apples oranges kiwis) & (myhash..insert)$(meat.) & (myhash..insert)$(fruit.melons bananas) & (myhash..remove)$formula & (myhash..insert)$(formula.x^2+y^2) & (myhash..forall) $ ( = key value . whl ' ( !arg:(?key.?value) ?arg & put$("key:" !key "\nvalue:" !value \n) ) & put$\n ) );
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
#Brat
Brat
h = [ hello: 1 world: 2 :! : 3]   #Iterate over key, value pairs h.each { k, v | p "Key: #{k} Value: #{v}" }   #Iterate over keys h.each_key { k | p "Key: #{k}" }   #Iterate over values h.each_value { v | p "Value: #{v}" }
http://rosettacode.org/wiki/Apply_a_digital_filter_(direct_form_II_transposed)
Apply a digital filter (direct form II transposed)
Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [1] Task Filter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667] The signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]
#FreeBASIC
FreeBASIC
Sub Filtro(a() As Double, b() As Double, senal() As Double, resultado() As Double) Dim As Integer j, k Dim As Double tmp   For j = 0 To Ubound(senal) tmp = 0 For k = 0 To Ubound(b) If (j-k < 0) Then Continue For tmp = tmp + b(k) * senal(j-k) Next k For k = 0 To Ubound(a) If (j-k < 0) Then Continue For tmp = tmp - a(k) * resultado(j-k) Next k tmp /= a(0) resultado(j) = tmp Next j End Sub   Dim Shared As Double a(4), b(4), senal(20), resultado(20) Dim As Integer i For i = 0 To 3 : Read a(i) : Next i For i = 0 To 3 : Read b(i) : Next i For i = 0 To 19 : Read senal(i) : Next i   Filtro(a(),b(),senal(),resultado())   For i = 0 To 19 Print Using "###.########"; resultado(i); If (i+1) Mod 5 <> 0 Then Print ", "; Else Print End If Next i   '' a() Data 1, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17 '' b() Data 0.16666667, 0.5, 0.5, 0.16666667 '' senal() Data -0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412 Data -0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044 Data 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195 Data 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293 Data 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589   Sleep
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
#C.23
C#
using System; using System.Linq;   class Program { static void Main() { Console.WriteLine(new[] { 1, 2, 3 }.Average()); } }
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
#C.2B.2B
C++
#include <vector>   double mean(const std::vector<double>& numbers) { if (numbers.size() == 0) return 0;   double sum = 0; for (std::vector<double>::iterator i = numbers.begin(); i != numbers.end(); i++) sum += *i; return sum / numbers.size(); }
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
#Nim
Nim
import tables   let t1 = {"name": "Rocket Skates", "price": "12.75", "color": "yellow"}.toTable let t2 = {"price": "15.25", "color": "red", "year": "1974"}.toTable   var t3 = t1 # Makes a copy. for key, value in t2.pairs: t3[key] = value   echo t3
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
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   int main(void) { @autoreleasepool { NSDictionary *base = @{@"name": @"Rocket Skates", @"price": @12.75, @"color": @"yellow"}; NSDictionary *update = @{@"price": @15.25, @"color": @"red", @"year": @1974};   NSMutableDictionary *result = [[NSMutableDictionary alloc] initWithDictionary:base]; [result addEntriesFromDictionary:update];   NSLog(@"%@", result); } return 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
#OCaml
OCaml
  type ty = | TFloat of float | TInt of int | TString of string   type key = string type assoc = string * ty   let string_of_ty : ty -> string = function | TFloat x -> string_of_float x | TInt i -> string_of_int i | TString s -> s   let print_pair key el = Printf.printf "%s: %s\n" key (string_of_ty el) ;;  
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%)
#PARI.2FGP
PARI/GP
expected(n)=sum(i=1,n,n!/(n-i)!/n^i,0.); test(n, times)={ my(ct); for(i=1,times, my(x=1,bits); while(!bitand(bits,x),ct++; bits=bitor(bits,x); x = 1<<random(n)) ); ct }; TIMES=1000000; {for(n=1,20, my(cnt=test(n, TIMES),avg=cnt/TIMES,ex=expected(n),diff=(avg/ex-1)*100.); print(n"\t"avg*1."\t"ex*1."\t"diff); )}
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%)
#Perl
Perl
use List::Util qw(sum reduce);   sub find_loop { my($n) = @_; my($r,@seen); while () { $seen[$r] = $seen[($r = int(1+rand $n))] ? return sum @seen : 1 } }   print " N empiric theoric (error)\n"; print "=== ========= ============ =========\n";   my $MAX = 20; my $TRIALS = 1000;   for my $n (1 .. $MAX) { my $empiric = ( sum map { find_loop($n) } 1..$TRIALS ) / $TRIALS; my $theoric = sum map { (reduce { $a*$b } $_**2, ($n-$_+1)..$n ) / $n ** ($_+1) } 1..$n;   printf "%3d  %9.4f  %12.4f (%5.2f%%)\n", $n, $empiric, $theoric, 100 * ($empiric - $theoric) / $theoric; }
http://rosettacode.org/wiki/Averages/Simple_moving_average
Averages/Simple moving average
Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is a method for computing an average of a stream of numbers by only averaging the last   P   numbers from the stream,   where   P   is known as the period. It can be implemented by calling an initialing routine with   P   as its argument,   I(P),   which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last   P   of them, lets call this   SMA(). The word   stateful   in the task description refers to the need for   SMA()   to remember certain information between calls to it:   The period,   P   An ordered container of at least the last   P   numbers from each of its individual calls. Stateful   also means that successive calls to   I(),   the initializer,   should return separate routines that do   not   share saved state so they could be used on two independent streams of data. Pseudo-code for an implementation of   SMA   is: function SMA(number: N): stateful integer: P stateful list: stream number: average stream.append_last(N) if stream.length() > P: # Only average the last P elements of the stream stream.delete_first() if stream.length() == 0: average = 0 else: average = sum( stream.values() ) / stream.length() return average See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#Ring
Ring
  load "stdlib.ring" decimals(8) maxperiod = 20 nums = newlist(maxperiod,maxperiod) accum = list(maxperiod) index = list(maxperiod) window = list(maxperiod) for i = 1 to maxperiod index[i] = 1 accum[i] = 0 window[i] = 0 next for i = 1 to maxperiod for j = 1 to maxperiod nums[i][j] = 0 next next for n = 1 to 5 see "number = " + n + " sma3 = " + left((string(sma(n,3)) + " "),9) + " sma5 = " + sma(n,5) + nl next for n = 5 to 1 step -1 see "number = " + n + " sma3 = " + left((string(sma(n,3)) + " "),9) + " sma5 = " + sma(n,5) + nl next see nl   func sma number, period accum[period] += number - nums[period][index[period]] nums[period][index[period]] = number index[period]= (index[period] + 1) % period + 1 if window[period]<period window[period] += 1 ok return (accum[period] / window[period])  
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.
#Groovy
Groovy
class AttractiveNumbers { static boolean isPrime(int n) { if (n < 2) return false if (n % 2 == 0) return n == 2 if (n % 3 == 0) return n == 3 int d = 5 while (d * d <= n) { if (n % d == 0) return false d += 2 if (n % d == 0) return false d += 4 } return true }   static int countPrimeFactors(int n) { if (n == 1) return 0 if (isPrime(n)) return 1 int count = 0, f = 2 while (true) { if (n % f == 0) { count++ n /= f if (n == 1) return count if (isPrime(n)) f = n } else if (f >= 3) f += 2 else f = 3 } }   static void main(String[] args) { final int max = 120 printf("The attractive numbers up to and including %d are:\n", max) int count = 0 for (int i = 1; i <= max; ++i) { int n = countPrimeFactors(i) if (isPrime(n)) { printf("%4d", i) if (++count % 20 == 0) println() } } println() } }
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
meanTime[list_] := StringJoin@ Riffle[ToString /@ Floor@{Mod[24 #, 24], Mod[24*60 #, 60], Mod[24*60*60 #, 60]} &[ Arg[Mean[ Exp[FromDigits[ToExpression@StringSplit[#, ":"], 60] & /@ list/(24*60*60) 2 Pi I]]]/(2 Pi)], ":"]; meanTime[{"23:00:17", "23:40:20", "00:12:45", "00:17:19"}]
http://rosettacode.org/wiki/Averages/Mean_time_of_day
Averages/Mean time of day
Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ideas of Averages/Mean angle compute and show the average time of the nocturnal activity to an accuracy of one second of time. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#MATLAB_.2F_Octave
MATLAB / Octave
function t = mean_time_of_day(t) c = pi/(12*60*60); for k=1:length(t) a = sscanf(t{k},'%d:%d:%d'); phi(k) = (a(1)*3600+a(2)*60+a(3)); end; d = angle(mean(exp(i*phi*c)))/(2*pi); % days if (d<0) d += 1; t = datestr(d,"HH:MM:SS"); 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.
#Objective-C
Objective-C
  @implementation AVLTree   -(BOOL)insertWithKey:(NSInteger)key {   if (self.root == nil) { self.root = [[AVLTreeNode alloc]initWithKey:key andParent:nil]; } else {   AVLTreeNode *n = self.root; AVLTreeNode *parent;   while (true) {   if (n.key == key) { return false; }   parent = n;   BOOL goLeft = n.key > key; n = goLeft ? n.left : n.right;   if (n == nil) {   if (goLeft) { parent.left = [[AVLTreeNode alloc]initWithKey:key andParent:parent]; } else { parent.right = [[AVLTreeNode alloc]initWithKey:key andParent:parent]; } [self rebalanceStartingAtNode:parent]; break; } } }   return true; }   -(void)rebalanceStartingAtNode:(AVLTreeNode*)n {   [self setBalance:@[n]];   if (n.balance == -2) { if ([self height:(n.left.left)] >= [self height:n.left.right]) { n = [self rotateRight:n]; } else { n = [self rotateLeftThenRight:n]; } } else if (n.balance == 2) { if ([self height:n.right.right] >= [self height:n.right.left]) { n = [self rotateLeft:n]; } else { n = [self rotateRightThenLeft:n]; } }   if (n.parent != nil) { [self rebalanceStartingAtNode:n.parent]; } else { self.root = n; } }     -(AVLTreeNode*)rotateRight:(AVLTreeNode*)a {   AVLTreeNode *b = a.left; b.parent = a.parent;   a.left = b.right;   if (a.left != nil) { a.left.parent = a; }   b.right = 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;   }   -(AVLTreeNode*)rotateLeftThenRight:(AVLTreeNode*)n {   n.left = [self rotateLeft:n.left]; return [self rotateRight:n];   }   -(AVLTreeNode*)rotateRightThenLeft:(AVLTreeNode*)n {   n.right = [self rotateRight:n.right]; return [self rotateLeft:n]; }   -(AVLTreeNode*)rotateLeft:(AVLTreeNode*)a {   //set a's right node as b AVLTreeNode* b = a.right; //set b's parent as a's parent (which could be nil) b.parent = a.parent; //in case b had a left child transfer it to a a.right = b.left;   // after changing a's reference to the right child, make sure the parent is set too if (a.right != nil) { a.right.parent = a; }   // switch a over to the left to be b's left child b.left = a; a.parent = b;   if (b.parent != nil) { if (b.parent.right == a) { b.parent.right = b; } else { b.parent.right = b; } }   [self setBalance:@[a,b]];   return b;   }       -(void) setBalance:(NSArray*)nodesArray {   for (AVLTreeNode* n in nodesArray) {   n.balance = [self height:n.right] - [self height:n.left]; }   }   -(int)height:(AVLTreeNode*)n {   if (n == nil) { return -1; }   return 1 + MAX([self height:n.left], [self height:n.right]); }   -(void)printKey:(AVLTreeNode*)n { if (n != nil) { [self printKey:n.left]; NSLog(@"%ld", n.key); [self printKey:n.right]; } }   -(void)printBalance:(AVLTreeNode*)n { if (n != nil) { [self printBalance:n.left]; NSLog(@"%ld", n.balance); [self printBalance:n.right]; } } @end -- test   int main(int argc, const char * argv[]) { @autoreleasepool {   AVLTree *tree = [AVLTree new]; NSLog(@"inserting values 1 to 6"); [tree insertWithKey:1]; [tree insertWithKey:2]; [tree insertWithKey:3]; [tree insertWithKey:4]; [tree insertWithKey:5]; [tree insertWithKey:6];   NSLog(@"printing balance: "); [tree printBalance:tree.root];   NSLog(@"printing key: "); [tree printKey:tree.root]; } return 0; }    
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
#Logo
Logo
to mean_angle :angles local "avgsin make "avgsin quotient apply "sum map "sin :angles count :angles local "avgcos make "avgcos quotient apply "sum map "cos :angles count :angles output (arctan :avgcos :avgsin) end   foreach [[350 10] [90 180 270 360] [10 20 30]] [ print (sentence [The average of \(] ? [\) is] (mean_angle ?)) ]   bye  
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
#Lua
Lua
function meanAngle (angleList) local sumSin, sumCos = 0, 0 for i, angle in pairs(angleList) do sumSin = sumSin + math.sin(math.rad(angle)) sumCos = sumCos + math.cos(math.rad(angle)) end local result = math.deg(math.atan2(sumSin, sumCos)) return string.format("%.2f", result) end   print(meanAngle({350, 10})) print(meanAngle({90, 180, 270, 360})) print(meanAngle({10, 20, 30}))
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches to this.   One is to sort the elements, and then pick the element(s) in the middle. Sorting would take at least   O(n logn).   Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s).   This would also take   O(n logn).   The best solution is to use the   selection algorithm   to find the median in   O(n)   time. See also Quickselect_algorithm Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#Elena
Elena
import system'routines; import system'math; import extensions;   extension op { get Median() { var sorted := self.ascendant();   var len := sorted.Length; if (len == 0) { ^ nil } else { var middleIndex := len / 2; if (len.mod:2 == 0) { ^ (sorted[middleIndex - 1] + sorted[middleIndex]) / 2 } else { ^ sorted[middleIndex] } } } }   public program() { var a1 := new real[]{4.1r, 5.6r, 7.2r, 1.7r, 9.3r, 4.4r, 3.2r}; var a2 := new real[]{4.1r, 7.2r, 1.7r, 9.3r, 4.4r, 3.2r};   console.printLine("median of (",a1.asEnumerable(),") is ",a1.Median); console.printLine("median of (",a2.asEnumerable(),") is ",a2.Median);   console.readChar() }
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
#Elixir
Elixir
defmodule Average do def median([]), do: nil def median(list) do len = length(list) sorted = Enum.sort(list) mid = div(len, 2) if rem(len,2) == 0, do: (Enum.at(sorted, mid-1) + Enum.at(sorted, mid)) / 2, else: Enum.at(sorted, mid) end end   median = fn list -> IO.puts "#{inspect list} => #{inspect Average.median(list)}" end median.([]) Enum.each(1..6, fn i -> (for _ <- 1..i, do: :rand.uniform(6)) |> median.() end)
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
#IS-BASIC
IS-BASIC
100 PROGRAM "Averages.bas" 110 NUMERIC ARR(1 TO 10) 120 FOR I=LBOUND(ARR) TO UBOUND(ARR) 130 LET ARR(I)=I 140 NEXT 150 PRINT "Arithmetic mean =";ARITHM(ARR) 160 PRINT "Geometric mean =";GEOMETRIC(ARR) 170 PRINT "Harmonic mean =";HARMONIC(ARR) 180 DEF ARITHM(REF A) 190 LET T=0 200 FOR I=LBOUND(A) TO UBOUND(A) 210 LET T=T+A(I) 220 NEXT 230 LET ARITHM=T/SIZE(A) 240 END DEF 250 DEF GEOMETRIC(REF A) 260 LET T=1 270 FOR I=LBOUND(A) TO UBOUND(A) 280 LET T=T*A(I) 290 NEXT 300 LET GEOMETRIC=T^(1/SIZE(A)) 310 END DEF 320 DEF HARMONIC(REF A) 330 LET T=0 340 FOR I=LBOUND(A) TO UBOUND(A) 350 LET T=T+(1/A(I)) 360 NEXT 370 LET HARMONIC=SIZE(A)/T 380 END DEF
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.
#Perl
Perl
use strict; use warnings;   my @d = qw( 0 + - ); my @v = qw( 0 1 -1 );   sub to_bt { my $n = shift; my $b = ''; while( $n ) { my $r = $n%3; $b .= $d[$r]; $n -= $v[$r]; $n /= 3; } return scalar reverse $b; }   sub from_bt { my $n = 0; for( split //, shift ) { # Horner $n *= 3; $n += "${_}1" if $_; } return $n; }   my %addtable = ( '-0' => [ '-', '' ], '+0' => [ '+', '' ], '+-' => [ '0', '' ], '00' => [ '0', '' ], '--' => [ '+', '-' ], '++' => [ '-', '+' ], );   sub add { my ($b1, $b2) = @_; return ($b1 or $b2 ) unless ($b1 and $b2); my $d = $addtable{ join '', sort substr( $b1, -1, 1, '' ), substr( $b2, -1, 1, '' ) }; return add( add($b1, $d->[1]), $b2 ).$d->[0]; }   sub unary_minus { my $b = shift; $b =~ tr/-+/+-/; return $b; }   sub subtract { my ($b1, $b2) = @_; return add( $b1, unary_minus $b2 ); }   sub mult { my ($b1, $b2) = @_; my $r = '0'; for( reverse split //, $b2 ){ $r = add $r, $b1 if $_ eq '+'; $r = subtract $r, $b1 if $_ eq '-'; $b1 .= '0'; } $r =~ s/^0+//; return $r; }   my $a = "+-0++0+"; my $b = to_bt( -436 ); my $c = "+-++-"; my $d = mult( $a, subtract( $b, $c ) ); printf " a: %14s %10d\n", $a, from_bt( $a ); printf " b: %14s %10d\n", $b, from_bt( $b ); printf " c: %14s %10d\n", $c, from_bt( $c ); printf "a*(b-c): %14s %10d\n", $d, from_bt( $d );  
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.
#PureBasic
PureBasic
EnableExplicit Macro putresult(n) If OpenConsole("Babbage_problem") PrintN("The smallest number whose square ends in 269696 is " + Str(n)) Input() EndIf EndMacro   CompilerIf #PB_Processor_x64 #MAXINT = 1 << 63 - 1 CompilerElseIf #PB_Processor_x86 #MAXINT = 1 << 31 - 1 CompilerEndIf   #GOAL = 269696 #DIV = 1000000 Define n.i, q.i = Int(Sqr(#MAXINT))   For n = 2 To q Step 2 If (n*n) % #DIV = #GOAL : putresult(n) : Break : EndIf Next
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.
#jq
jq
# 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)). def isclose(a; b; epsilon): ((a - b) | fabs) <= (([(a|fabs), (b|fabs)] | max) * epsilon);   def lpad($len; $fill): tostring | ($len - length) as $l | ($fill * $l)[:$l] + .;   def lpad: lpad(20; " ");   # test values def tv: [ {x: 100000000000000.01, y: 100000000000000.011 }, {x: 100.01, y: 100.011 }, {x: (10000000000000.001 / 10000.0), y: 1000000000.0000001000 }, {x: 0.001, y: 0.0010000001 }, {x: 0.000000000000000000000101, y: 0.0 }, {x: ((2|sqrt) * (2|sqrt)), y: 2.0 }, {x: (-(2|sqrt) * (2|sqrt)), y: -2.0 }, {x: 3.14159265358979323846, y: 3.14159265358979324 } ] ;   tv[] | "\(.x|lpad) \(if isclose(.x; .y; 1.0e-9) then " ≈ " else " ≉ " end) \(.y|lpad)"  
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.
#Julia
Julia
testvalues = [[100000000000000.01, 100000000000000.011], [100.01, 100.011], [10000000000000.001 / 10000.0, 1000000000.0000001000], [0.001, 0.0010000001], [0.000000000000000000000101, 0.0], [sqrt(2) * sqrt(2), 2.0], [-sqrt(2) * sqrt(2), -2.0], [3.14159265358979323846, 3.14159265358979324]]   for (x, y) in testvalues println(rpad(x, 21), " ≈ ", lpad(y, 22), ": ", x ≈ y) 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.
#Kotlin
Kotlin
import kotlin.math.abs import kotlin.math.sqrt   fun approxEquals(value: Double, other: Double, epsilon: Double): Boolean { return abs(value - other) < epsilon }   fun test(a: Double, b: Double) { val epsilon = 1e-18 println("$a, $b => ${approxEquals(a, b, epsilon)}") }   fun main() { test(100000000000000.01, 100000000000000.011) test(100.01, 100.011) test(10000000000000.001 / 10000.0, 1000000000.0000001000) test(0.001, 0.0010000001) test(0.000000000000000000000101, 0.0) test(sqrt(2.0) * sqrt(2.0), 2.0) test(-sqrt(2.0) * sqrt(2.0), -2.0) test(3.14159265358979323846, 3.14159265358979324) }
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
#CoffeeScript
CoffeeScript
  isBalanced = (brackets) -> openCount = 0 for bracket in brackets openCount += if bracket is '[' then 1 else -1 return false if openCount < 0 openCount is 0   bracketsCombinations = (n) -> for i in [0...Math.pow 2, n] str = i.toString 2 str = '0' + str while str.length < n str.replace(/0/g, '[').replace(/1/g, ']')   for brackets in bracketsCombinations 4 console.log brackets, isBalanced brackets  
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.
#C.2B.2B
C++
#include <iostream> #include <fstream> #include <string> #include <vector>   std::ostream& operator<<(std::ostream& out, const std::string s) { return out << s.c_str(); }   struct gecos_t { std::string fullname, office, extension, homephone, email;   friend std::ostream& operator<<(std::ostream&, const gecos_t&); };   std::ostream& operator<<(std::ostream& out, const gecos_t& g) { return out << g.fullname << ',' << g.office << ',' << g.extension << ',' << g.homephone << ',' << g.email; }   struct passwd_t { std::string account, password; int uid, gid; gecos_t gecos; std::string directory, shell;   passwd_t(const std::string& a, const std::string& p, int u, int g, const gecos_t& ge, const std::string& d, const std::string& s) : account(a), password(p), uid(u), gid(g), gecos(ge), directory(d), shell(s) { //empty }   friend std::ostream& operator<<(std::ostream&, const passwd_t&); };   std::ostream& operator<<(std::ostream& out, const passwd_t& p) { return out << p.account << ':' << p.password << ':' << p.uid << ':' << p.gid << ':' << p.gecos << ':' << p.directory << ':' << p.shell; }   std::vector<passwd_t> passwd_list{ { "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" } };   int main() { // Write the first two records std::ofstream out_fd("passwd.txt"); for (size_t i = 0; i < passwd_list.size(); ++i) { out_fd << passwd_list[i] << '\n'; } out_fd.close();   // Append the third record out_fd.open("passwd.txt", std::ios::app); out_fd << passwd_t("xyz", "x", 1003, 1000, { "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "[email protected]" }, "/home/xyz", "/bin/bash") << '\n'; out_fd.close();   // Verify the record was appended std::ifstream in_fd("passwd.txt"); std::string line, temp; while (std::getline(in_fd, temp)) { // the last line of the file is empty, make sure line contains the last record if (!temp.empty()) { line = temp; } } if (line.substr(0, 4) == "xyz:") { std::cout << "Appended record: " << line << '\n'; } else { std::cout << "Failed to find the expected record appended.\n"; }   return 0; }
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#ALGOL_68
ALGOL 68
main:(   MODE COLOR = BITS; FORMAT color repr = $"16r"16r6d$;   # This is an associative array which maps strings to ints # MODE ITEM = STRUCT(STRING key, COLOR value); REF[]ITEM color map items := LOC[0]ITEM;   PROC color map find = (STRING color)REF COLOR:( REF COLOR out; # linear search! # FOR index FROM LWB key OF color map items TO UPB key OF color map items DO IF color = key OF color map items[index] THEN out := value OF color map items[index]; GO TO found FI OD; NIL EXIT found: out );   PROC color map = (STRING color)REF COLOR:( REF COLOR out = color map find(color); IF out :=: REF COLOR(NIL) THEN # extend color map array # HEAP[UPB key OF color map items + 1]ITEM color map append; color map append[:UPB key OF color map items] := color map items; color map items := color map append; value OF (color map items[UPB value OF color map items] := (color, 16r000000)) # black # ELSE out FI );   # First, populate it with some values # color map("red") := 16rff0000; color map("green") := 16r00ff00; color map("blue") := 16r0000ff; color map("my favourite color") := 16r00ffff;   # then, get some values out # COLOR color := color map("green"); # color gets 16r00ff00 # color := color map("black"); # accessing unassigned values assigns them to 16r0 #   # get some value out without accidentally inserting new ones # REF COLOR value = color map find("green"); IF value :=: REF COLOR(NIL) THEN put(stand error, ("color not found!", new line)) ELSE printf(($"green: "f(color repr)l$, value)) FI;   # Now I changed my mind about my favourite color, so change it # color map("my favourite color") := 16r337733;   # print out all defined colors # FOR index FROM LWB color map items TO UPB color map items DO ITEM item = color map items[index]; putf(stand error, ($"color map("""g""") = "f(color repr)l$, item)) OD;   FORMAT fmt; FORMAT comma sep = $"("n(UPB color map items-1)(f(fmt)", ")f(fmt)")"$;   fmt := $""""g""""$; printf(($g$,"keys: ", comma sep, key OF color map items, $l$)); fmt := color repr; printf(($g$,"values: ", comma sep, value OF color map items, $l$))   )
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
#ALGOL_W
ALGOL W
begin  % find some anti-primes - numbers with more factors than the numbers  %  % smaller than them  %  % calculates the number of divisors of v  % integer procedure divisor_count( integer value v ) ; begin integer total, n, p; total := 1; n := v; while not odd( n ) do begin total := total + 1; n  := n div 2 end while_not_odd_n ; p := 3; while ( p * p ) <= n do begin integer count; count := 1; while n rem p = 0 do begin count := count + 1; n  := n div p end while_n_rem_p_eq_0 ; p  := p + 2; total := total * count end while_p_x_p_le_n ; if n > 1 then total := total * 2; total end divisor_count ; begin integer maxAntiPrime, antiPrimeCount, maxDivisors, n; maxAntiPrime := 20; n := maxDivisors := antiPrimeCount := 0; while antiPrimeCount < maxAntiPrime do begin integer divisors; n := n + 1; divisors := divisor_count( n ); if divisors > maxDivisors then begin writeon( i_w := 1, s_w := 0, " ", n ); maxDivisors  := divisors; antiPrimeCount := antiPrimeCount + 1 end if_have_an_anti_prime end while_antiPrimeCoiunt_lt_maxAntiPrime end end.
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#AppleScript
AppleScript
on factorCount(n) set counter to 0 set sqrt to n ^ 0.5 set limit to sqrt div 1 if (limit = sqrt) then set counter to counter + 1 set limit to limit - 1 end if repeat with i from limit to 1 by -1 if (n mod i is 0) then set counter to counter + 2 end repeat   return counter end factorCount   on antiprimes(howMany) set output to {} set mostFactorsSoFar to 0 set n to 0 repeat until ((count output) = howMany) set n to n + 1 tell (factorCount(n)) if (it > mostFactorsSoFar) then set end of output to n set mostFactorsSoFar to it end if end tell end repeat   return output end antiprimes   antiprimes(20)
http://rosettacode.org/wiki/Atomic_updates
Atomic updates
Task Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to: get the current value of any bucket remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the transferred amount to ensure the values remain non-negative In order to exercise this data type, create one set of buckets, and start three concurrent tasks: As often as possible, pick two buckets and make their values closer to equal. As often as possible, pick two buckets and arbitrarily redistribute their values. At whatever rate is convenient, display (by any means) the total value and, optionally, the individual values of each bucket. The display task need not be explicit; use of e.g. a debugger or trace tool is acceptable provided it is simple to set up to provide the display. This task is intended as an exercise in atomic operations.   The sum of the bucket values must be preserved even if the two tasks attempt to perform transfers simultaneously, and a straightforward solution is to ensure that at any time, only one transfer is actually occurring — that the transfer operation is atomic.
#Groovy
Groovy
class Buckets {   def cells = [] final n   Buckets(n, limit=1000, random=new Random()) { this.n = n (0..<n).each { cells << random.nextInt(limit) } }   synchronized getAt(i) { cells[i] }   synchronized transfer(from, to, amount) { assert from in (0..<n) && to in (0..<n) def cappedAmt = [cells[from], amount].min() cells[from] -= cappedAmt cells[to] += cappedAmt }   synchronized String toString() { cells.toString() } }   def random = new Random()   def buckets = new Buckets(5)   def makeCloser = { i, j -> synchronized(buckets) { def targetDiff = (buckets[i]-buckets[j]).intdiv(2) if (targetDiff < 0) { buckets.transfer(j, i, -targetDiff) } else { buckets.transfer(i, j, targetDiff) } } }   def randomize = { i, j -> synchronized(buckets) { def targetLimit = buckets[i] + buckets[j] def targetI = random.nextInt(targetLimit + 1) if (targetI < buckets[i]) { buckets.transfer(i, j, buckets[i] - targetI) } else { buckets.transfer(j, i, targetI - buckets[i]) } } }   Thread.start { def start = System.currentTimeMillis() while (start + 10000 > System.currentTimeMillis()) { def i = random.nextInt(buckets.n) def j = random.nextInt(buckets.n) makeCloser(i, j) } }   Thread.start { def start = System.currentTimeMillis() while (start + 10000 > System.currentTimeMillis()) { def i = random.nextInt(buckets.n) def j = random.nextInt(buckets.n) randomize(i, j) } }   def start = System.currentTimeMillis() while (start + 10000 > System.currentTimeMillis()) { synchronized(buckets) { def sum = buckets.cells.sum() println "${new Date()}: checksum: ${sum} buckets: ${buckets}" } Thread.sleep(500) }
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.
#Emacs_Lisp
Emacs Lisp
(require 'cl-lib) (let ((x 41)) (cl-assert (= x 42) t "This shouldn't happen"))
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.
#Erlang
Erlang
1> N = 42. 42 2> N = 43. ** exception error: no match of right hand side value 43 3> N = 42. 42 4> 44 = N. ** exception error: no match of right hand side value 42 5> 42 = 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.
#ALGOL_W
ALGOL W
begin procedure printSquare ( integer value x ) ; writeon( i_w := 1, s_w := 0, " ", x * x );  % applys f to each element of a from lb to ub (inclusive) % procedure applyI ( procedure f; integer array a ( * ); integer value lb, ub ) ; for i := lb until ub do f( a( i ) );  % test applyI % begin integer array a ( 1 :: 3 ); a( 1 ) := 1; a( 2 ) := 2; a( 3 ) := 3; applyI( printSquare, a, 1, 3 ) end end.
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.
#APL
APL
- 1 2 3 ¯1 ¯2 ¯3 2 * 1 2 3 4 2 4 8 16 2 × ⍳4 2 4 6 8 3 * 3 3 ⍴ ⍳9 3 9 27 81 243 729 2187 6561 19683  
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
#MUMPS
MUMPS
MODE(X)  ;X is assumed to be a list of numbers separated by "^"  ;I is a loop index  ;L is the length of X  ;Y is a new array  ;ML is the list of modes  ;LOC is a placeholder to shorten the statement Q:'$DATA(X) "No data" Q:X="" "Empty Set" NEW Y,I,L,LOC SET L=$LENGTH(X,"^"),ML="" FOR I=1:1:L SET LOC=+$P(X,"^",I),Y(LOC)=$S($DATA(Y(LOC)):Y(LOC)+1,1:1) SET I="",I=$O(Y(I)),ML=I ;Prime the pump, rather than test for no data FOR S I=$O(Y(I)) Q:I="" S ML=$SELECT(Y($P(ML,"^"))>Y(I):ML,Y($P(ML,"^"))<Y(I):I,Y($P(ML,"^"))=Y(I):ML_"^"_I) QUIT ML
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
#C
C
using System; using System.Collections.Generic;   namespace AssocArrays { class Program { static void Main(string[] args) {   Dictionary<string,int> assocArray = new Dictionary<string,int>();   assocArray["Hello"] = 1; assocArray.Add("World", 2); assocArray["!"] = 3;   foreach (KeyValuePair<string, int> kvp in assocArray) { Console.WriteLine(kvp.Key + " : " + kvp.Value); }   foreach (string key in assocArray.Keys) { Console.WriteLine(key); }   foreach (int val in assocArray.Values) { Console.WriteLine(val.ToString()); } } } }  
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]
#Go
Go
package main   import "fmt"   type filter struct { b, a []float64 }   func (f filter) filter(in []float64) []float64 { out := make([]float64, len(in)) s := 1. / f.a[0] for i := range in { tmp := 0. b := f.b if i+1 < len(b) { b = b[:i+1] } for j, bj := range b { tmp += bj * in[i-j] } a := f.a[1:] if i < len(a) { a = a[:i] } for j, aj := range a { tmp -= aj * out[i-j-1] } out[i] = tmp * s } return out }   //Constants for a Butterworth filter (order 3, low pass) var bwf = filter{ a: []float64{1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17}, b: []float64{0.16666667, 0.5, 0.5, 0.16666667}, }   var sig = []float64{ -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, }   func main() { for _, v := range bwf.filter(sig) { fmt.Printf("%9.6f\n", v) } }
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
#Chef
Chef
Mean.   Chef has no way to detect EOF, so rather than interpreting some arbitrary number as meaning "end of input", this program expects the first input to be the sample size. Pass in the samples themselves as the other inputs. For example, if you wanted to compute the mean of 10, 100, 47, you could pass in 3, 10, 100, and 47. To test the "zero-length vector" case, you need to pass in 0.   Ingredients. 0 g Sample Size 0 g Counter 0 g Current Sample   Method. Take Sample Size from refrigerator. Put Sample Size into mixing bowl. Fold Counter into mixing bowl. Put Current Sample into mixing bowl. Loop Counter. Take Current Sample from refrigerator. Add Current Sample into mixing bowl. Endloop Counter until looped. If Sample Size. Divide Sample Size into mixing bowl. Put Counter into 2nd mixing bowl. Fold Sample Size into 2nd mixing bowl. Endif until ifed. Pour contents of mixing bowl into baking dish.   Serves 1.
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
#Clojure
Clojure
(defn mean [sq] (if (empty? sq) 0 (/ (reduce + sq) (count sq))))
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
#Ol
Ol
  (define a1 { 'name "Rocket Skates" 'price 12.75 'color "yellow" })   (define a2 { 'price 15.25 'color "red" 'year 1974 })   (print "a1: " a1) (print "a2: " a2)   (define (collide a b) b) ; will use new key value (print "merged a1 a2: " (ff-union collide a1 a2))  
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
#Perl
Perl
use strict; use warnings;   my %base = ("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"); my %more = ("price" => 15.25, "color" => "red", "year" => 1974);   print "Update\n"; my %update = (%base, %more); printf "%-7s %s\n", $_, $update{$_} for sort keys %update;   print "\nMerge\n"; my %merge; $merge{$_} = [$base{$_}] for keys %base; push @{$merge{$_}}, $more{$_} for keys %more; printf "%-7s %s\n", $_, join ', ', @{$merge{$_}} for sort keys %merge;
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%)
#Phix
Phix
constant MAX = 20, ITER = 1000000 function expected(integer n) atom sum = 0 for i=1 to n do sum += factorial(n) / power(n,i) / factorial(n-i) end for return sum end function function test(integer n) integer count = 0, x, bits for i=1 to ITER do x = 1 bits = 0 while not and_bits(bits,x) do count += 1 bits = or_bits(bits,x) x = power(2,rand(n)-1) end while end for return count/ITER end function atom av, ex puts(1," n avg. exp. (error%)\n"); puts(1,"== ====== ====== ========\n"); for n=1 to MAX do av = test(n) ex = expected(n) printf(1,"%2d %8.4f %8.4f (%5.3f%%)\n", {n,av,ex,abs(1-av/ex)*100}) end for
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
#Ruby
Ruby
def simple_moving_average(size) nums = [] sum = 0.0 lambda do |hello| nums << hello goodbye = nums.length > size ? nums.shift : 0 sum += hello - goodbye sum / nums.length end end   ma3 = simple_moving_average(3) ma5 = simple_moving_average(5)   (1.upto(5).to_a + 5.downto(1).to_a).each do |num| printf "Next number = %d, SMA_3 = %.3f, SMA_5 = %.1f\n", num, ma3.call(num), ma5.call(num) end
http://rosettacode.org/wiki/Attractive_numbers
Attractive numbers
A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show sequence items up to   120. Reference   The OEIS entry:   A063989: Numbers with a prime number of prime divisors.
#Haskell
Haskell
import Data.Numbers.Primes import Data.Bool (bool)   attractiveNumbers :: [Integer] attractiveNumbers = [1 ..] >>= (bool [] . return) <*> (isPrime . length . primeFactors)   main :: IO () main = print $ takeWhile (<= 120) 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
#Nim
Nim
import math, complex, strutils, sequtils   proc meanAngle(deg: openArray[float]): float = var c: Complex[float] for d in deg: c += rect(1.0, degToRad(d)) radToDeg(phase(c / float(deg.len)))   proc meanTime(times: openArray[string]): string = const day = 24 * 60 * 60 let angles = times.map(proc(time: string): float = let t = time.split(":") (t[2].parseInt + t[1].parseInt * 60 + t[0].parseInt * 3600) * 360 / day) ms = (angles.meanAngle * day / 360 + day) mod day (h,m,s) = (ms.int div 3600, (ms.int mod 3600) div 60, ms.int mod 60)   align($h, 2, '0') & ":" & align($m, 2, '0') & ":" & align($s, 2, '0')   echo meanTime(["23:00:17", "23:40:20", "00:12:45", "00:17:19"])