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/Barnsley_fern
Barnsley fern
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ƒ2   (chosen 85% of the time) xn + 1 = 0.85 xn + 0.04 yn yn + 1 = −0.04 xn + 0.85 yn + 1.6 ƒ3   (chosen 7% of the time) xn + 1 = 0.2 xn − 0.26 yn yn + 1 = 0.23 xn + 0.22 yn + 1.6 ƒ4   (chosen 7% of the time) xn + 1 = −0.15 xn + 0.28 yn yn + 1 = 0.26 xn + 0.24 yn + 0.44. Starting position: x = 0, y = 0
#Yabasic
Yabasic
10 REM Fractal Fern 20 LET wid = 800 : LET hei = 600 : open window wid, hei : window origin "cb" 25 backcolor 0, 0, 0 : color 0, 255, 0 : clear window 30 LET maxpoints=wid*hei/2: LET x=0: LET y=0 40 FOR n=1 TO maxpoints 50 LET p=RAN(100) 60 IF p<=1 LET nx=0: LET ny=0.16*y: GOTO 100 70 IF p<=8 LET nx=0.2*x-0.26*y: LET ny=0.23*x+0.22*y+1.6: GOTO 100 80 IF p<=15 LET nx=-0.15*x+0.28*y: LET ny=0.26*x+0.24*y+0.44: GOTO 100 90 LET nx=0.85*x+0.04*y: LET ny=-0.04*x+0.85*y+1.6 100 LET x=nx: LET y=ny 110 DOT x*wid/12,y*hei/12 120 NEXT n
http://rosettacode.org/wiki/Babbage_problem
Babbage problem
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125. He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain. Task[edit] The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand. As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred. For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L]. Motivation The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
#Gambas
Gambas
Public Sub Main() Dim iNum As Long   For iNum = 1 To 100000 If Str(iNum * iNum) Ends "269696" Then Break Next   Print "The lowest number squared that ends in '269696' is " & Str(iNum)   End
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
#360_Assembly
360 Assembly
* Balanced brackets 28/04/2016 BALANCE CSECT USING BALANCE,R13 base register and savearea pointer SAVEAREA B STM-SAVEAREA(R15) DC 17F'0' STM STM R14,R12,12(R13) ST R13,4(R15) ST R15,8(R13) LR R13,R15 establish addressability LA R8,1 i=1 LOOPI C R8,=F'20' do i=1 to 20 BH ELOOPI MVC C(20),=CL20' ' c=' ' LA R1,1 LA R2,10 BAL R14,RANDOMX LR R11,R0 l=randomx(1,10) SLA R11,1 l=l*2 LA R10,1 j=1 LOOPJ CR R10,R11 do j=1 to 2*l BH ELOOPJ LA R1,0 LA R2,1 BAL R14,RANDOMX LR R12,R0 m=randomx(0,1) LTR R12,R12 if m=0 BNZ ELSEM MVI Q,C'[' q='[' B EIFM ELSEM MVI Q,C']' q=']' EIFM LA R14,C-1(R10) @c(j) MVC 0(1,R14),Q c(j)=q LA R10,1(R10) j=j+1 B LOOPJ ELOOPJ BAL R14,CHECKBAL LR R2,R0 C R2,=F'1' if checkbal=1 BNE ELSEC MVC PG+24(2),=C'ok' rep='ok' B EIFC ELSEC MVC PG+24(2),=C'? ' rep='? ' EIFC XDECO R8,XDEC i MVC PG+0(2),XDEC+10 MVC PG+3(20),C XPRNT PG,26 LA R8,1(R8) i=i+1 B LOOPI ELOOPI L R13,4(0,R13) LM R14,R12,12(R13) XR R15,R15 set return code to 0 BR R14 -------------- end CHECKBAL CNOP 0,4 -------------- checkbal SR R6,R6 n=0 LA R7,1 k=1 LOOPK C R7,=F'20' do k=1 to 20 BH ELOOPK LR R1,R7 k LA R4,C-1(R1) @c(k) MVC CI(1),0(R4) ci=c(k) CLI CI,C'[' if ci='[' BNE NOT1 LA R6,1(R6) n=n+1 NOT1 CLI CI,C']' if ci=']' BNE NOT2 BCTR R6,0 n=n-1 NOT2 LTR R6,R6 if n<0 BNM NSUP0 SR R0,R0 return(0) B RETCHECK NSUP0 LA R7,1(R7) k=k+1 B LOOPK ELOOPK LTR R6,R6 if n=0 BNZ ELSEN LA R0,1 return(1) B RETCHECK ELSEN SR R0,R0 return(0) RETCHECK BR R14 -------------- end checkbal RANDOMX CNOP 0,4 -------------- randomx LR R3,R2 i2 SR R3,R1 ii=i2-i1 L R5,SEED M R4,=F'1103515245' A R5,=F'12345' SRDL R4,1 shift to improve the algorithm ST R5,SEED seed=(seed*1103515245+12345)>>1 LR R6,R3 ii LA R6,1(R6) ii+1 L R5,SEED seed LA R4,0 clear DR R4,R6 seed//(ii+1) AR R4,R1 +i1 LR R0,R4 return(seed//(ii+1)+i1) BR R14 -------------- end randomx SEED DC F'903313037' C DS 20CL1 Q DS CL1 CI DS CL1 PG DC CL80' ' XDEC DS CL12 REGS END BALANCE
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
#AWK
AWK
#!/usr/bin/gawk -f { # compute histogram histo[$1] += 1; };   function mode(HIS) { # Computes the mode from Histogram A max = 0; n = 0; for (k in HIS) { val = HIS[k]; if (HIS[k] > max) { max = HIS[k]; n = 1; List[n] = k; } else if (HIS[k] == max) { List[++n] = k; } }   for (k=1; k<=n; k++) { o = o""OFS""List[k]; } return o; }   END { print mode(histo); };
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
#Lua
Lua
function sma(period) local t = {} function sum(a, ...) if a then return a+sum(...) else return 0 end end function average(n) if #t == period then table.remove(t, 1) end t[#t + 1] = n return sum(unpack(t)) / #t end return average end   sma5 = sma(5) sma10 = sma(10) print("SMA 5") for v=1,15 do print(sma5(v)) end print("\nSMA 10") for v=1,15 do print(sma10(v)) 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
#C
C
#include <stdio.h> #include <stdlib.h> // atoi() #include <math.h> // pow()   int main(int argc, char* argv[]) { int i, count=0; double f, sum=0.0, prod=1.0, resum=0.0;   for (i=1; i<argc; ++i) { f = atof(argv[i]); count++; sum += f; prod *= f; resum += (1.0/f); } //printf(" c:%d\n s:%f\n p:%f\n r:%f\n",count,sum,prod,resum); printf("Arithmetic mean = %f\n",sum/count); printf("Geometric mean = %f\n",pow(prod,(1.0/count))); printf("Harmonic mean = %f\n",count/resum);   return 0; }
http://rosettacode.org/wiki/Barnsley_fern
Barnsley fern
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ƒ2   (chosen 85% of the time) xn + 1 = 0.85 xn + 0.04 yn yn + 1 = −0.04 xn + 0.85 yn + 1.6 ƒ3   (chosen 7% of the time) xn + 1 = 0.2 xn − 0.26 yn yn + 1 = 0.23 xn + 0.22 yn + 1.6 ƒ4   (chosen 7% of the time) xn + 1 = −0.15 xn + 0.28 yn yn + 1 = 0.26 xn + 0.24 yn + 0.44. Starting position: x = 0, y = 0
#zkl
zkl
fcn barnsleyFern(){ w,h:=640,640; bitmap:=PPM(w+1,h+1,0xFF|FF|FF); // White background   x,y, nx,ny:=0.0, 0.0, 0.0, 0.0; do(0d100_000){ r:=(0).random(100); // [0..100)% if (r<= 1) nx,ny= 0, 0.16*y; else if(r<= 8) nx,ny= 0.2*x - 0.26*y, 0.23*x + 0.22*y + 1.6; else if(r<=15) nx,ny=-0.15*x + 0.28*y, 0.26*x + 0.24*y + 0.44; else nx,ny= 0.85*x + 0.04*y, -0.04*x + 0.85*y + 1.6; x,y=nx,ny; bitmap[w/2 + x*60, y*60] = 0x00|FF|00; // Green dot } bitmap.writeJPGFile("barnsleyFern.jpg"); }();
http://rosettacode.org/wiki/Barnsley_fern
Barnsley fern
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ƒ2   (chosen 85% of the time) xn + 1 = 0.85 xn + 0.04 yn yn + 1 = −0.04 xn + 0.85 yn + 1.6 ƒ3   (chosen 7% of the time) xn + 1 = 0.2 xn − 0.26 yn yn + 1 = 0.23 xn + 0.22 yn + 1.6 ƒ4   (chosen 7% of the time) xn + 1 = −0.15 xn + 0.28 yn yn + 1 = 0.26 xn + 0.24 yn + 0.44. Starting position: x = 0, y = 0
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 REM Fractal Fern 20 PAPER 7: BORDER 7: BRIGHT 1: INK 4: CLS 30 LET maxpoints=20000: LET x=0: LET y=0 40 FOR n=1 TO maxpoints 50 LET p=RND*100 60 IF p<=1 THEN LET nx=0: LET ny=0.16*y: GO TO 100 70 IF p<=8 THEN LET nx=0.2*x-0.26*y: LET ny=0.23*x+0.22*y+1.6: GO TO 100 80 IF p<=15 THEN LET nx=-0.15*x+0.28*y: LET ny=0.26*x+0.24*y+0.44: GO TO 100 90 LET nx=0.85*x+0.04*y: LET ny=-0.04*x+0.85*y+1.6 100 LET x=nx: LET y=ny 110 PLOT x*17+127,y*17 120 NEXT n  
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.
#11l
11l
F py_idiv(a, b) I a >= 0 R a I/ b R (a - b + 1) I/ b   F BalancedTernary_int2ternary(n) I n == 0 R [Int]() V n3 = ((n % 3) + 3) % 3 I n3 == 0 {R [0] [+] BalancedTernary_int2ternary(py_idiv(n, 3))} I n3 == 1 {R [1] [+] BalancedTernary_int2ternary(py_idiv(n, 3))} I n3 == 2 {R [-1] [+] BalancedTernary_int2ternary(py_idiv((n + 1), 3))} X RuntimeError(‘’)   F BalancedTernary_neg(digs) R digs.map(d -> -d)   V table = [(0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)]   F BalancedTernary_add(a, b, =c = 0) I !(!a.empty & !b.empty) I c == 0 R I !a.empty {a} E b E R BalancedTernary_add([c], I !a.empty {a} E b) E (V d, c) = :table[3 + (I !a.empty {a[0]} E 0) + (I !b.empty {b[0]} E 0) + c] V res = BalancedTernary_add(a[1..], b[1..], c) I !res.empty | d != 0 R [d] [+] res E R res   V BalancedTernary_str2dig = [‘+’ = 1, ‘-’ = -1, ‘0’ = 0] V BalancedTernary_dig2str = [1 = ‘+’, -1 = ‘-’, 0 = ‘0’]   T BalancedTernary [Int] digits   F (inp) I all(inp.map(d -> d C (0, 1, -1))) .digits = copy(inp) E X ValueError(‘BalancedTernary: Wrong input digits.’)   F to_int() R reversed(.digits).reduce(0, (y, x) -> x + 3 * y)   F String() I .digits.empty R ‘0’ R reversed(.digits).map(d -> BalancedTernary_dig2str[d]).join(‘’)   F +(b) R BalancedTernary(BalancedTernary_add(.digits, b.digits))   F -(b) R (.) + BalancedTernary(BalancedTernary_neg(b.digits))   F *(b) F _mul([Int] a, b) -> [Int] I !(!a.empty & !b.empty) R [Int]() E [Int] x I a[0] == -1 {x = BalancedTernary_neg(b)} E I a[0] == 0 {} E I a[0] == 1 {x = b} E assert(0B) V y = [0] [+] @_mul(a[1..], b) R BalancedTernary_add(x, y)   R BalancedTernary(_mul(.digits, b.digits))   F createBalancedTernaryFromStr(inp) R BalancedTernary(reversed(inp).map(c -> BalancedTernary_str2dig[c])) F createBalancedTernaryFromInt(inp) R BalancedTernary(BalancedTernary_int2ternary(inp))   V a = createBalancedTernaryFromStr(‘+-0++0+’) print(‘a: ’a.to_int()‘ ’a)   V b = createBalancedTernaryFromInt(-436) print(‘b: ’b.to_int()‘ ’b)   V c = createBalancedTernaryFromStr(‘+-++-’) print(‘c: ’c.to_int()‘ ’c)   V r = a * (b - c) print(‘a * (b - c): ’r.to_int()‘ ’r)
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.
#Go
Go
package main   import "fmt"   func main() { const ( target = 269696 modulus = 1000000 ) for n := 1; ; n++ { // Repeat with n=1, n=2, n=3, ... square := n * n ending := square % modulus if ending == target { fmt.Println("The smallest number whose square ends with", target, "is", n, ) return } } }
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
#ABAP
ABAP
  CLASS lcl_balanced_brackets DEFINITION. PUBLIC SECTION. CLASS-METHODS: class_constructor,   are_brackets_balanced IMPORTING seq TYPE string RETURNING VALUE(r_are_brackets_balanced) TYPE abap_bool,   get_random_brackets_seq IMPORTING n TYPE i RETURNING VALUE(r_bracket_seq) TYPE string.   PRIVATE SECTION. CLASS-DATA: random_int TYPE REF TO cl_abap_random_int.   CLASS-METHODS: _split_string IMPORTING i_text TYPE string RETURNING VALUE(r_chars) TYPE stringtab,   _rand_bool RETURNING VALUE(r_bool) TYPE i. ENDCLASS.   CLASS lcl_balanced_brackets IMPLEMENTATION. METHOD class_constructor. random_int = cl_abap_random_int=>create( seed = CONV #( sy-uzeit ) min = 0 max = 1 ). ENDMETHOD.   METHOD are_brackets_balanced. DATA: open_bracket_count TYPE i.   DATA(chars) = _split_string( seq ).   r_are_brackets_balanced = abap_false.   LOOP AT chars ASSIGNING FIELD-SYMBOL(<c>). IF <c> = ']' AND open_bracket_count = 0. RETURN. ENDIF.   IF <c> = ']'. open_bracket_count = open_bracket_count - 1. ENDIF.   IF <c> = '['. open_bracket_count = open_bracket_count + 1. ENDIF. ENDLOOP.   IF open_bracket_count > 0. RETURN. ENDIF.   r_are_brackets_balanced = abap_true. ENDMETHOD.   METHOD get_random_brackets_seq. DATA(itab) = VALUE stringtab( FOR i = 1 THEN i + 1 WHILE i <= n ( COND #( WHEN _rand_bool( ) = 0 THEN '[' ELSE ']' ) ) ). r_bracket_seq = concat_lines_of( itab ). ENDMETHOD.   METHOD _rand_bool. r_bool = random_int->get_next( ). ENDMETHOD.   METHOD _split_string. DATA: off TYPE i VALUE 0.   DO strlen( i_text ) TIMES. INSERT i_text+off(1) INTO TABLE r_chars. off = off + 1. ENDDO. ENDMETHOD. ENDCLASS.   START-OF-SELECTION. DO 10 TIMES. DATA(seq) = lcl_balanced_brackets=>get_random_brackets_seq( 10 ). cl_demo_output=>write( |{ seq } => { COND string( WHEN lcl_balanced_brackets=>are_brackets_balanced( seq ) = abap_true THEN 'OK' ELSE 'NOT OK' ) }| ). ENDDO. cl_demo_output=>display( ).    
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
#BBC_BASIC
BBC BASIC
DIM a(10), b(4) a() = 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17 b() = 1, 2, 4, 4, 1   DIM modes(10) PRINT "Mode(s) of a() = " ; FOR i% = 1 TO FNmodes(a(), modes()) PRINT ; modes(i%) " " ; NEXT PRINT PRINT "Mode(s) of b() = " ; FOR i% = 1 TO FNmodes(b(), modes()) PRINT ; modes(i%) " " ; NEXT PRINT END   DEF FNmodes(a(), m()) LOCAL I%, J%, N%, c%(), max% N% = DIM(a(),1) IF N% = 0 THEN m(1) = a(0) : = 1 DIM c%(N%) FOR I% = 0 TO N%-1 FOR J% = I%+1 TO N% IF a(I%) = a(J%) c%(I%) += 1 NEXT IF c%(I%) > max% max% = c%(I%) NEXT I% J% = 0 FOR I% = 0 TO N% IF c%(I%) = max% J% += 1 : m(J%) = a(I%) NEXT = J%  
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
#BQN
BQN
Mode1 ← ⌈´⊸=∘⊒⊸/ Mode2 ← ⊏∘⊑˘·(⌈´⊸=≠¨)⊸/⊐⊸⊔ arr ← 1‿1‿1‿1‿2‿2‿2‿3‿3‿3‿3‿4‿4‿3‿2‿4‿4‿4‿5‿5‿5‿5‿5 •Show Mode1 arr •Show Mode2 arr
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
MA[x_List, r_] := Join[Table[Mean[x[[1;;y]]],{y,r-1}], MovingAverage[x,r]]
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
#C.23
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq;   namespace PythMean { static class Program { static void Main(string[] args) { var nums = from n in Enumerable.Range(1, 10) select (double)n;   var a = nums.Average(); var g = nums.Gmean(); var h = nums.Hmean();   Console.WriteLine("Arithmetic mean {0}", a); Console.WriteLine("Geometric mean {0}", g); Console.WriteLine("Harmonic mean {0}", h);   Debug.Assert(a >= g && g >= h); }   // Geometric mean extension method. static double Gmean(this IEnumerable<double> n) { return Math.Pow(n.Aggregate((s, i) => s * i), 1.0 / n.Count()); }   // Harmonic mean extension method. static double Hmean(this IEnumerable<double> n) { return n.Count() / n.Sum(i => 1.0 / i); } } }
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.
#Ada
Ada
with Ada.Finalization;   package BT is   type Balanced_Ternary is private;   -- conversions function To_Balanced_Ternary (Num : Integer) return Balanced_Ternary; function To_Balanced_Ternary (Str : String) return Balanced_Ternary; function To_Integer (Num : Balanced_Ternary) return Integer; function To_string (Num : Balanced_Ternary) return String;   -- Arithmetics -- unary minus function "-" (Left : in Balanced_Ternary) return Balanced_Ternary;   -- subtraction function "-" (Left, Right : in Balanced_Ternary) return Balanced_Ternary;   -- addition function "+" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; -- multiplication function "*" (Left, Right : in Balanced_Ternary) return Balanced_Ternary;   private -- a balanced ternary number is a unconstrained array of (1,0,-1) -- dinamically allocated, least significant trit leftmost type Trit is range -1..1; type Trit_Array is array (Positive range <>) of Trit; pragma Pack(Trit_Array);   type Trit_Access is access Trit_Array;   type Balanced_Ternary is new Ada.Finalization.Controlled with record Ref : Trit_access; end record;   procedure Initialize (Object : in out Balanced_Ternary); procedure Adjust (Object : in out Balanced_Ternary); procedure Finalize (Object : in out Balanced_Ternary);   end BT;
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.
#Groovy
Groovy
  int n=104; ///starting point while( (n**2)%1000000 != 269696 ) { if (n%10==4) n=n+2; if (n%10==6) n=n+8; } println n+"^2== "+n**2 ;  
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
#Action.21
Action!
PROC Generate(BYTE size CHAR ARRAY s) BYTE i,half   s(0)=size half=size RSH 1   FOR i=1 TO half DO s(i)='[ OD   FOR i=half+1 TO size DO s(i)='] OD RETURN   PROC Shuffle(CHAR ARRAY s) BYTE i,j,k,n,len,tmp   len=s(0) n=Rand(len+1) FOR k=1 TO n DO i=Rand(len)+1 j=Rand(len)+1 tmp=s(i) s(i)=s(j) s(j)=tmp OD RETURN   BYTE FUNC Balanced(CHAR ARRAY s) INT i,lev   lev=0 FOR i=1 TO s(0) DO IF s(i)='[ THEN lev==+1 ELSE lev==-1 FI   IF lev<0 THEN RETURN (0) FI OD   IF lev#0 THEN RETURN (0) FI RETURN (1)   PROC Main() CHAR ARRAY s(20) BYTE i,b   FOR i=0 TO 20 STEP 2 DO Generate(i,s) Shuffle(s) b=Balanced(s)   IF s(0)=0 THEN Print("(empty)") ELSE Print(s) FI Print(" is ") IF b=0 THEN Print("not ") FI PrintE("balanced") OD RETURN
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
#C
C
#include <stdio.h> #include <stdlib.h>   typedef struct { double v; int c; } vcount;   int cmp_dbl(const void *a, const void *b) { double x = *(const double*)a - *(const double*)b; return x < 0 ? -1 : x > 0; }   int vc_cmp(const void *a, const void *b) { return ((const vcount*)b)->c - ((const vcount*)a)->c; }   int get_mode(double* x, int len, vcount **list) { int i, j; vcount *vc;   /* sort values */ qsort(x, len, sizeof(double), cmp_dbl);   /* count occurence of each value */ for (i = 0, j = 1; i < len - 1; i++, j += (x[i] != x[i + 1]));   *list = vc = malloc(sizeof(vcount) * j); vc[0].v = x[0]; vc[0].c = 1;   /* generate list value-count pairs */ for (i = j = 0; i < len - 1; i++, vc[j].c++) if (x[i] != x[i + 1]) vc[++j].v = x[i + 1];   /* sort that by count in descending order */ qsort(vc, j + 1, sizeof(vcount), vc_cmp);   /* the number of entries with same count as the highest */ for (i = 0; i <= j && vc[i].c == vc[0].c; i++);   return i; }   int main() { double values[] = { 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 12, 12, 17 }; # define len sizeof(values)/sizeof(double) vcount *vc;   int i, n_modes = get_mode(values, len, &vc);   printf("got %d modes:\n", n_modes); for (i = 0; i < n_modes; i++) printf("\tvalue = %g, count = %d\n", vc[i].v, vc[i].c);   free(vc); return 0; }
http://rosettacode.org/wiki/Averages/Simple_moving_average
Averages/Simple moving average
Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is a method for computing an average of a stream of numbers by only averaging the last   P   numbers from the stream,   where   P   is known as the period. It can be implemented by calling an initialing routine with   P   as its argument,   I(P),   which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last   P   of them, lets call this   SMA(). The word   stateful   in the task description refers to the need for   SMA()   to remember certain information between calls to it:   The period,   P   An ordered container of at least the last   P   numbers from each of its individual calls. Stateful   also means that successive calls to   I(),   the initializer,   should return separate routines that do   not   share saved state so they could be used on two independent streams of data. Pseudo-code for an implementation of   SMA   is: function SMA(number: N): stateful integer: P stateful list: stream number: average stream.append_last(N) if stream.length() > P: # Only average the last P elements of the stream stream.delete_first() if stream.length() == 0: average = 0 else: average = sum( stream.values() ) / stream.length() return average See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#MATLAB_.2F_Octave
MATLAB / Octave
[m,z] = filter(ones(1,P),P,x);
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of 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
#C.2B.2B
C++
#include <vector> #include <iostream> #include <numeric> #include <cmath> #include <algorithm>   double toInverse ( int i ) { return 1.0 / i ; }   int main( ) { std::vector<int> numbers ; for ( int i = 1 ; i < 11 ; i++ ) numbers.push_back( i ) ; double arithmetic_mean = std::accumulate( numbers.begin( ) , numbers.end( ) , 0 ) / 10.0 ; double geometric_mean = pow( std::accumulate( numbers.begin( ) , numbers.end( ) , 1 , std::multiplies<int>( ) ), 0.1 ) ; std::vector<double> inverses ; inverses.resize( numbers.size( ) ) ; std::transform( numbers.begin( ) , numbers.end( ) , inverses.begin( ) , toInverse ) ; double harmonic_mean = 10 / std::accumulate( inverses.begin( ) , inverses.end( ) , 0.0 ); //initial value of accumulate must be a double! std::cout << "The arithmetic mean is " << arithmetic_mean << " , the geometric mean " << geometric_mean << " and the harmonic mean " << harmonic_mean << " !\n" ; return 0 ; }
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.
#ALGOL_68
ALGOL 68
-- Build a balanced ternary, as text, from an integer value or acceptable AppleScript substitute. on BTFromInteger(n) try if (n mod 1 is not 0) then error (n as text) & " isn't an integer value" set n to n as integer on error errMsg display alert "BTFromInteger handler: parameter error" message errMsg buttons {"OK"} default button 1 as critical error number -128 end try if (n is 0) then return "0" -- Positive numbers' digits will be indexed from the beginning of a list containing them, negatives' from the end. -- AppleScript indices are 1-based, so get the appropriate 1 or -1 add-in. set one to 1 if (n < 0) then set one to -1 set digits to {"0", "+", "-", "0"} -- Build the text digit by digit. set bt to "" repeat until (n = 0) set nMod3 to n mod 3 set bt to (item (nMod3 + one) of digits) & bt set n to n div 3 + nMod3 div 2 -- + nMod3 div 2 adds in a carry when nMod3 is either 2 or -2. end repeat   return bt end BTFromInteger   -- Calculate a balanced ternary's integer value from its characters' Unicode numbers. on integerFromBT(bt) checkInput(bt, "integerFromBT") set n to 0 repeat with thisID in (get bt's id) set n to n * 3 -- Unicode 48 is "0", 43 is "+", 45 is "-". if (thisID < 48) then set n to n + (44 - thisID) end repeat   return n end integerFromBT   -- Add two balanced ternaries together. on addBTs(bt1, bt2) checkInput({bt1, bt2}, "addBTs") set {longerLength, shorterLength} to {(count bt1), (count bt2)} if (longerLength < shorterLength) then set {bt1, bt2, longerLength, shorterLength} to {bt2, bt1, shorterLength, longerLength}   -- Add the shorter number's digits into a list of the longer number's digits, adding in carries too where appropriate. set resultList to bt1's characters repeat with i from -1 to -shorterLength by -1 set {carry, item i of resultList} to sumDigits(item i of resultList, character i of bt2) repeat with j from (i - 1) to -longerLength by -1 if (carry is "0") then exit repeat set {carry, item j of resultList} to sumDigits(carry, item j of resultList) end repeat if (carry is not "0") then set beginning of bt1 to carry end repeat -- Zap any leading zeros resulting from the cancelling out of the longer number's MSD(s). set j to -(count resultList) repeat while ((item j of resultList is "0") and (j < -1)) set item j of resultList to "" set j to j + 1 end repeat   return join(resultList, "") end addBTs   -- Multiply one balanced ternary by another. on multiplyBTs(bt1, bt2) checkInput({bt1, bt2}, "multiplyBTs") -- Longer and shorter aren't critical here, but it's more efficient to loop through the lesser number of digits. set {longerLength, shorterLength} to {(count bt1), (count bt2)} if (longerLength < shorterLength) then set {bt1, bt2, shorterLength} to {bt2, bt1, longerLength}   set multiplicationResult to "0" repeat with i from -1 to -shorterLength by -1 set d2 to character i of bt2 if (d2 is not "0") then set subresult to "" -- With each non-"0" subresult, begin with the appropriate number of trailing zeros. repeat (-1 - i) times set subresult to "0" & subresult end repeat -- Prepend the longer ternary as is. set subresult to bt1 & subresult -- Negate the result if the current multiplier from the shorter ternary is "-". if (d2 is "-") then set subresult to negateBT(subresult) -- Add the subresult to the total so far. set multiplicationResult to addBTs(multiplicationResult, subresult) end if end repeat   return multiplicationResult end multiplyBTs   -- Negate a balanced ternary by substituting the characters obtained through subtracting its sign characters' Unicode numbers from 88. on negateBT(bt) checkInput(bt, "negateBT") set characterIDs to bt's id repeat with thisID in characterIDs if (thisID < 48) then set thisID's contents to 88 - thisID end repeat   return string id characterIDs end negateBT   (* Private handlers. *)   on checkInput(params as list, handlerName) try repeat with thisParam in params if (thisParam's class is text) then if (join(split(thisParam, {"-", "+", "0"}), "") > "") then error "\"" & thisParam & "\" isn't a balanced ternary number." else error "The parameter isn't text." end if end repeat on error errMsg display alert handlerName & " handler: parameter error" message errMsg buttons {"OK"} default button 1 as critical error number -128 end try end checkInput   -- "Add" two balanced ternaries and return both the carry and the result for the column. on sumDigits(d1, d2) if (d1 is "0") then return {"0", d2} else if (d2 is "0") then return {"0", d1} else if (d1 = d2) then if (d1 = "+") then return {"+", "-"} else return {"-", "+"} end if else return {"0", "0"} end if end sumDigits   on join(lst, delimiter) set astid to AppleScript's text item delimiters set AppleScript's text item delimiters to delimiter set txt to lst as text set AppleScript's text item delimiters to astid   return txt end join   on split(txt, delimiter) set astid to AppleScript's text item delimiters set AppleScript's text item delimiters to delimiter set lst to txt's text items set AppleScript's text item delimiters to astid   return lst end split   -- Test code: set a to "+-0++0+" set b to BTFromInteger(-436) --> "-++-0--" set c to "+-++-"   set line1 to "a = " & integerFromBT(a) set line2 to "b = " & integerFromBT(b) set line3 to "c = " & integerFromBT(c) tell multiplyBTs(a, addBTs(b, negateBT(c))) to ¬ set line4 to "a * (b - c) = " & it & " or " & my integerFromBT(it)   return line1 & linefeed & line2 & linefeed & line3 & linefeed & line4
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.
#Haskell
Haskell
--Calculate squares, testing for the last 6 digits findBabbageNumber :: Integer findBabbageNumber = head (filter ((269696 ==) . flip mod 1000000 . (^ 2)) [1 ..])   main :: IO () main = (putStrLn . unwords) (zipWith (++) (show <$> ([id, (^ 2)] <*> [findBabbageNumber])) [" ^ 2 equals", " !"])
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
#Acurity_Architect
Acurity Architect
Using #HASH-OFF
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
#C.23
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq;   namespace Test { class Program {   static void Main(string[] args) { /* * We Use Linq To Determine The Mode */ List<int> myList = new List<int>() { 1, 1, 2, 4, 4 };   var query = from numbers in myList //select the numbers group numbers by numbers //group them together so we can get the count into groupedNumbers select new { Number = groupedNumbers.Key, Count = groupedNumbers.Count() }; //so we got a query //find the max of the occurence of the mode int max = query.Max(g => g.Count); IEnumerable<int> modes = query.Where(x => x.Count == max).Select(x => x.Number);//match the frequence and select the number foreach (var item in modes) { Console.WriteLine(item); }   Console.ReadLine(); }       }     }  
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
#Mercury
Mercury
 % state(period, list of floats from [newest, ..., oldest]) :- type state ---> state(int, list(float)).   :- func init(int) = state. init(Period) = state(Period, []).   :- pred sma(float::in, float::out, state::in, state::out) is det. sma(N, Average, state(P, L0), state(P, L)) :- take_upto(P, [N|L0], L), Average = foldl((+), L, 0.0) / float(length(L)).
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
#Clojure
Clojure
(use '[clojure.contrib.math :only (expt)])   (defn a-mean [coll] (/ (apply + coll) (count coll)))   (defn g-mean [coll] (expt (apply * coll) (/ (count coll))))   (defn h-mean [coll] (/ (count coll) (apply + (map / coll))))   (let [numbers (range 1 11) a (a-mean numbers) g (g-mean numbers) h (h-mean numbers)] (println a ">=" g ">=" h) (>= a g h))
http://rosettacode.org/wiki/Balanced_ternary
Balanced ternary
Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0" 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.
#AppleScript
AppleScript
-- Build a balanced ternary, as text, from an integer value or acceptable AppleScript substitute. on BTFromInteger(n) try if (n mod 1 is not 0) then error (n as text) & " isn't an integer value" set n to n as integer on error errMsg display alert "BTFromInteger handler: parameter error" message errMsg buttons {"OK"} default button 1 as critical error number -128 end try if (n is 0) then return "0" -- Positive numbers' digits will be indexed from the beginning of a list containing them, negatives' from the end. -- AppleScript indices are 1-based, so get the appropriate 1 or -1 add-in. set one to 1 if (n < 0) then set one to -1 set digits to {"0", "+", "-", "0"} -- Build the text digit by digit. set bt to "" repeat until (n = 0) set nMod3 to n mod 3 set bt to (item (nMod3 + one) of digits) & bt set n to n div 3 + nMod3 div 2 -- + nMod3 div 2 adds in a carry when nMod3 is either 2 or -2. end repeat   return bt end BTFromInteger   -- Calculate a balanced ternary's integer value from its characters' Unicode numbers. on integerFromBT(bt) checkInput(bt, "integerFromBT") set n to 0 repeat with thisID in (get bt's id) set n to n * 3 -- Unicode 48 is "0", 43 is "+", 45 is "-". if (thisID < 48) then set n to n + (44 - thisID) end repeat   return n end integerFromBT   -- Add two balanced ternaries together. on addBTs(bt1, bt2) checkInput({bt1, bt2}, "addBTs") set {longerLength, shorterLength} to {(count bt1), (count bt2)} if (longerLength < shorterLength) then set {bt1, bt2, longerLength, shorterLength} to {bt2, bt1, shorterLength, longerLength}   -- Add the shorter number's digits into a list of the longer number's digits, adding in carries too where appropriate. set resultList to bt1's characters repeat with i from -1 to -shorterLength by -1 set {carry, item i of resultList} to sumDigits(item i of resultList, character i of bt2) repeat with j from (i - 1) to -longerLength by -1 if (carry is "0") then exit repeat set {carry, item j of resultList} to sumDigits(carry, item j of resultList) end repeat if (carry is not "0") then set beginning of bt1 to carry end repeat -- Zap any leading zeros resulting from the cancelling out of the longer number's MSD(s). set j to -(count resultList) repeat while ((item j of resultList is "0") and (j < -1)) set item j of resultList to "" set j to j + 1 end repeat   return join(resultList, "") end addBTs   -- Multiply one balanced ternary by another. on multiplyBTs(bt1, bt2) checkInput({bt1, bt2}, "multiplyBTs") -- Longer and shorter aren't critical here, but it's more efficient to loop through the lesser number of digits. set {longerLength, shorterLength} to {(count bt1), (count bt2)} if (longerLength < shorterLength) then set {bt1, bt2, shorterLength} to {bt2, bt1, longerLength}   set multiplicationResult to "0" repeat with i from -1 to -shorterLength by -1 set d2 to character i of bt2 if (d2 is not "0") then set subresult to "" -- With each non-"0" subresult, begin with the appropriate number of trailing zeros. repeat (-1 - i) times set subresult to "0" & subresult end repeat -- Prepend the longer ternary as is. set subresult to bt1 & subresult -- Negate the result if the current multiplier from the shorter ternary is "-". if (d2 is "-") then set subresult to negateBT(subresult) -- Add the subresult to the total so far. set multiplicationResult to addBTs(multiplicationResult, subresult) end if end repeat   return multiplicationResult end multiplyBTs   -- Negate a balanced ternary by substituting the characters obtained through subtracting its sign characters' Unicode numbers from 88. on negateBT(bt) checkInput(bt, "negateBT") set characterIDs to bt's id repeat with thisID in characterIDs if (thisID < 48) then set thisID's contents to 88 - thisID end repeat   return string id characterIDs end negateBT   (* Private handlers. *)   on checkInput(params as list, handlerName) try repeat with thisParam in params if (thisParam's class is text) then if (join(split(thisParam, {"-", "+", "0"}), "") > "") then error "\"" & thisParam & "\" isn't a balanced ternary number." else error "The parameter isn't text." end if end repeat on error errMsg display alert handlerName & " handler: parameter error" message errMsg buttons {"OK"} default button 1 as critical error number -128 end try end checkInput   -- "Add" two balanced ternaries and return both the carry and the result for the column. on sumDigits(d1, d2) if (d1 is "0") then return {"0", d2} else if (d2 is "0") then return {"0", d1} else if (d1 = d2) then if (d1 = "+") then return {"+", "-"} else return {"-", "+"} end if else return {"0", "0"} end if end sumDigits   on join(lst, delimiter) set astid to AppleScript's text item delimiters set AppleScript's text item delimiters to delimiter set txt to lst as text set AppleScript's text item delimiters to astid   return txt end join   on split(txt, delimiter) set astid to AppleScript's text item delimiters set AppleScript's text item delimiters to delimiter set lst to txt's text items set AppleScript's text item delimiters to astid   return lst end split   -- Test code: set a to "+-0++0+" set b to BTFromInteger(-436) --> "-++-0--" set c to "+-++-"   set line1 to "a = " & integerFromBT(a) set line2 to "b = " & integerFromBT(b) set line3 to "c = " & integerFromBT(c) tell multiplyBTs(a, addBTs(b, negateBT(c))) to ¬ set line4 to "a * (b - c) = " & it & " or " & my integerFromBT(it)   return line1 & linefeed & line2 & linefeed & line3 & linefeed & line4
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.
#J
J
square=: ^&2 modulo1e6=: 1000000&| trythese=: i. 1000000 NB. first million nonnegative integers which=: I. NB. position of true values which 269696=modulo1e6 square trythese NB. right to left <- 25264 99736 150264 224736 275264 349736 400264 474736 525264 599736 650264 724736 775264 849736 900264 974736
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
#Ada
Ada
with Ada.Numerics.Discrete_Random; with Ada.Text_IO; with Ada.Strings.Fixed; procedure Brackets is package Random_Positive is new Ada.Numerics.Discrete_Random (Positive); Positive_Generator : Random_Positive.Generator; procedure Swap (Left, Right : in out Character) is Temp : constant Character := Left; begin Left := Right; Right := Temp; end Swap; function Generate_Brackets (Bracket_Count : Natural; Opening_Bracket : Character := '['; Closing_Bracket : Character := ']') return String is use Ada.Strings.Fixed; All_Brackets : String := Bracket_Count * Opening_Bracket & Bracket_Count * Closing_Bracket; begin for I in All_Brackets'Range loop Swap (All_Brackets (I), All_Brackets (Random_Positive.Random (Positive_Generator) mod (Bracket_Count * 2) + 1)); end loop; return All_Brackets; end Generate_Brackets;   function Check_Brackets (Test : String; Opening_Bracket : Character := '['; Closing_Bracket : Character := ']') return Boolean is Open : Natural := 0; begin for I in Test'Range loop if Test (I) = Opening_Bracket then Open := Open + 1; elsif Test (I) = Closing_Bracket then if Open = 0 then return False; else Open := Open - 1; end if; end if; end loop; return True; end Check_Brackets; begin Random_Positive.Reset (Positive_Generator); Ada.Text_IO.Put_Line ("Brackets"); for I in 0 .. 4 loop for J in 0 .. I loop declare My_String : constant String := Generate_Brackets (I); begin Ada.Text_IO.Put_Line (My_String & ": " & Boolean'Image (Check_Brackets (My_String))); end; end loop; end loop; end Brackets;
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
#C.2B.2B
C++
#include <iterator> #include <utility> #include <algorithm> #include <list> #include <iostream>   // helper struct template<typename T> struct referring { referring(T const& t): value(t) {} template<typename Iter> bool operator()(std::pair<Iter, int> const& p) const { return *p.first == value; } T const& value; };   // requires: // FwdIterator is a ForwardIterator // The value_type of FwdIterator is EqualityComparable // OutIterator is an output iterator // the value_type of FwdIterator is convertible to the value_type of OutIterator // [first, last) is a valid range // provides: // the mode is written to result template<typename FwdIterator, typename OutIterator> void mode(FwdIterator first, FwdIterator last, OutIterator result) { typedef typename std::iterator_traits<FwdIterator>::value_type value_type; typedef std::list<std::pair<FwdIterator, int> > count_type; typedef typename count_type::iterator count_iterator;   // count elements count_type counts;   while (first != last) { count_iterator element = std::find_if(counts.begin(), counts.end(), referring<value_type>(*first)); if (element == counts.end()) counts.push_back(std::make_pair(first, 1)); else ++element->second; ++first; }   // find maximum int max = 0; for (count_iterator i = counts.begin(); i != counts.end(); ++i) if (i->second > max) max = i->second;   // copy corresponding elements to output sequence for (count_iterator i = counts.begin(); i != counts.end(); ++i) if (i->second == max) *result++ = *i->first; }   // example usage int main() { int values[] = { 1, 2, 3, 1, 2, 4, 2, 5, 2, 3, 3, 1, 3, 6 }; median(values, values + sizeof(values)/sizeof(int), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; return 0; }
http://rosettacode.org/wiki/Averages/Simple_moving_average
Averages/Simple moving average
Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is a method for computing an average of a stream of numbers by only averaging the last   P   numbers from the stream,   where   P   is known as the period. It can be implemented by calling an initialing routine with   P   as its argument,   I(P),   which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last   P   of them, lets call this   SMA(). The word   stateful   in the task description refers to the need for   SMA()   to remember certain information between calls to it:   The period,   P   An ordered container of at least the last   P   numbers from each of its individual calls. Stateful   also means that successive calls to   I(),   the initializer,   should return separate routines that do   not   share saved state so they could be used on two independent streams of data. Pseudo-code for an implementation of   SMA   is: function SMA(number: N): stateful integer: P stateful list: stream number: average stream.append_last(N) if stream.length() > P: # Only average the last P elements of the stream stream.delete_first() if stream.length() == 0: average = 0 else: average = sum( stream.values() ) / stream.length() return average See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#MiniScript
MiniScript
SMA = {} SMA.P = 5 // (a default; may be overridden) SMA.buffer = null SMA.next = function(n) if self.buffer == null then self.buffer = [] self.buffer.push n if self.buffer.len > self.P then self.buffer.pull return self.buffer.sum / self.buffer.len end function   sma3 = new SMA sma3.P = 3 sma5 = new SMA   for i in range(10) num = round(rnd*100) print "num: " + num + " sma3: " + sma3.next(num) + " sma5: " + sma5.next(num) end for
http://rosettacode.org/wiki/Averages/Mean_time_of_day
Averages/Mean time of day
Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ideas of Averages/Mean angle compute and show the average time of the nocturnal activity to an accuracy of one second of time. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#11l
11l
F mean_angle(angles) V x = sum(angles.map(a -> cos(radians(a)))) / angles.len V y = sum(angles.map(a -> sin(radians(a)))) / angles.len R degrees(atan2(y, x))   F mean_time(times) V t = (times.map(time -> time.split(‘:’))) V seconds = (t.map(hms -> (Float(hms[2]) + Int(hms[1]) * 60 + Int(hms[0]) * 3600))) V day = 24 * 60 * 60 V to_angles = seconds.map(s -> s * 360.0 / @day) V mean_as_angle = mean_angle(to_angles) V mean_seconds = round(mean_as_angle * day / 360.0) I mean_seconds < 0 mean_seconds += day V h = mean_seconds I/ 3600 V m = mean_seconds % 3600 V s = m % 60 m = m I/ 60 R ‘#02:#02:#02’.format(h, m, s)   print(mean_time([‘23:00:17’, ‘23:40:20’, ‘00:12:45’, ‘00:17:19’]))
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
#CoffeeScript
CoffeeScript
a = [ 1..10 ] arithmetic_mean = (a) -> a.reduce(((s, x) -> s + x), 0) / a.length geometic_mean = (a) -> Math.pow(a.reduce(((s, x) -> s * x), 1), (1 / a.length)) harmonic_mean = (a) -> a.length / a.reduce(((s, x) -> s + 1 / x), 0)   A = arithmetic_mean a G = geometic_mean a H = harmonic_mean a   console.log "A = ", A, " G = ", G, " H = ", H console.log "A >= G : ", A >= G, " G >= H : ", G >= H
http://rosettacode.org/wiki/Balanced_ternary
Balanced ternary
Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0" 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.
#ATS
ATS
  (* ** This one is ** translated into ATS from the Ocaml entry *)   (* ****** ****** *) // // How to compile: // patscc -DATS_MEMALLOC_LIBC -o bternary bternary.dats // (* ****** ****** *)   #include "share/atspre_staload.hats"   (* ****** ****** *)   datatype btd = P | Z | N; typedef btern = List0(btd)   (* ****** ****** *)   fun btd2int (d: btd): int = (case+ d of P() => 1 | Z() => 0 | N() => ~1)   (* ****** ****** *)   fun btd2string (d:btd): string = ( case+ d of P() => "+" | Z() => "0" | N() => "-" )   (* ****** ****** *)   fun btern2string ( ds: btern ) : string = strptr2string(res) where { val xs = list_map_cloref (ds, lam d => btd2string(d)) val xs = list_vt_reverse (xs) val res = stringlst_concat($UNSAFE.castvwtp1{List(string)}(xs)) val () = list_vt_free<string> (xs) }   (* ****** ****** *)   fun from_string (inp: string): btern = let // fun loop{n:nat} ( inp: string(n), ds: btern ) : btern = ( // if isneqz(inp) then let val c = inp.head() val d = (case- c of '+' => P | '0' => Z | '-' => N): btd // end of [val] in loop (inp.tail(), list_cons(d, ds)) end // end of [then] else ds // end of [else] // ) (* end of [loop] *) // in loop (g1ofg0(inp), list_nil) end // end of [from_string]   (* ****** ****** *)   fun to_int (ds: btern): int = ( case+ ds of | list_nil () => 0 | list_cons (d, ds) => 3*to_int(ds) + btd2int(d) ) (* end of [to_int] *)   fun from_int (n: int): btern = ( if n = 0 then list_nil else let val r = n mod 3 in if r = 0 then list_cons (Z, from_int (n/3)) else if (r = 1 || r = ~2) then list_cons (P, from_int ((n-1)/3)) else list_cons (N, from_int ((n+1)/3)) end // end of [else] ) (* end of [from_int] *)   (* ****** ****** *)   fun neg_btern (ds: btern): btern = list_vt2t ( list_map_cloref<btd><btd> (ds, lam d => case+ d of P() => N() | Z() => Z() | N() => P()) ) (* end of [neg_btern] *)   overload ~ with neg_btern   (* ****** ****** *) // extern fun add_btern_btern: (btern, btern) -> btern and sub_btern_btern: (btern, btern) -> btern overload + with add_btern_btern of 100 overload - with sub_btern_btern of 100 // extern fun mul_btern_btern: (btern, btern) -> btern overload * with mul_btern_btern of 110 // (* ****** ****** *)   #define :: list_cons   (* ****** ****** *)   local   fun aux0 (ds: btern): btern = ( case+ ds of nil() => ds | _ => Z()::ds )   fun succ(ds:btern) = ds+list_sing(P()) fun pred(ds:btern) = ds+list_sing(N())   in (* in-of-local *)   implement add_btern_btern (ds1, ds2) = ( case+ (ds1, ds2) of | (nil(), _) => ds2 | (_, nil()) => ds1 | (P()::ds1, N()::ds2) => aux0 (ds1+ds2) | (Z()::ds1, Z()::ds2) => aux0 (ds1+ds2) | (N()::ds1, P()::ds2) => aux0 (ds1+ds2) | (P()::ds1, P()::ds2) => N() :: succ(ds1 + ds2) | (N()::ds1, N()::ds2) => P() :: pred(ds1 + ds2) | (Z()::ds1, btd::ds2) => btd :: (ds1 + ds2) | (btd::ds1, Z()::ds2) => btd :: (ds1 + ds2) )   implement sub_btern_btern (ds1, ds2) = ds1 + (~ds2)   implement mul_btern_btern (ds1, ds2) = ( case+ ds2 of | nil() => nil() | Z()::ds2 => aux0 (ds1 * ds2) | P()::ds2 => aux0 (ds1 * ds2) + ds1 | N()::ds2 => aux0 (ds1 * ds2) - ds1 )   end // end of [local]   (* ****** ****** *)   typedef charptr = $extype"char*"   (* ****** ****** *)   implement main0 () = { // val a = from_string "+-0++0+" // val b = from_int (~436) val c = from_string "+-++-" // val d = a * (b - c) // val () = $extfcall ( void , "printf" , "a = %d\nb = %d\nc = %d\na * (b - c) = %s = %d\n" , to_int(a) , to_int(b) , to_int(c) , $UNSAFE.cast{charptr}(btern2string(d)) , to_int(d) ) (* end of [val] *) // } (* end of [main0] *)  
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.
#Java
Java
public class Test {   public static void main(String[] args) {   // let n be zero int n = 0;   // repeat the following action do {   // increase n by 1 n++;   // while the modulo of n times n is not equal to 269696 } while (n * n % 1000_000 != 269696);   // show the result System.out.println(n); } }
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#Aime
Aime
unbalanced(data s) { integer b, i;   b = i = 0; while (i + ~s && -1 < b) { b += s[i -= 1] == '[' ? -1 : 1; }   b; }   generate(data b, integer d) { if (d) { d.times(l_bill, list(), -1, '[', ']').l_rand().ucall(b_append, 1, b); } }   main(void) { integer i;   i = 0; while (i < 10) { data s;   generate(s, i); o_(s, " is ", unbalanced(s) ? "un" : "", "balanced\n");   i += 1; }   0; }
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
#Clojure
Clojure
(defn modes [coll] (let [distrib (frequencies coll) [value freq] [first second] ; name the key/value pairs in the distrib (map) entries sorted (sort-by (comp - freq) distrib) maxfq (freq (first sorted))] (map value (take-while #(= maxfq (freq %)) sorted))))
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
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   numeric digits 20   class RAvgSimpleMoving public   properties private window = java.util.Queue period sum   properties constant exMsg = 'Period must be a positive integer'   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method RAvgSimpleMoving(period_) public if \period_.datatype('w') then signal RuntimeException(exMsg) if period_ <= 0 then signal RuntimeException(exMsg) window = LinkedList() period = period_ sum = 0 return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method newNum(num) public sum = sum + num window.add(num) if window.size() > period then do rmv = (Rexx window.remove()) sum = sum - rmv end return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method getAvg() public returns Rexx if window.isEmpty() then do avg = 0 end else do avg = sum / window.size() end return avg   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method run_samples(args = String[]) public static testData = [Rexx 1, 2, 3, 4, 5, 5, 4, 3, 2, 1] windowSizes = [Rexx 3, 5] loop windSize over windowSizes ma = RAvgSimpleMoving(windSize) loop xVal over testData ma.newNum(xVal) say 'Next number =' xVal.right(5)', SMA =' ma.getAvg().format(10, 9) end xVal say end windSize   return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method main(args = String[]) public static run_samples(args) return  
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
#Action.21
Action!
INCLUDE "H6:REALMATH.ACT"   DEFINE PTR="CARD" TYPE Time=[BYTE s,m,h] REAL r60   PROC PrintB2(BYTE b) IF b<10 THEN Put('0) FI PrintB(b) RETURN   PROC PrintTime(Time POINTER t) PrintB2(t.h) Put(':) PrintB2(t.m) Put(':) PrintB2(t.s) RETURN   PROC Decode(CHAR ARRAY st Time POINTER t) CHAR ARRAY tmp   IF st(0)#8 THEN Break() FI SCopyS(tmp,st,1,2) t.h=ValB(tmp) SCopyS(tmp,st,4,5) t.m=ValB(tmp) SCopyS(tmp,st,7,8) t.s=ValB(tmp) RETURN   PROC TimeToSeconds(Time POINTER t REAL POINTER seconds) REAL r   IntToReal(t.h,seconds) RealMult(seconds,r60,seconds) IntToReal(t.m,r) RealAdd(seconds,r,seconds) RealMult(seconds,r60,seconds) IntToReal(t.s,r) RealAdd(seconds,r,seconds) RETURN   PROC SecondsToTime(REAL POINTER seconds Time POINTER t) REAL tmp1,tmp2   RealAssign(seconds,tmp1) RealMod(tmp1,r60,tmp2) t.s=RealToInt(tmp2) RealDivInt(tmp1,r60,tmp2) RealMod(tmp2,r60,tmp1) t.m=RealToInt(tmp1) RealDivInt(tmp2,r60,tmp1) t.h=RealToInt(tmp1) RETURN   PROC AverageTime(PTR ARRAY times BYTE count Time POINTER res) BYTE i Time t REAL avg,rcount,seconds,halfDay,day   IntToReal(0,avg) IntToReal(count,rcount) ValR("43200",halfDay) ;seconds in the half of day ValR("86400",day)  ;seconds in the whole day FOR i=0 TO count-1 DO Decode(times(i),t) TimeToSeconds(t,seconds) IF RealLess(seconds,halfDay) THEN RealAdd(seconds,day,seconds) ;correction of time FI RealAdd(avg,seconds,avg) OD RealDivInt(avg,rcount,avg) WHILE RealGreaterOrEqual(avg,day) DO RealSub(avg,day,avg) ;correction of time OD SecondsToTime(avg,res) RETURN   PROC Main() DEFINE COUNT="4" PTR ARRAY times(COUNT) Time t   Put(125) PutE() ;clear the screen IntToReal(60,r60) times(0)="23:00:17" times(1)="23:40:20" times(2)="00:12:45" times(3)="00:17:19"   AverageTime(times,COUNT,t) Print("Mean time is ") PrintTime(t) RETURN
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
#Ada
Ada
with Ada.Calendar.Formatting; with Ada.Command_Line; with Ada.Numerics.Elementary_Functions; with Ada.Strings.Fixed; with Ada.Text_IO;   procedure Mean_Time_Of_Day is   subtype Time is Ada.Calendar.Time; subtype Time_Of_Day is Ada.Calendar.Day_Duration; subtype Time_String is String (1 .. 8); -- "HH:MM:SS"   type Time_List is array (Positive range <>) of Time_String;   function Average_Time (List : Time_List) return Time_String is   function To_Time (Time_Image : Time_String) return Time is (Ada.Calendar.Formatting.Value ("2000-01-01 " & Time_Image));   function To_Time_Of_Day (TS : Time) return Time_Of_Day is use Ada.Calendar.Formatting; Hour_Part : constant Time_Of_Day := 60.0 * 60.0 * Hour (TS); Min_Part  : constant Time_Of_Day := 60.0 * Minute (TS); Sec_Part  : constant Time_Of_Day := Time_Of_Day (Second (TS)); begin return Hour_Part + Min_Part + Sec_Part; end To_Time_Of_Day;   function To_Time_Image (Angle : Time_Of_Day) return Time_String is use Ada.Calendar.Formatting; TOD : constant Time := Time_Of (Year => 2000, Month => 1, Day => 1, -- Not used Seconds => Angle); begin return Ada.Strings.Fixed.Tail (Image (TOD), Time_String'Length); end To_Time_Image;   function Average_Time_Of_Day (List : Time_List) return Time_Of_Day is use Ada.Numerics.Elementary_Functions; Cycle : constant Float := Float (Time_Of_Day'Last); X_Sum, Y_Sum : Float := 0.0; Angle  : Float; begin for Time_Stamp of List loop Angle := Float (To_Time_Of_Day (To_Time (Time_Stamp))); X_Sum := X_Sum + Cos (Angle, Cycle => Cycle); Y_Sum := Y_Sum + Sin (Angle, Cycle => Cycle); end loop; Angle := Arctan (Y_Sum, X_Sum, Cycle => Cycle); if Angle < 0.0 then Angle := Angle + Cycle; elsif Angle > Cycle then Angle := Angle - Cycle; end if; return Time_Of_Day (Angle); end Average_Time_Of_Day;   begin return To_Time_Image (Average_Time_Of_Day (List)); end Average_Time;   use Ada.Command_Line; List : Time_List (1 .. Argument_Count); begin if Argument_Count = 0 then raise Constraint_Error; end if;   for A in 1 .. Argument_Count loop List (A) := Argument (A); end loop; Ada.Text_IO.Put_Line (Average_Time (List));   exception when others => Ada.Text_IO.Put_Line ("Usage: mean_time_of_day <time-1> ..."); Ada.Text_IO.Put_Line (" <time-1> ... 'HH:MM:SS' format"); end Mean_Time_Of_Day;
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
#Common_Lisp
Common Lisp
(defun generic-mean (nums reduce-op final-op) (funcall final-op (reduce reduce-op nums)))   (defun a-mean (nums) (generic-mean nums #'+ (lambda (x) (/ x (length nums)))))   (defun g-mean (nums) (generic-mean nums #'* (lambda (x) (expt x (/ 1 (length nums))))))   (defun h-mean (nums) (generic-mean nums (lambda (x y) (+ x (/ 1 y))) (lambda (x) (/ (length nums) x))))   (let ((numbers (loop for i from 1 to 10 collect i))) (let ((a-mean (a-mean numbers)) (g-mean (g-mean numbers)) (h-mean (h-mean numbers))) (assert (> a-mean g-mean h-mean)) (format t "a-mean ~a~%" a-mean) (format t "g-mean ~a~%" g-mean) (format t "h-mean ~a~%" h-mean)))
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.
#AutoHotkey
AutoHotkey
BalancedTernary(n){ k = 0 if abs(n)<2 return n=1?"+":n=0?"0":"-" if n<1 negative := true, n:= -1*n while !break { d := Mod(n, 3**(k+1)) / 3**k d := d=2?-1:d n := n - (d * 3**k) r := (d=-1?"-":d=1?"+":0) . r k++ if (n = 3**k) r := "+" . r , break := true } if negative { StringReplace, r, r, -,n, all StringReplace, r, r, `+,-, all StringReplace, r, r, n,+, all } return r }
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.
#JavaScript
JavaScript
// Every line starting with a double slash will be ignored by the processing machine, // just like these two. // // Since the square root of 269,696 is approximately 519, we create a variable named "n" // and give it this value. n = 519   // The while-condition is in parentheses // * is for multiplication // % is for modulo operation // != is for "not equal" while ( ((n * n) % 1000000) != 269696 ) n = n + 1   // n is incremented until the while-condition is met, so n should finally be the // smallest positive integer whose square ends in the digits 269,696. To see n, we // need to send it to the monitoring device (named console). console.log(n)  
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#ALGOL_68
ALGOL 68
# generates a string of random opening and closing brackets. The number of # # each type of brackets is speccified in length # PROC get brackets = ( INT length ) STRING: BEGIN INT result length = length * 2; [ 1 : result length ]CHAR result; # initialise the brackets to all open brackets # FOR char pos TO result length DO result[ char pos ] := "[" OD; # set half of the brackets to close brackets # INT close count := 0; WHILE close count < length DO INT random pos = 1 + ENTIER ( next random * result length ); IF result[ random pos ] = "[" THEN close count +:= 1; result[ random pos ] := "]" FI OD; result END # get brackets # ;   # returns TRUE if the brackets string contains a correctly nested sequence # # of brackets, FALSE otherwise # PROC check brackets = ( STRING brackets ) BOOL: BEGIN INT depth := 0; FOR char pos FROM LWB brackets TO UPB brackets WHILE IF brackets[ char pos ] = "[" THEN depth +:= 1 ELSE depth -:= 1 FI; depth >= 0 DO SKIP OD; # depth will be 0 if we reached the end of the string and it was # # correct, non-0 otherwise # depth = 0 END # check brackets # ;   # procedure to test check brackets # PROC test check brackets = ( STRING brackets ) VOID: print( ( ( brackets + ": " + IF check brackets( brackets ) THEN "ok" ELSE "not ok" FI ) , newline ) ) ;   # test the bracket generation and checking PROCs # test check brackets( get brackets( 0 ) ); FOR length TO 12 DO TO 2 DO test check brackets( get brackets( length ) ) OD OD
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
#CoffeeScript
CoffeeScript
mode = (arr) -> # returns an array with the modes of arr, i.e. the # elements that appear most often in arr counts = {} for elem in arr counts[elem] ||= 0 counts[elem] += 1 max = 0 for key, cnt of counts max = cnt if cnt > max (key for key, cnt of counts when cnt == max)   console.log mode [1, 2, 2, 2, 3, 3, 3, 4, 4]
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
#Nim
Nim
import deques   proc simplemovingaverage(period: int): auto = assert period > 0   var summ, n = 0.0 values: Deque[float] for i in 1..period: values.addLast(0)   proc sma(x: float): float = values.addLast(x) summ += x - values.popFirst() n = min(n+1, float(period)) result = summ / n   return sma   var sma = simplemovingaverage(3) for i in 1..5: echo sma(float(i)) for i in countdown(5,1): echo sma(float(i))   echo ""   var sma2 = simplemovingaverage(5) for i in 1..5: echo sma2(float(i)) for i in countdown(5,1): echo sma2(float(i))
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
#AutoHotkey
AutoHotkey
MsgBox, % "The mean time is: " MeanTime(["23:00:17", "23:40:20", "00:12:45", "00:17:19"])   MeanTime(t, x=0, y=0) { static c := ATan(1) / 45 for k, v in t { n := StrSplit(v, ":") r := c * (n[1] * 3600 + n[2] * 60 + n[3]) / 240 x += Cos(r) y += Sin(r) } r := atan2(x, y) / c r := (r < 0 ? r + 360 : r) / 15 h := SubStr("00" Round(r // 1, 0), -1) s := SubStr("00" Round(Mod(m := Mod(r, 1) * 60, 1) * 60, 0), -1) m := SubStr("00" Round(m // 1, 0), -1) return, h ":" m ":" s }   atan2(x, y) { return dllcall("msvcrt\atan2", "Double",y, "Double",x, "CDECL Double") }
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
#D
D
import std.stdio, std.algorithm, std.range, std.functional;   auto aMean(T)(T data) pure nothrow @nogc { return data.sum / data.length; }   auto gMean(T)(T data) pure /*@nogc*/ { return data.reduce!q{a * b} ^^ (1.0 / data.length); }   auto hMean(T)(T data) pure /*@nogc*/ { return data.length / data.reduce!q{ 1.0 / a + b }; }   void main() { immutable m = [adjoin!(hMean, gMean, aMean)(iota(1.0L, 11.0L))[]]; writefln("%(%.19f %)", m); assert(m.isSorted); }
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.
#C
C
#include <stdio.h> #include <string.h>   void reverse(char *p) { size_t len = strlen(p); char *r = p + len - 1; while (p < r) { *p ^= *r; *r ^= *p; *p++ ^= *r--; } }   void to_bt(int n, char *b) { static char d[] = { '0', '+', '-' }; static int v[] = { 0, 1, -1 };   char *ptr = b; *ptr = 0;   while (n) { int r = n % 3; if (r < 0) { r += 3; }   *ptr = d[r]; *(++ptr) = 0;   n -= v[r]; n /= 3; }   reverse(b); }   int from_bt(const char *a) { int n = 0;   while (*a != '\0') { n *= 3; if (*a == '+') { n++; } else if (*a == '-') { n--; } a++; }   return n; }   char last_char(char *ptr) { char c;   if (ptr == NULL || *ptr == '\0') { return '\0'; }   while (*ptr != '\0') { ptr++; } ptr--;   c = *ptr; *ptr = 0; return c; }   void add(const char *b1, const char *b2, char *out) { if (*b1 != '\0' && *b2 != '\0') { char c1[16]; char c2[16]; char ob1[16]; char ob2[16]; char d[3] = { 0, 0, 0 }; char L1, L2;   strcpy(c1, b1); strcpy(c2, b2); L1 = last_char(c1); L2 = last_char(c2); if (L2 < L1) { L2 ^= L1; L1 ^= L2; L2 ^= L1; }   if (L1 == '-') { if (L2 == '0') { d[0] = '-'; } if (L2 == '-') { d[0] = '+'; d[1] = '-'; } } if (L1 == '+') { if (L2 == '0') { d[0] = '+'; } if (L2 == '-') { d[0] = '0'; } if (L2 == '+') { d[0] = '-'; d[1] = '+'; } } if (L1 == '0') { if (L2 == '0') { d[0] = '0'; } }   add(c1, &d[1], ob1); add(ob1, c2, ob2); strcpy(out, ob2);   d[1] = 0; strcat(out, d); } else if (*b1 != '\0') { strcpy(out, b1); } else if (*b2 != '\0') { strcpy(out, b2); } else { *out = '\0'; } }   void unary_minus(const char *b, char *out) { while (*b != '\0') { if (*b == '-') { *out++ = '+'; b++; } else if (*b == '+') { *out++ = '-'; b++; } else { *out++ = *b++; } } *out = '\0'; }   void subtract(const char *b1, const char *b2, char *out) { char buf[16]; unary_minus(b2, buf); add(b1, buf, out); }   void mult(const char *b1, const char *b2, char *out) { char r[16] = "0"; char t[16]; char c1[16]; char c2[16]; char *ptr = c2;   strcpy(c1, b1); strcpy(c2, b2);   reverse(c2);   while (*ptr != '\0') { if (*ptr == '+') { add(r, c1, t); strcpy(r, t); } if (*ptr == '-') { subtract(r, c1, t); strcpy(r, t); } strcat(c1, "0");   ptr++; }   ptr = r; while (*ptr == '0') { ptr++; } strcpy(out, ptr); }   int main() { const char *a = "+-0++0+"; char b[16]; const char *c = "+-++-"; char t[16]; char d[16];   to_bt(-436, b); subtract(b, c, t); mult(a, t, d);   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));   return 0; }
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.
#jq
jq
$ jq -n '1 | until( .*. | tostring | test("269696$"); .+1)' 25264
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.
#Julia
Julia
  function babbage(x::Integer) i = big(0) d = floor(log10(x)) + 1 while i ^ 2 % 10 ^ d != x i += 1 end return i end  
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
#ANTLR
ANTLR
  grammar balancedBrackets ;   options { language = Java; }   bb : {System.out.print("input is: ");} (balancedBrackets {System.out.print($balancedBrackets.text);})* NEWLINE {System.out.println();} ; balancedBrackets : OpenBracket balancedBrackets* CloseBracket ; OpenBracket : '[' ; CloseBracket : ']' ; NEWLINE : '\r'? '\n' ;  
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
#Common_Lisp
Common Lisp
(defun mode (sequence &rest hash-table-options) (let ((frequencies (apply #'make-hash-table hash-table-options))) (map nil (lambda (element) (incf (gethash element frequencies 0))) sequence) (let ((modes '()) (hifreq 0 )) (maphash (lambda (element frequency) (cond ((> frequency hifreq) (setf hifreq frequency modes (list element))) ((= frequency hifreq) (push element modes)))) frequencies) (values modes hifreq))))
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
#Objeck
Objeck
  use Collection;   class MovingAverage { @window : FloatQueue; @period : Int; @sum : Float;   New(period : Int) { @window := FloatQueue->New(); @period := period; }   method : NewNum(num : Float) ~ Nil { @sum += num; @window->Add(num); if(@window->Size() > @period) { @sum -= @window->Remove(); }; }   method : GetAvg() ~ Float { if(@window->IsEmpty()) { return 0; # technically the average is undefined };   return @sum / @window->Size(); }   function : Main(args : String[]) ~ Nil { testData := [1.0, 2.0, 3.0, 4.0, 5.0, 5.0, 4.0, 3.0, 2.0, 1.0]; windowSizes := [3.0, 5.0];   each(i : windowSizes) { windSize := windowSizes[i]; ma := MovingAverage->New(windSize); each(j : testData) { x := testData[j]; ma->NewNum(x); avg := ma->GetAvg(); "Next number = {$x}, SMA = {$avg}"->PrintLine(); }; IO.Console->PrintLine(); }; } }  
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
#AWK
AWK
#!/usr/bin/awk -f { c = atan2(0,-1)/(12*60*60); x=0.0; y=0.0; for (i=1; i<=NF; i++) { split($i,a,":"); p = (a[1]*3600+a[2]*60+a[3])*c; x += sin(p); y += cos(p); } p = atan2(x,y)/c; if (p<0) p += 24*60*60; print strftime("%T",p,1); }
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.
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program avltree64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   .equ NBVAL, 12   /*******************************************/ /* Structures */ /********************************************/ /* structure tree */ .struct 0 tree_root: // root pointer (or node right) .struct tree_root + 8 tree_size: // number of element of tree .struct tree_size + 8 tree_suite: .struct tree_suite + 24 // for alignement to node tree_fin: /* structure node tree */ .struct 0 node_right: // right pointer .struct node_right + 8 node_left: // left pointer .struct node_left + 8 node_value: // element value .struct node_value + 8 node_height: // element value .struct node_height + 8 node_parent: // element value .struct node_parent + 8 node_fin:   /*******************************************/ /* Initialized data */ /*******************************************/ .data szMessPreOrder: .asciz "PreOrder :\n" szCarriageReturn: .asciz "\n" /* datas error display */ szMessErreur: .asciz "Error detected.\n" szMessKeyDbl: .asciz "Key exists in tree.\n" szMessInsInv: .asciz "Insertion in inverse order.\n" /* datas message display */ szMessResult: .asciz "Ele: @ G: @ D: @ val @ h @ \npere @\n"   /*******************************************/ /* UnInitialized data */ /*******************************************/ .bss sZoneConv: .skip 24 stTree: .skip tree_fin // place to structure tree stTree1: .skip tree_fin // place to structure tree /*******************************************/ /* code section */ /*******************************************/ .text .global main main: mov x20,#1 // node tree value 1: // loop insertion in order ldr x0,qAdrstTree // structure tree address mov x1,x20 bl insertElement // add element value x1 cmp x0,-1 beq 99f add x20,x20,1 // increment value cmp x20,NBVAL // end ? ble 1b // no -> loop   ldr x0,qAdrstTree // structure tree address mov x1,11 // verif key dobble bl insertElement // add element value x1 cmp x0,-1 bne 2f ldr x0,qAdrszMessErreur bl affichageMess 2: ldr x0,qAdrszMessPreOrder // load verification bl affichageMess ldr x3,qAdrstTree // tree root address (begin structure) ldr x0,[x3,tree_root] ldr x1,qAdrdisplayElement // function to execute bl preOrder     ldr x0,qAdrszMessInsInv bl affichageMess mov x20,NBVAL // node tree value 3: // loop insertion inverse order ldr x0,qAdrstTree1 // structure tree address mov x1,x20 bl insertElement // add element value x1 cmp x0,-1 beq 99f sub x20,x20,1 // increment value cmp x20,0 // end ? bgt 3b // no -> loop   ldr x0,qAdrszMessPreOrder // load verification bl affichageMess ldr x3,qAdrstTree1 // tree root address (begin structure) ldr x0,[x3,tree_root] ldr x1,qAdrdisplayElement // function to execute bl preOrder   // search value ldr x0,qAdrstTree1 // tree root address (begin structure) mov x1,11 // value to search bl searchTree cmp x0,-1 beq 100f mov x2,x0 ldr x0,qAdrszMessKeyDbl // key exists bl affichageMess // suppresssion previous value mov x0,x2 ldr x1,qAdrstTree1 bl supprimer   ldr x0,qAdrszMessPreOrder // verification bl affichageMess ldr x3,qAdrstTree1 // tree root address (begin structure) ldr x0,[x3,tree_root] ldr x1,qAdrdisplayElement // function to execute bl preOrder   b 100f 99: // display error ldr x0,qAdrszMessErreur bl affichageMess 100: // standard end of the program mov x8, #EXIT // request to exit program svc 0 // perform system call qAdrszMessPreOrder: .quad szMessPreOrder qAdrszMessErreur: .quad szMessErreur qAdrszCarriageReturn: .quad szCarriageReturn qAdrstTree: .quad stTree qAdrstTree1: .quad stTree1 qAdrdisplayElement: .quad displayElement qAdrszMessInsInv: .quad szMessInsInv /******************************************************************/ /* insert element in the tree */ /******************************************************************/ /* x0 contains the address of the tree structure */ /* x1 contains the value of element */ /* x0 returns address of element or - 1 if error */ insertElement: // INFO: insertElement stp x1,lr,[sp,-16]! // save registers mov x6,x0 // save head mov x0,#node_fin // reservation place one element bl allocHeap cmp x0,#-1 // allocation error beq 100f mov x5,x0 str x1,[x5,#node_value] // store value in address heap mov x3,#0 str x3,[x5,#node_left] // init left pointer with zero str x3,[x5,#node_right] // init right pointer with zero str x3,[x5,#node_height] // init balance with zero ldr x2,[x6,#tree_size] // load tree size cmp x2,#0 // 0 element ? bne 1f str x5,[x6,#tree_root] // yes -> store in root b 4f 1: // else search free address in tree ldr x3,[x6,#tree_root] // start with address root 2: // begin loop to insertion ldr x4,[x3,#node_value] // load key cmp x1,x4 beq 6f // key equal blt 3f // key < // key > insertion right ldr x8,[x3,#node_right] // node empty ? cmp x8,#0 csel x3,x8,x3,ne // current = right node if not //movne x3,x8 // no -> next node bne 2b // and loop str x5,[x3,#node_right] // store node address in right pointer b 4f 3: // left ldr x8,[x3,#node_left] // left pointer empty ? cmp x8,#0 csel x3,x8,x3,ne // current = left node if not //movne x3,x8 // bne 2b // no -> loop str x5,[x3,#node_left] // store node address in left pointer 4: str x3,[x5,#node_parent] // store parent mov x4,#1 str x4,[x5,#node_height] // store height = 1 mov x0,x5 // begin node to requilbrate mov x1,x6 // head address bl equilibrer   5: add x2,x2,#1 // increment tree size str x2,[x6,#tree_size] mov x0,#0 b 100f 6: // key equal ? ldr x0,qAdrszMessKeyDbl bl affichageMess mov x0,#-1 b 100f 100: ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 qAdrszMessKeyDbl: .quad szMessKeyDbl /******************************************************************/ /* equilibrer after insertion */ /******************************************************************/ /* x0 contains the address of the node */ /* x1 contains the address of head */ equilibrer: // INFO: equilibrer stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers stp x4,x5,[sp,-16]! // save registers stp x6,x7,[sp,-16]! // save registers mov x3,#0 // balance factor 1: // begin loop ldr x5,[x0,#node_parent] // load father cmp x5,#0 // end ? beq 8f cmp x3,#2 // right tree too long beq 8f cmp x3,#-2 // left tree too long beq 8f mov x6,x0 // s = current ldr x0,[x6,#node_parent] // current = father ldr x7,[x0,#node_left] mov x4,#0 cmp x7,#0 beq 2f ldr x4,[x7,#node_height] // height left tree 2: ldr x7,[x0,#node_right] mov x2,#0 cmp x7,#0 beq 3f ldr x2,[x7,#node_height] // height right tree 3: cmp x4,x2 ble 4f add x4,x4,#1 str x4,[x0,#node_height] b 5f 4: add x2,x2,#1 str x2,[x0,#node_height] 5: ldr x7,[x0,#node_right] mov x4,0 cmp x7,#0 beq 6f ldr x4,[x7,#node_height] 6: ldr x7,[x0,#node_left] mov x2,0 cmp x7,#0 beq 7f ldr x2,[x7,#node_height] 7: sub x3,x4,x2 // compute balance factor b 1b 8: cmp x3,#2 beq 9f cmp x3,#-2 beq 9f b 100f 9: mov x3,x1 mov x4,x0 mov x1,x6 bl equiUnSommet // change head address ? ldr x2,[x3,#tree_root] cmp x2,x4 bne 100f str x6,[x3,#tree_root] 100: ldp x6,x7,[sp],16 // restaur 2 registers ldp x4,x5,[sp],16 // restaur 2 registers ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* equilibre 1 sommet */ /******************************************************************/ /* x0 contains the address of the node */ /* x1 contains the address of the node */ equiUnSommet: // INFO: equiUnSommet stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers stp x4,x5,[sp,-16]! // save registers stp x6,x7,[sp,-16]! // save registers mov x5,x0 // save p mov x6,x1 // s ldr x2,[x5,#node_left] cmp x2,x6 bne 6f ldr x7,[x5,#node_right] mov x4,#0 cmp x7,#0 beq 1f ldr x4,[x7,#node_height] 1: ldr x7,[x5,#node_left] mov x2,0 cmp x7,#0 beq 2f ldr x2,[x7,#node_height] 2: sub x3,x4,x2 cmp x3,#-2 bne 100f ldr x7,[x6,#node_right] mov x4,0 cmp x7,#0 beq 3f ldr x4,[x7,#node_height] 3: ldr x7,[x6,#node_left] mov x2,0 cmp x7,#0 beq 4f ldr x2,[x7,#node_height] 4: sub x3,x4,x2 cmp x3,#1 bge 5f mov x0,x5 bl rotRight b 100f 5: mov x0,x6 bl rotLeft mov x0,x5 bl rotRight b 100f   6: ldr x7,[x5,#node_right] mov x4,0 cmp x7,#0 beq 7f ldr x4,[x7,#node_height] 7: ldr x7,[x5,#node_left] mov x2,0 cmp x7,#0 beq 8f ldr x2,[x7,#node_height] 8: sub x3,x4,x2 cmp x3,2 bne 100f ldr x7,[x6,#node_right] mov x4,0 cmp x7,#0 beq 9f ldr x4,[x7,#node_height] 9: ldr x7,[x6,#node_left] mov x2,0 cmp x7,#0 beq 10f ldr x2,[x7,#node_height] 10: sub x3,x4,x2 cmp x3,#-1 ble 11f mov x0,x5 bl rotLeft b 100f 11: mov x0,x6 bl rotRight mov x0,x5 bl rotLeft   100: ldp x6,x7,[sp],16 // restaur 2 registers ldp x4,x5,[sp],16 // restaur 2 registers ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* right rotation */ /******************************************************************/ /* x0 contains the address of the node */ rotRight: // INFO: rotRight stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers stp x4,x5,[sp,-16]! // save registers // x2 x2 // x0 x1 // x1 x0 // x3 x3 ldr x1,[x0,#node_left] // load left children ldr x2,[x0,#node_parent] // load father cmp x2,#0 // no father ??? beq 2f ldr x3,[x2,#node_left] // load left node father cmp x3,x0 // equal current node ? bne 1f str x1,[x2,#node_left] // yes store left children b 2f 1: str x1,[x2,#node_right] // no store right 2: str x2,[x1,#node_parent] // change parent str x1,[x0,#node_parent] ldr x3,[x1,#node_right] str x3,[x0,#node_left] cmp x3,#0 beq 3f str x0,[x3,#node_parent] // change parent node left 3: str x0,[x1,#node_right]   ldr x3,[x0,#node_left] // compute newbalance factor mov x4,0 cmp x3,#0 beq 4f ldr x4,[x3,#node_height] 4: ldr x3,[x0,#node_right] mov x5,0 cmp x3,#0 beq 5f ldr x5,[x3,#node_height] 5: cmp x4,x5 ble 6f add x4,x4,#1 str x4,[x0,#node_height] b 7f 6: add x5,x5,#1 str x5,[x0,#node_height] 7: // ldr x3,[x1,#node_left] // compute new balance factor mov x4,0 cmp x3,#0 beq 8f ldr x4,[x3,#node_height] 8: ldr x3,[x1,#node_right] mov x5,0 cmp x3,#0 beq 9f ldr x5,[x3,#node_height] 9: cmp x4,x5 ble 10f add x4,x4,#1 str x4,[x1,#node_height] b 100f 10: add x5,x5,#1 str x5,[x1,#node_height] 100: ldp x4,x5,[sp],16 // restaur 2 registers ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* left rotation */ /******************************************************************/ /* x0 contains the address of the node sommet */ rotLeft: // INFO: rotLeft stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers stp x4,x5,[sp,-16]! // save registers // x2 x2 // x0 x1 // x1 x0 // x3 x3 ldr x1,[x0,#node_right] // load right children ldr x2,[x0,#node_parent] // load father (racine) cmp x2,#0 // no father ??? beq 2f ldr x3,[x2,#node_left] // load left node father cmp x3,x0 // equal current node ? bne 1f str x1,[x2,#node_left] // yes store left children b 2f 1: str x1,[x2,#node_right] // no store to right 2: str x2,[x1,#node_parent] // change parent of right children str x1,[x0,#node_parent] // change parent of sommet ldr x3,[x1,#node_left] // left children str x3,[x0,#node_right] // left children pivot exists ? cmp x3,#0 beq 3f str x0,[x3,#node_parent] // yes store in 3: str x0,[x1,#node_left] // ldr x3,[x0,#node_left] // compute new height for old summit mov x4,0 cmp x3,#0 beq 4f ldr x4,[x3,#node_height] // left height 4: ldr x3,[x0,#node_right] mov x5,0 cmp x3,#0 beq 5f ldr x5,[x3,#node_height] // right height 5: cmp x4,x5 ble 6f add x4,x4,#1 str x4,[x0,#node_height] // if right > left b 7f 6: add x5,x5,#1 str x5,[x0,#node_height] // if left > right 7: // ldr x3,[x1,#node_left] // compute new height for new mov x4,0 cmp x3,#0 beq 8f ldr x4,[x3,#node_height] 8: ldr x3,[x1,#node_right] mov x5,0 cmp x3,#0 beq 9f ldr x5,[x3,#node_height] 9: cmp x4,x5 ble 10f add x4,x4,#1 str x4,[x1,#node_height] b 100f 10: add x5,x5,#1 str x5,[x1,#node_height] 100: ldp x4,x5,[sp],16 // restaur 2 registers ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* search value in tree */ /******************************************************************/ /* x0 contains the address of structure of tree */ /* x1 contains the value to search */ searchTree: // INFO: searchTree stp x2,lr,[sp,-16]! // save registers stp x3,x4,[sp,-16]! // save registers ldr x2,[x0,#tree_root]   1: // begin loop ldr x4,[x2,#node_value] // load key cmp x1,x4 beq 3f // key equal blt 2f // key < // key > insertion right ldr x3,[x2,#node_right] // node empty ? cmp x3,#0 csel x2,x3,x2,ne //movne x2,x3 // no -> next node bne 1b // and loop mov x0,#-1 // not find b 100f 2: // left ldr x3,[x2,#node_left] // left pointer empty ? cmp x3,#0 csel x2,x3,x2,ne bne 1b // no -> loop mov x0,#-1 // not find b 100f 3: mov x0,x2 // return node address 100: ldp x3,x4,[sp],16 // restaur 2 registers ldp x2,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* suppression node */ /******************************************************************/ /* x0 contains the address of the node */ /* x1 contains structure tree address */ supprimer: // INFO: supprimer stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers stp x4,x5,[sp,-16]! // save registers stp x6,x7,[sp,-16]! // save registers ldr x1,[x0,#node_left] cmp x1,#0 bne 5f ldr x1,[x0,#node_right] cmp x1,#0 bne 5f // is a leaf mov x4,#0 ldr x3,[x0,#node_parent] // father cmp x3,#0 bne 11f str x4,[x1,#tree_root] b 100f 11: ldr x1,[x3,#node_left] cmp x1,x0 bne 2f str x4,[x3,#node_left] // suppression left children ldr x5,[x3,#node_right] mov x6,#0 cmp x5,#0 beq 12f ldr x6,[x5,#node_height] 12: add x6,x6,#1 str x6,[x3,#node_height] b 3f 2: // suppression right children str x4,[x3,#node_right] ldr x5,[x3,#node_left] mov x6,#0 cmp x5,#0 beq 21f ldr x6,[x5,#node_height] 21: add x6,x6,#1 str x6,[x3,#node_height] 3: // new balance mov x0,x3 bl equilibrerSupp b 100f 5: // is not à leaf ldr x7,[x0,#node_right] cmp x7,#0 beq 7f mov x2,x0 mov x0,x7 6: ldr x6,[x0,#node_left] // search the litle element cmp x6,#0 beq 9f mov x0,x6 b 6b 7: ldr x7,[x0,#node_left] cmp x7,#0 beq 9f mov x2,x0 mov x0,x7 8: ldr x6,[x0,#node_right] // search the great element cmp x6,#0 beq 9f mov x0,x6 b 8b 9: ldr x5,[x0,#node_value] // copy value str x5,[x2,#node_value] bl supprimer // suppression node x0 100: ldp x6,x7,[sp],16 // restaur 2 registers ldp x4,x5,[sp],16 // restaur 2 registers ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30   /******************************************************************/ /* equilibrer after suppression */ /******************************************************************/ /* x0 contains the address of the node */ /* x1 contains the address of head */ equilibrerSupp: // INFO: equilibrerSupp stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers stp x4,x5,[sp,-16]! // save registers stp x6,x7,[sp,-16]! // save registers mov x3,#1 // balance factor ldr x2,[x1,#tree_root] 1: ldr x5,[x0,#node_parent] // load father cmp x5,#0 // no father beq 100f cmp x3,#0 // balance equilibred beq 100f mov x6,x0 // save entry node ldr x0,[x6,#node_parent] // current = father ldr x7,[x0,#node_left] mov x4,#0 cmp x7,#0 b 11f ldr x4,[x7,#node_height] // height left tree 11: ldr x7,[x0,#node_right] mov x5,#0 cmp x7,#0 beq 12f ldr x5,[x7,#node_height] // height right tree 12: cmp x4,x5 ble 13f add x4,x4,1 str x4,[x0,#node_height] b 14f 13: add x5,x5,1 str x5,[x0,#node_height] 14: ldr x7,[x0,#node_right] mov x4,#0 cmp x7,#0 beq 15f ldr x4,[x7,#node_height] 15: ldr x7,[x0,#node_left] mov x5,0 cmp x7,#0 beq 16f ldr x5,[x7,#node_height] 16: sub x3,x4,x5 // compute balance factor mov x2,x1 mov x7,x0 // save current mov x1,x6 bl equiUnSommet // change head address ? cmp x2,x7 bne 17f str x6,[x3,#tree_root] 17: mov x0,x7 // restaur current b 1b   100: ldp x6,x7,[sp],16 // restaur 2 registers ldp x4,x5,[sp],16 // restaur 2 registers ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* preOrder */ /******************************************************************/ /* x0 contains the address of the node */ /* x1 function address */ preOrder: // INFO: preOrder stp x2,lr,[sp,-16]! // save registers cmp x0,#0 beq 100f mov x2,x0 blr x1 // call function ldr x0,[x2,#node_left] bl preOrder ldr x0,[x2,#node_right] bl preOrder 100: ldp x2,lr,[sp],16 // restaur 2 registers ret // return to address lr x30   /******************************************************************/ /* display node */ /******************************************************************/ /* x0 contains node address */ displayElement: // INFO: displayElement stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers stp x4,x5,[sp,-16]! // save registers mov x2,x0 ldr x1,qAdrsZoneConv bl conversion16 //strb wzr,[x1,x0] ldr x0,qAdrszMessResult ldr x1,qAdrsZoneConv bl strInsertAtCharInc mov x3,x0 ldr x0,[x2,#node_left] ldr x1,qAdrsZoneConv bl conversion16 //strb wzr,[x1,x0] mov x0,x3 ldr x1,qAdrsZoneConv bl strInsertAtCharInc mov x3,x0 ldr x0,[x2,#node_right] ldr x1,qAdrsZoneConv bl conversion16 //strb wzr,[x1,x0] mov x0,x3 ldr x1,qAdrsZoneConv bl strInsertAtCharInc mov x3,x0 ldr x0,[x2,#node_value] ldr x1,qAdrsZoneConv bl conversion10 //strb wzr,[x1,x0] mov x0,x3 ldr x1,qAdrsZoneConv bl strInsertAtCharInc mov x3,x0 ldr x0,[x2,#node_height] ldr x1,qAdrsZoneConv bl conversion10 //strb wzr,[x1,x0] mov x0,x3 ldr x1,qAdrsZoneConv bl strInsertAtCharInc mov x3,x0 ldr x0,[x2,#node_parent] ldr x1,qAdrsZoneConv bl conversion16 //strb wzr,[x1,x0] mov x0,x3 ldr x1,qAdrsZoneConv bl strInsertAtCharInc bl affichageMess 100: ldp x4,x5,[sp],16 // restaur 2 registers ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 qAdrszMessResult: .quad szMessResult qAdrsZoneConv: .quad sZoneConv   /******************************************************************/ /* memory allocation on the heap */ /******************************************************************/ /* x0 contains the size to allocate */ /* x0 returns address of memory heap or - 1 if error */ /* CAUTION : The size of the allowance must be a multiple of 4 */ allocHeap: stp x1,lr,[sp,-16]! // save registers stp x2,x8,[sp,-16]! // save registers // allocation mov x1,x0 // save size mov x0,0 // read address start heap mov x8,BRK // call system 'brk' svc 0 mov x2,x0 // save address heap for return add x0,x0,x1 // reservation place for size mov x8,BRK // call system 'brk' svc 0 cmp x0,-1 // allocation error beq 100f mov x0,x2 // return address memory heap 100: ldp x2,x8,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
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
#11l
11l
F mean_angle(angles) V x = sum(angles.map(a -> cos(radians(a)))) / angles.len V y = sum(angles.map(a -> sin(radians(a)))) / angles.len R degrees(atan2(y, x))   print(mean_angle([350, 10])) print(mean_angle([90, 180, 270, 360])) print(mean_angle([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
#11l
11l
F median(aray) V srtd = sorted(aray) V alen = srtd.len R 0.5 * (srtd[(alen - 1) I/ 2] + srtd[alen I/ 2])   print(median([4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2])) print(median([4.1, 7.2, 1.7, 9.3, 4.4, 3.2]))
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of positive integers. The most common of the three means, the arithmetic mean, is the sum of the list divided by its length: A ( x 1 , … , x n ) = x 1 + ⋯ + x n n {\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}} The geometric mean is the n {\displaystyle n} th root of the product of the list: G ( x 1 , … , x n ) = x 1 ⋯ x n n {\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}} The harmonic mean is n {\displaystyle n} divided by the sum of the reciprocal of each item in the list: H ( x 1 , … , x n ) = n 1 x 1 + ⋯ + 1 x n {\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}} See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#Delphi
Delphi
program AveragesPythagoreanMeans;   {$APPTYPE CONSOLE}   uses Types, Math;   function ArithmeticMean(aArray: TDoubleDynArray): Double; var lValue: Double; begin Result := 0; for lValue in aArray do Result := Result + lValue; if Result > 0 then Result := Result / Length(aArray); end;   function GeometricMean(aArray: TDoubleDynArray): Double; var lValue: Double; begin Result := 1; for lValue in aArray do Result := Result * lValue; Result := Power(Result, 1 / Length(aArray)); end;   function HarmonicMean(aArray: TDoubleDynArray): Double; var lValue: Double; begin Result := 0; for lValue in aArray do Result := Result + 1 / lValue; Result := Length(aArray) / Result; end;   var lSourceArray: TDoubleDynArray; AMean, GMean, HMean: Double; begin lSourceArray := TDoubleDynArray.Create(1,2,3,4,5,6,7,8,9,10); AMean := ArithmeticMean(lSourceArray)); GMean := GeometricMean(lSourceArray)); HMean := HarmonicMean(lSourceArray)); if (AMean >= GMean) and (GMean >= HMean) then Writeln(AMean, " ≥ ", GMean, " ≥ ", HMean) else writeln("Error!"); 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.
#C.23
C#
using System; using System.Text; using System.Collections.Generic;   public class BalancedTernary { public static void Main() { BalancedTernary a = new BalancedTernary("+-0++0+"); System.Console.WriteLine("a: " + a + " = " + a.ToLong()); BalancedTernary b = new BalancedTernary(-436); System.Console.WriteLine("b: " + b + " = " + b.ToLong()); BalancedTernary c = new BalancedTernary("+-++-"); System.Console.WriteLine("c: " + c + " = " + c.ToLong()); BalancedTernary d = a * (b - c); System.Console.WriteLine("a * (b - c): " + d + " = " + d.ToLong()); }   private enum BalancedTernaryDigit { MINUS = -1, ZERO = 0, PLUS = 1 }   private BalancedTernaryDigit[] value;   // empty = 0 public BalancedTernary() { this.value = new BalancedTernaryDigit[0]; }   // create from String public BalancedTernary(String str) { this.value = new BalancedTernaryDigit[str.Length]; for (int i = 0; i < str.Length; ++i) { switch (str[i]) { case '-': this.value[i] = BalancedTernaryDigit.MINUS; break; case '0': this.value[i] = BalancedTernaryDigit.ZERO; break; case '+': this.value[i] = BalancedTernaryDigit.PLUS; break; default: throw new ArgumentException("Unknown Digit: " + str[i]); } } Array.Reverse(this.value); }   // convert long integer public BalancedTernary(long l) { List<BalancedTernaryDigit> value = new List<BalancedTernaryDigit>(); int sign = Math.Sign(l); l = Math.Abs(l);   while (l != 0) { byte rem = (byte)(l % 3); switch (rem) { case 0: case 1: value.Add((BalancedTernaryDigit)rem); l /= 3; break; case 2: value.Add(BalancedTernaryDigit.MINUS); l = (l + 1) / 3; break; } }   this.value = value.ToArray(); if (sign < 0) { this.Invert(); } }   // copy constructor public BalancedTernary(BalancedTernary origin) { this.value = new BalancedTernaryDigit[origin.value.Length]; Array.Copy(origin.value, this.value, origin.value.Length); }   // only for internal use private BalancedTernary(BalancedTernaryDigit[] value) { int end = value.Length - 1; while (value[end] == BalancedTernaryDigit.ZERO) --end; this.value = new BalancedTernaryDigit[end + 1]; Array.Copy(value, this.value, end + 1); }   // invert the values private void Invert() { for (int i=0; i < this.value.Length; ++i) { this.value[i] = (BalancedTernaryDigit)(-(int)this.value[i]); } }   // convert to string override public String ToString() { StringBuilder result = new StringBuilder(); for (int i = this.value.Length - 1; i >= 0; --i) { switch (this.value[i]) { case BalancedTernaryDigit.MINUS: result.Append('-'); break; case BalancedTernaryDigit.ZERO: result.Append('0'); break; case BalancedTernaryDigit.PLUS: result.Append('+'); break; } } return result.ToString(); }   // convert to long public long ToLong() { long result = 0; int digit; for (int i = 0; i < this.value.Length; ++i) { result += (long)this.value[i] * (long)Math.Pow(3.0, (double)i); } return result; }   // unary minus public static BalancedTernary operator -(BalancedTernary origin) { BalancedTernary result = new BalancedTernary(origin); result.Invert(); return result; }   // addition of digits private static BalancedTernaryDigit carry = BalancedTernaryDigit.ZERO; private static BalancedTernaryDigit Add(BalancedTernaryDigit a, BalancedTernaryDigit b) { if (a != b) { carry = BalancedTernaryDigit.ZERO; return (BalancedTernaryDigit)((int)a + (int)b); } else { carry = a; return (BalancedTernaryDigit)(-(int)b); } }   // addition of balanced ternary numbers public static BalancedTernary operator +(BalancedTernary a, BalancedTernary b) { int maxLength = Math.Max(a.value.Length, b.value.Length); BalancedTernaryDigit[] resultValue = new BalancedTernaryDigit[maxLength + 1]; for (int i=0; i < maxLength; ++i) { if (i < a.value.Length) { resultValue[i] = Add(resultValue[i], a.value[i]); resultValue[i+1] = carry; } else { carry = BalancedTernaryDigit.ZERO; }   if (i < b.value.Length) { resultValue[i] = Add(resultValue[i], b.value[i]); resultValue[i+1] = Add(resultValue[i+1], carry); } } return new BalancedTernary(resultValue); }   // subtraction of balanced ternary numbers public static BalancedTernary operator -(BalancedTernary a, BalancedTernary b) { return a + (-b); }   // multiplication of balanced ternary numbers public static BalancedTernary operator *(BalancedTernary a, BalancedTernary b) { BalancedTernaryDigit[] longValue = a.value; BalancedTernaryDigit[] shortValue = b.value; BalancedTernary result = new BalancedTernary(); if (a.value.Length < b.value.Length) { longValue = b.value; shortValue = a.value; }   for (int i = 0; i < shortValue.Length; ++i) { if (shortValue[i] != BalancedTernaryDigit.ZERO) { BalancedTernaryDigit[] temp = new BalancedTernaryDigit[i + longValue.Length]; for (int j = 0; j < longValue.Length; ++j) { temp[i+j] = (BalancedTernaryDigit)((int)shortValue[i] * (int)longValue[j]); } result = result + new BalancedTernary(temp); } } return result; } }
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.
#Kotlin
Kotlin
fun main(args: Array<String>) { var number = 520L var square = 520 * 520L   while (true) { val last6 = square.toString().takeLast(6) if (last6 == "269696") { println("The smallest number is $number whose square is $square") return } number += 2 square = number * number } }
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
#APL
APL
gen ← (⊂+?+)⍨ ⌷ ('[]'/⍨⊢) bal ← (((|≡⊢)+\) ∧ 0=+/)(+⌿1 ¯1×[1]'[]'∘.=⊢)
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
#D
D
import std.stdio, std.algorithm, std.array;   auto mode(T)(T[] items) pure /*nothrow @safe*/ { int[T] aa; foreach (item; items) aa[item]++; immutable m = aa.byValue.reduce!max; return aa.byKey.filter!(k => aa[k] == m); }   void main() /*@safe*/ { auto data = [1, 2, 3, 1, 2, 4, 2, 5, 3, 3, 1, 3, 6]; writeln("Mode: ", data.mode);   data ~= 2; writeln("Mode: ", data.mode); }
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
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   @interface MovingAverage : NSObject { unsigned int period; NSMutableArray *window; double sum; } - (instancetype)initWithPeriod:(unsigned int)thePeriod; @end   @implementation MovingAverage   // init with default period - (instancetype)init { self = [super init]; if(self) { period = 10; window = [[NSMutableArray alloc] init]; sum = 0.0; } return self; }   // init with specified period - (instancetype)initWithPeriod:(unsigned int)thePeriod { self = [super init]; if(self) { period = thePeriod; window = [[NSMutableArray alloc] init]; sum = 0.0; } return self; }   // add a new number to the window - (void)add:(double)val { sum += val; [window addObject:@(val)]; if([window count] > period) { NSNumber *n = window[0]; sum -= [n doubleValue]; [window removeObjectAtIndex:0]; } }   // get the average value - (double)avg { if([window count] == 0) { return 0; // technically the average is undefined } return sum / [window count]; }   // set the period, resizes current window - (void)setPeriod:(unsigned int)thePeriod { // make smaller? if(thePeriod < [window count]) { for(int i = 0; i < thePeriod; ++i) { NSNumber *n = window[0]; sum -= [n doubleValue]; [window removeObjectAtIndex:0]; } } period = thePeriod; }   // get the period (window size) - (unsigned int)period { return period; }   // clear the window and current sum - (void)clear { [window removeAllObjects]; sum = 0; }   @end   int main (int argc, const char * argv[]) { @autoreleasepool { double testData[10] = {1,2,3,4,5,5,4,3,2,1}; int periods[2] = {3,5}; for(int i = 0; i < 2; ++i) { MovingAverage *ma = [[MovingAverage alloc] initWithPeriod:periods[i]]; for(int j = 0; j < 10; ++j) { [ma add:testData[j]]; NSLog(@"Next number = %f, SMA = %f", testData[j], [ma avg]); } NSLog(@"\n"); } } return 0; }
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
#BBC_BASIC
BBC BASIC
nTimes% = 4 DATA 23:00:17, 23:40:20, 00:12:45, 00:17:19   DIM angles(nTimes%-1) FOR N% = 0 TO nTimes%-1 READ tim$ angles(N%) = FNtimetoangle(tim$) NEXT PRINT "Mean time is " FNangletotime(FNmeanangle(angles(), nTimes%)) END   DEF FNtimetoangle(t$) LOCAL A%, I% REPEAT A% = A% * 60 + VAL(t$) I% = INSTR(t$, ":") t$ = MID$(t$, I%+1) UNTIL I% = 0 = A% / 240 - 180   DEF FNangletotime(a) LOCAL A%, I%, t$ A% = INT((a + 180) * 240 + 0.5) FOR I% = 1 TO 3 t$ = RIGHT$("0" + STR$(A% MOD 60), 2) + ":" + t$ A% DIV= 60 NEXT = LEFT$(t$)   DEF FNmeanangle(angles(), N%) LOCAL I%, addsin, addcos FOR I% = 0 TO N%-1 addsin += SINRADangles(I%) addcos += COSRADangles(I%) NEXT = DEGFNatan2(addsin, addcos)   DEF FNatan2(y,x) : ON ERROR LOCAL = SGN(y)*PI/2 IF x>0 THEN = ATN(y/x) ELSE IF y>0 THEN = ATN(y/x)+PI ELSE = ATN(y/x)-PI
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
#C
C
#include<stdlib.h> #include<math.h> #include<stdio.h>   typedef struct { int hour, minute, second; } digitime;   double timeToDegrees (digitime time) { return (360 * time.hour / 24.0 + 360 * time.minute / (24 * 60.0) + 360 * time.second / (24 * 3600.0)); }   digitime timeFromDegrees (double angle) { digitime d; double totalSeconds = 24 * 60 * 60 * angle / 360;   d.second = (int) totalSeconds % 60; d.minute = ((int) totalSeconds % 3600 - d.second) / 60; d.hour = (int) totalSeconds / 3600;   return d; }   double meanAngle (double *angles, int size) { double y_part = 0, x_part = 0; int i;   for (i = 0; i < size; i++) { x_part += cos (angles[i] * M_PI / 180); y_part += sin (angles[i] * M_PI / 180); }   return atan2 (y_part / size, x_part / size) * 180 / M_PI; }   int main () { digitime *set, meanTime; int inputs, i; double *angleSet, angleMean;   printf ("Enter number of inputs : "); scanf ("%d", &inputs); set = malloc (inputs * sizeof (digitime)); angleSet = malloc (inputs * sizeof (double)); printf ("\n\nEnter the data separated by a space between each unit : ");   for (i = 0; i < inputs; i++) { scanf ("%d:%d:%d", &set[i].hour, &set[i].minute, &set[i].second); angleSet[i] = timeToDegrees (set[i]); }   meanTime = timeFromDegrees (360 + meanAngle (angleSet, inputs));   printf ("\n\nThe mean time is : %d:%d:%d", meanTime.hour, meanTime.minute, meanTime.second); return 0; }
http://rosettacode.org/wiki/AVL_tree
AVL tree
This page uses content from Wikipedia. The original article was at AVL tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In computer science, an AVL tree is a self-balancing binary search tree. 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.
#Ada
Ada
  with Ada.Text_IO, Ada.Finalization, Ada.Unchecked_Deallocation;   procedure Main is   generic type Key_Type is private; with function "<"(a, b : Key_Type) return Boolean is <>; with function "="(a, b : Key_Type) return Boolean is <>; with function "<="(a, b : Key_Type) return Boolean is <>; package AVL_Tree is type Tree is tagged limited private; function insert(self : in out Tree; key : Key_Type) return Boolean; procedure delete(self : in out Tree; key : Key_Type); procedure print_balance(self : in out Tree);   private type Height_Amt is range -1 .. Integer'Last;   -- Since only one key is inserted before each rebalance, the balance of -- all trees/subtrees will stay in range -2 .. 2 type Balance_Amt is range -2 .. 2;   type Node; type Node_Ptr is access Node; type Node is new Ada.Finalization.Limited_Controlled with record left, right, parent : Node_Ptr := null; key : Key_Type; balance : Balance_Amt := 0; end record; overriding procedure Finalize(self : in out Node); subtype Node_Parent is Ada.Finalization.Limited_Controlled;   type Tree is new Ada.Finalization.Limited_Controlled with record root : Node_Ptr := null; end record; overriding procedure Finalize(self : in out Tree);   end AVL_Tree;   package body AVL_Tree is   procedure Free_Node is new Ada.Unchecked_Deallocation(Node, Node_Ptr);   overriding procedure Finalize(self : in out Node) is begin Free_Node(self.left); Free_Node(self.right); end Finalize;   overriding procedure Finalize(self : in out Tree) is begin Free_Node(self.root); end Finalize;     function height(n : Node_Ptr) return Height_Amt is begin if n = null then return -1; else return 1 + Height_Amt'Max(height(n.left), height(n.right)); end if; end height;   procedure set_balance(n : not null Node_Ptr) is begin n.balance := Balance_Amt(height(n.right) - height(n.left)); end set_balance;   procedure update_parent(parent : Node_Ptr; new_child : Node_Ptr; old_child : Node_Ptr) is begin if parent /= null then if parent.right = old_child then parent.right := new_child; else parent.left := new_child; end if; end if; end update_parent;   function rotate_left(a : not null Node_Ptr) return Node_Ptr is b : Node_Ptr := a.right; begin b.parent := a.parent; a.right := b.left; if a.right /= null then a.right.parent := a; end if; b.left := a; a.parent := b; update_parent(parent => b.parent, new_child => b, old_child => a);   set_balance(a); set_balance(b); return b; end rotate_left;   function rotate_right(a : not null Node_Ptr) return Node_Ptr is b : Node_Ptr := a.left; begin b.parent := a.parent; a.left := b.right; if a.left /= null then a.left.parent := a; end if; b.right := a; a.parent := b; update_parent(parent => b.parent, new_child => b, old_child => a);   set_balance(a); set_balance(b); return b; end rotate_right;   function rotate_left_right(n : not null Node_Ptr) return Node_Ptr is begin n.left := rotate_left(n.left); return rotate_right(n); end rotate_left_right;   function rotate_right_left(n : not null Node_Ptr) return Node_Ptr is begin n.right := rotate_right(n.right); return rotate_left(n); end rotate_right_left;   procedure rebalance(self : in out Tree; n : not null Node_Ptr) is new_n : Node_Ptr := n; begin set_balance(new_n); if new_n.balance = -2 then if height(new_n.left.left) >= height(new_n.left.right) then new_n := rotate_right(new_n); else new_n := rotate_left_right(new_n); end if; elsif new_n.balance = 2 then if height(new_n.right.right) >= height(new_n.right.left) then new_n := rotate_left(new_n); else new_n := rotate_right_left(new_n); end if; end if;   if new_n.parent /= null then rebalance(self, new_n.parent); else self.root := new_n; end if; end rebalance;   function new_node(key : Key_Type) return Node_Ptr is (new Node'(Node_Parent with key => key, others => <>));   function insert(self : in out Tree; key : Key_Type) return Boolean is curr, parent : Node_Ptr; go_left : Boolean; begin if self.root = null then self.root := new_node(key); return True; end if;   curr := self.root; while curr.key /= key loop parent := curr; go_left := key < curr.key; curr := (if go_left then curr.left else curr.right); if curr = null then if go_left then parent.left := new_node(key); parent.left.parent := parent; else parent.right := new_node(key); parent.right.parent := parent; end if; rebalance(self, parent); return True; end if; end loop; return False; end insert;   procedure delete(self : in out Tree; key : Key_Type) is successor, parent, child : Node_Ptr := self.root; to_delete : Node_Ptr := null; begin if self.root = null then return; end if;   while child /= null loop parent := successor; successor := child; child := (if successor.key <= key then successor.right else successor.left); if successor.key = key then to_delete := successor; end if; end loop;   if to_delete = null then return; end if; to_delete.key := successor.key; child := (if successor.left = null then successor.right else successor.left); if self.root.key = key then self.root := child; else update_parent(parent => parent, new_child => child, old_child => successor); rebalance(self, parent); end if; Free_Node(successor); end delete;   procedure print_balance(n : Node_Ptr) is begin if n /= null then print_balance(n.left); Ada.Text_IO.Put(n.balance'Image); print_balance(n.right); end if; end print_balance;   procedure print_balance(self : in out Tree) is begin print_balance(self.root); end print_balance; end AVL_Tree;   package Int_AVL_Tree is new AVL_Tree(Integer);   tree : Int_AVL_Tree.Tree; success : Boolean; begin for i in 1 .. 10 loop success := tree.insert(i); end loop; Ada.Text_IO.Put("Printing balance: "); tree.print_balance; Ada.Text_IO.New_Line; end Main;  
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
#Ada
Ada
with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions;   procedure Mean_Angles is   type X_Real is digits 4; -- or more digits for improved precision subtype Real is X_Real range 0.0 .. 360.0; -- the range of interest type Angles is array(Positive range <>) of Real;   procedure Put(R: Real) is package IO is new Ada.Text_IO.Float_IO(Real); begin IO.Put(R, Fore => 3, Aft => 2, Exp => 0); end Put;   function Mean_Angle(A: Angles) return Real is Sin_Sum, Cos_Sum: X_Real := 0.0; -- X_Real since sums might exceed 360.0 package Math is new Ada.Numerics.Generic_Elementary_Functions(Real); use Math; begin for I in A'Range loop Sin_Sum := Sin_Sum + Sin(A(I), Cycle => 360.0); Cos_Sum := Cos_Sum + Cos(A(I), Cycle => 360.0); end loop; return Arctan(Sin_Sum / X_Real(A'Length), Cos_Sum / X_Real(A'Length), Cycle => 360.0); -- may raise Ada.Numerics.Argument_Error if inputs are -- numerically instable, e.g., when Cos_Sum is 0.0 end Mean_Angle;   begin Put(Mean_Angle((10.0, 20.0, 30.0))); Ada.Text_IO.New_Line; -- 20.00 Put(Mean_Angle((10.0, 350.0))); Ada.Text_IO.New_Line; -- 0.00 Put(Mean_Angle((90.0, 180.0, 270.0, 360.0))); -- Ada.Numerics.Argument_Error! end Mean_Angles;
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches to this.   One is to sort the elements, and then pick the element(s) in the middle. Sorting would take at least   O(n logn).   Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s).   This would also take   O(n logn).   The best solution is to use the   selection algorithm   to find the median in   O(n)   time. See also Quickselect_algorithm Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#Action.21
Action!
INCLUDE "H6:REALMATH.ACT"   DEFINE PTR="CARD"   PROC Sort(PTR ARRAY a INT count) INT i,j,minpos REAL POINTER tmp   FOR i=0 TO count-2 DO minpos=i FOR j=i+1 TO count-1 DO IF RealGreaterOrEqual(a(minpos),a(j)) THEN minpos=j FI OD   IF minpos#i THEN tmp=a(i) a(i)=a(minpos) a(minpos)=tmp FI OD RETURN   PROC Median(PTR ARRAY a INT count REAL POINTER res) IF count=0 THEN Break() FI Sort(a,count) IF (count&1)=0 THEN RealAdd(a(count RSH 1-1),a(count RSH 1),res) RealMult(res,half,res) ELSE RealAssign(a(count RSH 1),res) FI RETURN   PROC Test(PTR ARRAY a INT count) INT i REAL res   FOR i=0 TO count-1 DO PrintR(a(i)) Put(32) OD Median(a,count,res) Print("-> ") PrintRE(res) RETURN   PROC Main() PTR ARRAY a(8) REAL r1,r2,r3,r4,r5,r6,r7,r8 BYTE i   Put(125) PutE() ;clear the screen MathInit() ValR("3.2",r1) ValR("-4.1",r2) ValR("0.6",r3) ValR("9.8",r4) ValR("5.1",r5) ValR("-1.4",r6) ValR("0.3",r7) ValR("2.2",r8) FOR i=1 TO 8 DO a(0)=r1 a(1)=r2 a(2)=r3 a(3)=r4 a(4)=r5 a(5)=r6 a(6)=r7 a(7)=r8 Test(a,i) OD RETURN
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
#E
E
def makeMean(base, include, finish) { return def mean(numbers) { var count := 0 var acc := base for x in numbers { acc := include(acc, x) count += 1 } return finish(acc, count) } }   def A := makeMean(0, fn b,x { b+x }, fn acc,n { acc / n }) def G := makeMean(1, fn b,x { b*x }, fn acc,n { acc ** (1/n) }) def H := makeMean(0, fn b,x { b+1/x }, fn acc,n { n / acc })
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.
#C.2B.2B
C++
#include <iostream> #include <string> #include <climits> using namespace std;   class BalancedTernary { protected: // Store the value as a reversed string of +, 0 and - characters string value;   // Helper function to change a balanced ternary character to an integer int charToInt(char c) const { if (c == '0') return 0; return 44 - c; }   // Helper function to negate a string of ternary characters string negate(string s) const { for (int i = 0; i < s.length(); ++i) { if (s[i] == '+') s[i] = '-'; else if (s[i] == '-') s[i] = '+'; } return s; }   public: // Default constructor BalancedTernary() { value = "0"; }   // Construct from a string BalancedTernary(string s) { value = string(s.rbegin(), s.rend()); }   // Construct from an integer BalancedTernary(long long n) { if (n == 0) { value = "0"; return; }   bool neg = n < 0; if (neg) n = -n;   value = ""; while (n != 0) { int r = n % 3; if (r == 0) value += "0"; else if (r == 1) value += "+"; else { value += "-"; ++n; }   n /= 3; }   if (neg) value = negate(value); }   // Copy constructor BalancedTernary(const BalancedTernary &n) { value = n.value; }   // Addition operators BalancedTernary operator+(BalancedTernary n) const { n += *this; return n; }   BalancedTernary& operator+=(const BalancedTernary &n) { static char *add = "0+-0+-0"; static char *carry = "--000++";   int lastNonZero = 0; char c = '0'; for (int i = 0; i < value.length() || i < n.value.length(); ++i) { char a = i < value.length() ? value[i] : '0'; char b = i < n.value.length() ? n.value[i] : '0';   int sum = charToInt(a) + charToInt(b) + charToInt(c) + 3; c = carry[sum];   if (i < value.length()) value[i] = add[sum]; else value += add[sum];   if (add[sum] != '0') lastNonZero = i; }   if (c != '0') value += c; else value = value.substr(0, lastNonZero + 1); // Chop off leading zeroes   return *this; }   // Negation operator BalancedTernary operator-() const { BalancedTernary result; result.value = negate(value); return result; }   // Subtraction operators BalancedTernary operator-(const BalancedTernary &n) const { return operator+(-n); }   BalancedTernary& operator-=(const BalancedTernary &n) { return operator+=(-n); }   // Multiplication operators BalancedTernary operator*(BalancedTernary n) const { n *= *this; return n; }   BalancedTernary& operator*=(const BalancedTernary &n) { BalancedTernary pos = *this; BalancedTernary neg = -pos; // Storing an extra copy to avoid negating repeatedly value = "0";   for (int i = 0; i < n.value.length(); ++i) { if (n.value[i] == '+') operator+=(pos); else if (n.value[i] == '-') operator+=(neg); pos.value = '0' + pos.value; neg.value = '0' + neg.value; }   return *this; }   // Stream output operator friend ostream& operator<<(ostream &out, const BalancedTernary &n) { out << n.toString(); return out; }   // Convert to string string toString() const { return string(value.rbegin(), value.rend()); }   // Convert to integer long long toInt() const { long long result = 0; for (long long i = 0, pow = 1; i < value.length(); ++i, pow *= 3) result += pow * charToInt(value[i]); return result; }   // Convert to integer if possible bool tryInt(long long &out) const { long long result = 0; bool ok = true;   for (long long i = 0, pow = 1; i < value.length() && ok; ++i, pow *= 3) { if (value[i] == '+') { ok &= LLONG_MAX - pow >= result; // Clear ok if the result overflows result += pow; } else if (value[i] == '-') { ok &= LLONG_MIN + pow <= result; // Clear ok if the result overflows result -= pow; } }   if (ok) out = result; return ok; } };   int main() { BalancedTernary a("+-0++0+"); BalancedTernary b(-436); BalancedTernary c("+-++-");   cout << "a = " << a << " = " << a.toInt() << endl; cout << "b = " << b << " = " << b.toInt() << endl; cout << "c = " << c << " = " << c.toInt() << endl;   BalancedTernary d = a * (b - c);   cout << "a * (b - c) = " << d << " = " << d.toInt() << endl;   BalancedTernary e("+++++++++++++++++++++++++++++++++++++++++");   long long n; if (e.tryInt(n)) cout << "e = " << e << " = " << n << endl; else cout << "e = " << e << " is too big to fit in a long long" << endl;   return 0; }  
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.
#Liberty_BASIC
Liberty BASIC
  [start] if right$(str$(n*n),6)="269696" then print "n = "; using("###,###", n); print " n*n = "; using("###,###,###,###", n*n) end if if n<100000 then n=n+1: goto [start] print "Program complete."  
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
#AppleScript
AppleScript
-- CHECK NESTING OF SQUARE BRACKET SEQUENCES ---------------------------------   -- Zero-based index of the first problem (-1 if none found):   -- imbalance :: String -> Integer on imbalance(strBrackets) script on errorIndex(xs, iDepth, iIndex) set lngChars to length of xs if lngChars > 0 then set iNext to iDepth + cond(item 1 of xs = "[", 1, -1)   if iNext < 0 then -- closing bracket unmatched iIndex else if lngChars > 1 then -- continue recursively errorIndex(items 2 thru -1 of xs, iNext, iIndex + 1) else -- end of string cond(iNext = 0, -1, iIndex) end if end if else cond(iDepth = 0, -1, iIndex) end if end errorIndex end script   result's errorIndex(characters of strBrackets, 0, 0) end imbalance   -- TEST ----------------------------------------------------------------------   -- Random bracket sequences for testing -- brackets :: Int -> String on randomBrackets(n) -- bracket :: () -> String script bracket on |λ|(_) cond((random number) < 0.5, "[", "]") end |λ| end script intercalate("", map(bracket, enumFromTo(1, n))) end randomBrackets   on run set nPairs to 6   -- report :: Int -> String script report property strPad : concat(replicate(nPairs * 2 + 4, space))   on |λ|(n) set w to n * 2 set s to randomBrackets(w) set i to imbalance(s) set blnOK to (i = -1)   set strStatus to cond(blnOK, "OK", "problem")   set strLine to "'" & s & "'" & ¬ (items (w + 2) thru -1 of strPad) & strStatus   set strPointer to cond(blnOK, ¬ "", linefeed & concat(replicate(i + 1, space)) & "^")   intercalate("", {strLine, strPointer}) end |λ| end script   linefeed & ¬ intercalate(linefeed, ¬ map(report, enumFromTo(1, nPairs))) & linefeed end run     -- GENERIC FUNCTIONS ---------------------------------------------------------   -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map   -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl   -- Text -> [Text] -> Text on intercalate(strText, lstText) set {dlm, my text item delimiters} to {my text item delimiters, strText} set strJoined to lstText as text set my text item delimiters to dlm return strJoined end intercalate   -- concat :: [[a]] -> [a] | [String] -> String on concat(xs) script append on |λ|(a, b) a & b end |λ| end script   if length of xs > 0 and class of (item 1 of xs) is string then set empty to "" else set empty to {} end if foldl(append, empty, xs) end concat   -- Egyptian multiplication - progressively doubling a list, appending -- stages of doubling to an accumulator where needed for binary -- assembly of a target length   -- replicate :: Int -> a -> [a] on replicate(n, a) set out to {} if n < 1 then return out set dbl to {a}   repeat while (n > 1) if (n mod 2) > 0 then set out to out & dbl set n to (n div 2) set dbl to (dbl & dbl) end repeat return out & dbl end replicate   -- Value of one of two expressions -- cond :: Bool -> a -> b -> c on cond(bln, f, g) if bln then set e to f else set e to g end if if class of e is handler then mReturn(e)'s |λ|() else e end if end cond   -- enumFromTo :: Int -> Int -> [Int] on enumFromTo(m, n) if m > n then set d to -1 else set d to 1 end if set lst to {} repeat with i from m to n by d set end of lst to i end repeat return lst end enumFromTo   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn
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
#Delphi
Delphi
  program AveragesMode;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Generics.Collections, System.Generics.Defaults;   type TCounts = TDictionary<Integer, Integer>;   TPair = record value, count: Integer; constructor Create(value, count: Integer); end;   TPairs = TArray<TPair>;   var dict: TCounts; Pairs: TPairs; list: TArray<Integer>; i, key, max: Integer; p: TPair;   { TPair }   constructor TPair.Create(value, count: Integer); begin self.value := value; self.count := count; end;   function SortByCount(const left, right: TPair): Integer; begin Result := right.count - left.count; end;   begin list := [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 12, 12, 17]; dict := TCounts.Create;   for i in list do begin if dict.ContainsKey(i) then dict[i] := dict[i] + 1 else begin dict.Add(i, 1); end; end;   SetLength(Pairs, dict.Count); i := 0; for key in dict.Keys do begin Pairs[i] := TPair.Create(key, dict[key]); inc(i); end;   TArray.Sort<TPair>(Pairs, TComparer<TPair>.Construct(SortByCount));   Writeln('Modes:'); max := Pairs[0].count; for p in Pairs do if p.count = max then Writeln(' Value: ', p.value, ', Count: ', p.count);   dict.Free; Readln; end.
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
#OCaml
OCaml
let sma (n, s, q) x = let l = Queue.length q and s = s +. x in Queue.push x q; if l < n then (n, s, q), s /. float (l + 1) else ( let s = s -. Queue.pop q in (n, s, q), s /. float l )   let _ = let periodLst = [ 3; 5 ] in let series = [ 1.; 2.; 3.; 4.; 5.; 5.; 4.; 3.; 2.; 1. ] in   List.iter (fun d -> Printf.printf "SIMPLE MOVING AVERAGE: PERIOD = %d\n" d; ignore ( List.fold_left (fun o x -> let o, m = sma o x in Printf.printf "Next number = %-2g, SMA = %g\n" x m; o ) (d, 0., Queue.create ()) series; ); print_newline (); ) periodLst
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
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace RosettaCode { class Program { static void Main(string[] args) { Func<TimeSpan, double> TimeToDegrees = (time) => 360 * time.Hours / 24.0 + 360 * time.Minutes / (24 * 60.0) + 360 * time.Seconds / (24 * 3600.0); Func<List<double>, double> MeanAngle = (angles) => { double y_part = 0.0d, x_part = 0.0d; int numItems = angles.Count;   for (int i = 0; i < numItems; i++) { x_part += Math.Cos(angles[i] * Math.PI / 180); y_part += Math.Sin(angles[i] * Math.PI / 180); }   return Math.Atan2(y_part / numItems, x_part / numItems) * 180 / Math.PI; }; Func<double, TimeSpan> TimeFromDegrees = (angle) => new TimeSpan( (int)(24 * 60 * 60 * angle / 360) / 3600, ((int)(24 * 60 * 60 * angle / 360) % 3600 - (int)(24 * 60 * 60 * angle / 360) % 60) / 60, (int)(24 * 60 * 60 * angle / 360) % 60); List<double> digitimes = new List<double>(); TimeSpan digitime; string input;   Console.WriteLine("Enter times, end with no input: "); do { input = Console.ReadLine(); if (!(string.IsNullOrWhiteSpace(input))) { if (TimeSpan.TryParse(input, out digitime)) digitimes.Add(TimeToDegrees(digitime)); else Console.WriteLine("Seems this is wrong input: ignoring time"); } } while (!string.IsNullOrWhiteSpace(input));   if(digitimes.Count() > 0) Console.WriteLine("The mean time is : {0}", TimeFromDegrees(360 + MeanAngle(digitimes))); } } }  
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.
#Agda
Agda
  module Avl where   -- The Peano naturals data Nat : Set where z : Nat s : Nat -> Nat   -- An AVL tree's type is indexed by a natural. -- Avl N is the type of AVL trees of depth N. There arj 3 different -- node constructors: -- Left: The left subtree is one level deeper than the right -- Balanced: The subtrees have the same depth -- Right: The right Subtree is one level deeper than the left -- Since the AVL invariant is that the depths of a node's subtrees -- always differ by at most 1, this perfectly encodes the AVL depth invariant. data Avl : Nat -> Set where Empty : Avl z Left : {X : Nat} -> Nat -> Avl (s X) -> Avl X -> Avl (s (s X)) Balanced : {X : Nat} -> Nat -> Avl X -> Avl X -> Avl (s X) Right : {X : Nat} -> Nat -> Avl X -> Avl (s X) -> Avl (s (s X))   -- A wrapper type that hides the AVL tree invariant. This is the interface -- exposed to the user. data Tree : Set where avl : {N : Nat} -> Avl N -> Tree   -- Comparison result data Ord : Set where Less : Ord Equal : Ord Greater : Ord   -- Comparison function cmp : Nat -> Nat -> Ord cmp z (s X) = Less cmp z z = Equal cmp (s X) z = Greater cmp (s X) (s Y) = cmp X Y   -- Insertions can either leave the depth the same or -- increase it by one. Encode this in the type. data InsertResult : Nat -> Set where Same : {X : Nat} -> Avl X -> InsertResult X Bigger : {X : Nat} -> Avl (s X) -> InsertResult X   -- If the left subtree is 2 levels deeper than the right, rotate to the right. -- balance-left X L R means X is the root, L is the left subtree and R is the right. balance-left : {N : Nat} -> Nat -> Avl (s (s N)) -> Avl N -> InsertResult (s (s N)) balance-left X (Right Y A (Balanced Z B C)) D = Same (Balanced Z (Balanced X A B) (Balanced Y C D)) balance-left X (Right Y A (Left Z B C)) D = Same (Balanced Z (Balanced X A B) (Right Y C D)) balance-left X (Right Y A (Right Z B C)) D = Same (Balanced Z (Left X A B) (Balanced Y C D)) balance-left X (Left Y (Balanced Z A B) C) D = Same (Balanced Z (Balanced X A B) (Balanced Y C D)) balance-left X (Left Y (Left Z A B) C) D = Same (Balanced Z (Left X A B) (Balanced Y C D)) balance-left X (Left Y (Right Z A B) C) D = Same (Balanced Z (Right X A B) (Balanced Y C D)) balance-left X (Balanced Y (Balanced Z A B) C) D = Bigger (Right Z (Balanced X A B) (Left Y C D)) balance-left X (Balanced Y (Left Z A B) C) D = Bigger (Right Z (Left X A B) (Left Y C D)) balance-left X (Balanced Y (Right Z A B) C) D = Bigger (Right Z (Right X A B) (Left Y C D))   -- Symmetric with balance-left balance-right : {N : Nat} -> Nat -> Avl N -> Avl (s (s N)) -> InsertResult (s (s N)) balance-right X A (Left Y (Left Z B C) D) = Same (Balanced Z (Balanced X A B) (Right Y C D)) balance-right X A (Left Y (Balanced Z B C) D) = Same(Balanced Z (Balanced X A B) (Balanced Y C D)) balance-right X A (Left Y (Right Z B C) D) = Same(Balanced Z (Left X A B) (Balanced Y C D)) balance-right X A (Balanced Z B (Left Y C D)) = Bigger(Left Z (Right X A B) (Left Y C D)) balance-right X A (Balanced Z B (Balanced Y C D)) = Bigger (Left Z (Right X A B) (Balanced Y C D)) balance-right X A (Balanced Z B (Right Y C D)) = Bigger (Left Z (Right X A B) (Right Y C D)) balance-right X A (Right Z B (Left Y C D)) = Same (Balanced Z (Balanced X A B) (Left Y C D)) balance-right X A (Right Z B (Balanced Y C D)) = Same (Balanced Z (Balanced X A B) (Balanced Y C D)) balance-right X A (Right Z B (Right Y C D)) = Same (Balanced Z (Balanced X A B) (Right Y C D))   -- insert' T N does all the work of inserting the element N into the tree T. insert' : {N : Nat} -> Avl N -> Nat -> InsertResult N insert' Empty N = Bigger (Balanced N Empty Empty) insert' (Left Y L R) X with cmp X Y insert' (Left Y L R) X | Less with insert' L X insert' (Left Y L R) X | Less | Same L' = Same (Left Y L' R) insert' (Left Y L R) X | Less | Bigger L' = balance-left Y L' R insert' (Left Y L R) X | Equal = Same (Left Y L R) insert' (Left Y L R) X | Greater with insert' R X insert' (Left Y L R) X | Greater | Same R' = Same (Left Y L R') insert' (Left Y L R) X | Greater | Bigger R' = Same (Balanced Y L R') insert' (Balanced Y L R) X with cmp X Y insert' (Balanced Y L R) X | Less with insert' L X insert' (Balanced Y L R) X | Less | Same L' = Same (Balanced Y L' R) insert' (Balanced Y L R) X | Less | Bigger L' = Bigger (Left Y L' R) insert' (Balanced Y L R) X | Equal = Same (Balanced Y L R) insert' (Balanced Y L R) X | Greater with insert' R X insert' (Balanced Y L R) X | Greater | Same R' = Same (Balanced Y L R') insert' (Balanced Y L R) X | Greater | Bigger R' = Bigger (Right Y L R') insert' (Right Y L R) X with cmp X Y insert' (Right Y L R) X | Less with insert' L X insert' (Right Y L R) X | Less | Same L' = Same (Right Y L' R) insert' (Right Y L R) X | Less | Bigger L' = Same (Balanced Y L' R) insert' (Right Y L R) X | Equal = Same (Right Y L R) insert' (Right Y L R) X | Greater with insert' R X insert' (Right Y L R) X | Greater | Same R' = Same (Right Y L R') insert' (Right Y L R) X | Greater | Bigger R' = balance-right Y L R'   -- Wrapper around insert' to use the depth-agnostic type Tree. insert : Tree -> Nat -> Tree insert (avl T) X with insert' T X ... | Same T' = avl T' ... | Bigger T' = avl T'  
http://rosettacode.org/wiki/Averages/Mean_angle
Averages/Mean angle
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the 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
#Aime
Aime
real mean(list l) { integer i; real x, y;   x = y = 0;   i = 0; while (i < l_length(l)) { x += Gcos(l[i]); y += Gsin(l[i]); i += 1; }   return Gatan2(y / l_length(l), x / l_length(l)); }   integer main(void) { o_form("mean of 1st set: /d6/\n", mean(l_effect(350, 10))); o_form("mean of 2nd set: /d6/\n", mean(l_effect(90, 180, 270, 360))); o_form("mean of 3rd set: /d6/\n", mean(l_effect(10, 20, 30)));   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
#ALGOL_68
ALGOL 68
#!/usr/bin/a68g --script # # -*- coding: utf-8 -*- #   PROC mean angle = ([]#LONG# REAL angles)#LONG# REAL: ( INT size = UPB angles - LWB angles + 1; #LONG# REAL y part := 0, x part := 0; FOR i FROM LWB angles TO UPB angles DO x part +:= #long# cos (angles[i] * #long# pi / 180); y part +:= #long# sin (angles[i] * #long# pi / 180) OD;   #long# arc tan2 (y part / size, x part / size) * 180 / #long# pi );   main: ( []#LONG# REAL angle set 1 = ( 350, 10 ); []#LONG# REAL angle set 2 = ( 90, 180, 270, 360); []#LONG# REAL angle set 3 = ( 10, 20, 30);   FORMAT summary fmt=$"Mean angle for "g" set :"-zd.ddddd" degrees"l$; printf ((summary fmt,"1st", mean angle (angle set 1))); printf ((summary fmt,"2nd", mean angle (angle set 2))); printf ((summary fmt,"3rd", mean angle (angle set 3))) )
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
#Ada
Ada
with Ada.Text_IO, Ada.Float_Text_IO;   procedure FindMedian is   f: array(1..10) of float := ( 4.4, 2.3, -1.7, 7.5, 6.6, 0.0, 1.9, 8.2, 9.3, 4.5 ); min_idx: integer; min_val, median_val, swap: float;   begin for i in f'range loop min_idx := i; min_val := f(i); for j in i+1 .. f'last loop if f(j) < min_val then min_idx := j; min_val := f(j); end if; end loop; swap := f(i); f(i) := f(min_idx); f(min_idx) := swap; end loop;   if f'length mod 2 /= 0 then median_val := f( f'length/2+1 ); else median_val := ( f(f'length/2) + f(f'length/2+1) ) / 2.0; end if;   Ada.Text_IO.Put( "Median value: " ); Ada.Float_Text_IO.Put( median_val ); Ada.Text_IO.New_line; end FindMedian;
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
#EchoLisp
EchoLisp
  (define (A xs) (// (for/sum ((x xs)) x) (length xs)))   (define (G xs) (expt (for/product ((x xs)) x) (// (length xs))))   (define (H xs) (// (length xs) (for/sum ((x xs)) (// x))))   (define xs (range 1 11)) (and (>= (A xs) (G xs)) (>= (G xs) (H xs))) → #t  
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.
#Common_Lisp
Common Lisp
;;; balanced ternary ;;; represented as a list of 0, 1 or -1s, with least significant digit first   ;;; convert ternary to integer (defun bt-integer (b) (reduce (lambda (x y) (+ x (* 3 y))) b :from-end t :initial-value 0))   ;;; convert integer to ternary (defun integer-bt (n) (if (zerop n) nil (case (mod n 3) (0 (cons 0 (integer-bt (/ n 3)))) (1 (cons 1 (integer-bt (floor n 3)))) (2 (cons -1 (integer-bt (floor (1+ n) 3)))))))   ;;; convert string to ternary (defun string-bt (s) (loop with o = nil for c across s do (setf o (cons (case c (#\+ 1) (#\- -1) (#\0 0)) o)) finally (return o)))   ;;; convert ternary to string (defun bt-string (bt) (if (not bt) "0" (let* ((l (length bt)) (s (make-array l :element-type 'character))) (mapc (lambda (b) (setf (aref s (decf l)) (case b (-1 #\-) (0 #\0) (1 #\+)))) bt) s)))   ;;; arithmetics (defun bt-neg (a) (map 'list #'- a)) (defun bt-sub (a b) (bt-add a (bt-neg b)))   (let ((tbl #((0 -1) (1 -1) (-1 0) (0 0) (1 0) (-1 1) (0 1)))) (defun bt-add-digits (a b c) (values-list (aref tbl (+ 3 a b c)))))   (defun bt-add (a b &optional (c 0)) (if (not (and a b)) (if (zerop c) (or a b) (bt-add (list c) (or a b))) (multiple-value-bind (d c) (bt-add-digits (if a (car a) 0) (if b (car b) 0) c) (let ((res (bt-add (cdr a) (cdr b) c))) ;; trim leading zeros (if (or res (not (zerop d))) (cons d res))))))   (defun bt-mul (a b) (if (not (and a b)) nil (bt-add (case (car a) (-1 (bt-neg b)) ( 0 nil) ( 1 b)) (cons 0 (bt-mul (cdr a) b)))))   ;;; division with quotient/remainder, for completeness (defun bt-truncate (a b) (let ((n (- (length a) (length b))) (d (car (last b)))) (if (minusp n) (values nil a) (labels ((recur (a b x) (multiple-value-bind (quo rem) (if (plusp x) (recur a (cons 0 b) (1- x)) (values nil a))   (loop with g = (car (last rem)) with quo = (cons 0 quo) while (= (length rem) (length b)) do (cond ((= g d) (setf rem (bt-sub rem b) quo (bt-add '(1) quo))) ((= g (- d)) (setf rem (bt-add rem b) quo (bt-add '(-1) quo)))) (setf x (car (last rem))) finally (return (values quo rem))))))   (recur a b n)))))   ;;; test case (let* ((a (string-bt "+-0++0+")) (b (integer-bt -436)) (c (string-bt "+-++-")) (d (bt-mul a (bt-sub b c)))) (format t "a~5d~8t~a~%b~5d~8t~a~%c~5d~8t~a~%a × (b − c) = ~d ~a~%" (bt-integer a) (bt-string a) (bt-integer b) (bt-string b) (bt-integer c) (bt-string c) (bt-integer d) (bt-string 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.
#Limbo
Limbo
implement Babbage;   include "sys.m"; sys: Sys; print: import sys; include "draw.m"; draw: Draw;   Babbage : module { init : fn(ctxt : ref Draw->Context, args : list of string); };   init (ctxt: ref Draw->Context, args: list of string) { sys = load Sys Sys->PATH; current := 0; while ((current * current) % 1000000 != 269696) current++; print("%d", current); }  
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.
#Lua
Lua
-- get smallest number <= sqrt(269696) k = math.floor(math.sqrt(269696))   -- if root is odd -> make it even if k % 2 == 1 then k = k - 1 end   -- cycle through numbers while not ((k * k) % 1000000 == 269696) do k = k + 2 end   io.write(string.format("%d * %d = %d\n", k, k, k * k))
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
#ARM_Assembly
ARM Assembly
  .data   balanced_message: .ascii "OK\n"   unbalanced_message: .ascii "NOT OK\n"     .text   .equ balanced_msg_len, 3 .equ unbalanced_msg_len, 7     BalancedBrackets:   mov r1, #0 mov r2, #0 mov r3, #0   process_bracket: ldrb r2, [r0, r1]   cmp r2, #0 beq evaluate_balance   cmp r2, #'[' addeq r3, r3, #1   cmp r2, #']' subeq r3, r3, #1   cmp r3, #0 blt unbalanced   add r1, r1, #1 b process_bracket   evaluate_balance: cmp r3, #0 beq balanced   unbalanced: ldr r1, =unbalanced_message mov r2, #unbalanced_msg_len b display_result   balanced: ldr r1, =balanced_message mov r2, #balanced_msg_len   display_result: mov r7, #4 mov r0, #1 svc #0   mov pc, lr    
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
#E
E
pragma.enable("accumulator") def mode(values) { def counts := [].asMap().diverge() var maxCount := 0 for v in values { maxCount max= (counts[v] := counts.fetch(v, fn{0}) + 1) } return accum [].asSet() for v => ==maxCount in counts { _.with(v) } }
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
#Oforth
Oforth
import: parallel   : createSMA(period) | ch | Channel new [ ] over send drop ->ch #[ ch receive + left(period) dup avg swap ch send drop ] ;
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
#C.2B.2B
C++
#include <iomanip> #include <iostream> #include <vector>   #define _USE_MATH_DEFINES #include <math.h>   struct Time { int hour, minute, second;   friend std::ostream &operator<<(std::ostream &, const Time &); };   std::ostream &operator<<(std::ostream &os, const Time &t) { return os << std::setfill('0') << std::setw(2) << t.hour << ':' << std::setw(2) << t.minute << ':' << std::setw(2) << t.second; }   double timeToDegrees(Time &&t) { return 360.0 * t.hour / 24.0 + 360.0 * t.minute / (24 * 60.0) + 360.0 * t.second / (24 * 3600.0); }   Time degreesToTime(double angle) { while (angle < 0.0) { angle += 360.0; } while (angle > 360.0) { angle -= 360.0; }   double totalSeconds = 24.0 * 60 * 60 * angle / 360; Time t;   t.second = (int)totalSeconds % 60; t.minute = ((int)totalSeconds % 3600 - t.second) / 60; t.hour = (int)totalSeconds / 3600;   return t; }   double meanAngle(const std::vector<double> &angles) { double yPart = 0.0, xPart = 0.0; for (auto a : angles) { xPart += cos(a * M_PI / 180); yPart += sin(a * M_PI / 180); } return atan2(yPart / angles.size(), xPart / angles.size()) * 180 / M_PI; }   int main() { std::vector<double> tv; tv.push_back(timeToDegrees({ 23, 0, 17 })); tv.push_back(timeToDegrees({ 23, 40, 20 })); tv.push_back(timeToDegrees({ 0, 12, 45 })); tv.push_back(timeToDegrees({ 0, 17, 19 }));   double ma = meanAngle(tv); auto mt = degreesToTime(ma); std::cout << mt << '\n';   return 0; }
http://rosettacode.org/wiki/AVL_tree
AVL tree
This page uses content from Wikipedia. The original article was at AVL tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In computer science, an AVL tree is a self-balancing binary search tree. 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.
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program avltree2.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */   /*******************************************/ /* Constantes */ /*******************************************/ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall .equ BRK, 0x2d @ Linux syscall .equ CHARPOS, '@'   .equ NBVAL, 12   /*******************************************/ /* Structures */ /********************************************/ /* structure tree */ .struct 0 tree_root: @ root pointer (or node right) .struct tree_root + 4 tree_size: @ number of element of tree .struct tree_size + 4 tree_suite: .struct tree_suite + 12 @ for alignement to node tree_fin: /* structure node tree */ .struct 0 node_right: @ right pointer .struct node_right + 4 node_left: @ left pointer .struct node_left + 4 node_value: @ element value .struct node_value + 4 node_height: @ element value .struct node_height + 4 node_parent: @ element value .struct node_parent + 4 node_fin: /* structure queue*/ .struct 0 queue_begin: @ next pointer .struct queue_begin + 4 queue_end: @ element value .struct queue_end + 4 queue_fin: /* structure node queue */ .struct 0 queue_node_next: @ next pointer .struct queue_node_next + 4 queue_node_value: @ element value .struct queue_node_value + 4 queue_node_fin: /*******************************************/ /* Initialized data */ /*******************************************/ .data szMessPreOrder: .asciz "PreOrder :\n" szCarriageReturn: .asciz "\n" /* datas error display */ szMessErreur: .asciz "Error detected.\n" szMessKeyDbl: .asciz "Key exists in tree.\n" szMessInsInv: .asciz "Insertion in inverse order.\n" /* datas message display */ szMessResult: .asciz "Ele: @ G: @ D: @ val @ h @ pere @\n" sValue: .space 12,' ' .asciz "\n" /*******************************************/ /* UnInitialized data */ /*******************************************/ .bss sZoneConv: .skip 24 stTree: .skip tree_fin @ place to structure tree stTree1: .skip tree_fin @ place to structure tree stQueue: .skip queue_fin @ place to structure queue /*******************************************/ /* code section */ /*******************************************/ .text .global main main: mov r8,#1 @ node tree value 1: @ loop insertion in order ldr r0,iAdrstTree @ structure tree address mov r1,r8 bl insertElement @ add element value r1 cmp r0,#-1 beq 99f //ldr r3,iAdrstTree @ tree root address (begin structure) //ldr r0,[r3,#tree_root] //ldr r1,iAdrdisplayElement @ function to execute //bl preOrder add r8,#1 @ increment value cmp r8,#NBVAL @ end ? ble 1b @ no -> loop   ldr r0,iAdrstTree @ structure tree address mov r1,#11 @ verif key dobble bl insertElement @ add element value r1 cmp r0,#-1 bne 2f ldr r0,iAdrszMessErreur bl affichageMess 2: ldr r0,iAdrszMessPreOrder @ load verification bl affichageMess ldr r3,iAdrstTree @ tree root address (begin structure) ldr r0,[r3,#tree_root] ldr r1,iAdrdisplayElement @ function to execute bl preOrder     ldr r0,iAdrszMessInsInv bl affichageMess mov r8,#NBVAL @ node tree value 3: @ loop insertion inverse order ldr r0,iAdrstTree1 @ structure tree address mov r1,r8 bl insertElement @ add element value r1 cmp r0,#-1 beq 99f sub r8,#1 @ increment value cmp r8,#0 @ end ? bgt 3b @ no -> loop   ldr r0,iAdrszMessPreOrder @ load verification bl affichageMess ldr r3,iAdrstTree1 @ tree root address (begin structure) ldr r0,[r3,#tree_root] ldr r1,iAdrdisplayElement @ function to execute bl preOrder   @ search value ldr r0,iAdrstTree1 @ tree root address (begin structure) mov r1,#11 @ value to search bl searchTree cmp r0,#-1 beq 100f mov r2,r0 ldr r0,iAdrszMessKeyDbl @ key exists bl affichageMess @ suppresssion previous value mov r0,r2 ldr r1,iAdrstTree1 bl supprimer   ldr r0,iAdrszMessPreOrder @ verification bl affichageMess ldr r3,iAdrstTree1 @ tree root address (begin structure) ldr r0,[r3,#tree_root] ldr r1,iAdrdisplayElement @ function to execute bl preOrder   b 100f 99: @ display error ldr r0,iAdrszMessErreur bl affichageMess 100: @ standard end of the program mov r7, #EXIT @ request to exit program svc 0 @ perform system call iAdrszMessPreOrder: .int szMessPreOrder iAdrszMessErreur: .int szMessErreur iAdrszCarriageReturn: .int szCarriageReturn iAdrstTree: .int stTree iAdrstTree1: .int stTree1 iAdrstQueue: .int stQueue iAdrdisplayElement: .int displayElement iAdrszMessInsInv: .int szMessInsInv /******************************************************************/ /* insert element in the tree */ /******************************************************************/ /* r0 contains the address of the tree structure */ /* r1 contains the value of element */ /* r0 returns address of element or - 1 if error */ insertElement: @ INFO: insertElement push {r1-r8,lr} @ save registers mov r7,r0 @ save head mov r0,#node_fin @ reservation place one element bl allocHeap cmp r0,#-1 @ allocation error beq 100f mov r5,r0 str r1,[r5,#node_value] @ store value in address heap mov r3,#0 str r3,[r5,#node_left] @ init left pointer with zero str r3,[r5,#node_right] @ init right pointer with zero str r3,[r5,#node_height] @ init balance with zero ldr r2,[r7,#tree_size] @ load tree size cmp r2,#0 @ 0 element ? bne 1f str r5,[r7,#tree_root] @ yes -> store in root b 4f 1: @ else search free address in tree ldr r3,[r7,#tree_root] @ start with address root 2: @ begin loop to insertion ldr r4,[r3,#node_value] @ load key cmp r1,r4 beq 6f @ key equal blt 3f @ key < @ key > insertion right ldr r8,[r3,#node_right] @ node empty ? cmp r8,#0 movne r3,r8 @ no -> next node bne 2b @ and loop str r5,[r3,#node_right] @ store node address in right pointer b 4f 3: @ left ldr r8,[r3,#node_left] @ left pointer empty ? cmp r8,#0 movne r3,r8 @ bne 2b @ no -> loop str r5,[r3,#node_left] @ store node address in left pointer 4: str r3,[r5,#node_parent] @ store parent mov r4,#1 str r4,[r5,#node_height] @ store height = 1 mov r0,r5 @ begin node to requilbrate mov r1,r7 @ head address bl equilibrer   5: add r2,#1 @ increment tree size str r2,[r7,#tree_size] mov r0,#0 b 100f 6: @ key equal ? ldr r0,iAdrszMessKeyDbl bl affichageMess mov r0,#-1 b 100f 100: pop {r1-r8,lr} @ restaur registers bx lr @ return iAdrszMessKeyDbl: .int szMessKeyDbl /******************************************************************/ /* equilibrer after insertion */ /******************************************************************/ /* r0 contains the address of the node */ /* r1 contains the address of head */ equilibrer: @ INFO: equilibrer push {r1-r8,lr} @ save registers mov r3,#0 @ balance factor 1: @ begin loop ldr r5,[r0,#node_parent] @ load father cmp r5,#0 @ end ? beq 5f cmp r3,#2 @ right tree too long beq 5f cmp r3,#-2 @ left tree too long beq 5f mov r6,r0 @ s = current ldr r0,[r6,#node_parent] @ current = father ldr r7,[r0,#node_left] cmp r7,#0 ldrne r8,[r7,#node_height] @ height left tree moveq r8,#0 ldr r7,[r0,#node_right] cmp r7,#0 ldrne r9,[r7,#node_height] @ height right tree moveq r9,#0 cmp r8,r9 addgt r8,#1 strgt r8,[r0,#node_height] addle r9,#1 strle r9,[r0,#node_height] // ldr r7,[r0,#node_right] cmp r7,#0 ldrne r8,[r7,#node_height] moveq r8,#0 ldr r7,[r0,#node_left] cmp r7,#0 ldrne r9,[r7,#node_height] moveq r9,#0 sub r3,r8,r9 @ compute balance factor b 1b 5: cmp r3,#2 beq 6f cmp r3,#-2 beq 6f b 100f 6: mov r3,r1 mov r4,r0 mov r1,r6 bl equiUnSommet @ change head address ? ldr r2,[r3,#tree_root] cmp r2,r4 streq r6,[r3,#tree_root] 100: pop {r1-r8,lr} @ restaur registers bx lr @ return /******************************************************************/ /* equilibre 1 sommet */ /******************************************************************/ /* r0 contains the address of the node */ /* r1 contains the address of the node */ equiUnSommet: @ INFO: equiUnSommet push {r1-r9,lr} @ save registers mov r5,r0 @ save p mov r6,r1 // s ldr r2,[r5,#node_left] cmp r2,r6 bne 5f ldr r7,[r5,#node_right] cmp r7,#0 moveq r8,#0 ldrne r8,[r7,#node_height] ldr r7,[r5,#node_left] cmp r7,#0 moveq r9,#0 ldrne r9,[r7,#node_height] sub r3,r8,r9 cmp r3,#-2 bne 100f ldr r7,[r6,#node_right] cmp r7,#0 moveq r8,#0 ldrne r8,[r7,#node_height] ldr r7,[r6,#node_left] cmp r7,#0 moveq r9,#0 ldrne r9,[r7,#node_height] sub r3,r8,r9 cmp r3,#1 bge 2f mov r0,r5 bl rotRight b 100f 2: mov r0,r6 bl rotLeft mov r0,r5 bl rotRight b 100f   5: ldr r7,[r5,#node_right] cmp r7,#0 moveq r8,#0 ldrne r8,[r7,#node_height] ldr r7,[r5,#node_left] cmp r7,#0 moveq r9,#0 ldrne r9,[r7,#node_height] sub r3,r8,r9 cmp r3,#2 bne 100f ldr r7,[r6,#node_right] cmp r7,#0 moveq r8,#0 ldrne r8,[r7,#node_height] ldr r7,[r6,#node_left] cmp r7,#0 moveq r9,#0 ldrne r9,[r7,#node_height] sub r3,r8,r9 cmp r3,#-1 ble 2f mov r0,r5 bl rotLeft b 100f 2: mov r0,r6 bl rotRight mov r0,r5 bl rotLeft b 100f   100: pop {r1-r9,lr} @ restaur registers bx lr @ return /******************************************************************/ /* right rotation */ /******************************************************************/ /* r0 contains the address of the node */ rotRight: @ INFO: rotRight push {r1-r5,lr} @ save registers // r2 r2 // r0 r1 // r1 r0 // r3 r3 ldr r1,[r0,#node_left] @ load left children ldr r2,[r0,#node_parent] @ load father cmp r2,#0 @ no father ??? beq 2f ldr r3,[r2,#node_left] @ load left node father cmp r3,r0 @ equal current node ? streq r1,[r2,#node_left] @ yes store left children strne r1,[r2,#node_right] @ no store right 2: str r2,[r1,#node_parent] @ change parent str r1,[r0,#node_parent] ldr r3,[r1,#node_right] str r3,[r0,#node_left] cmp r3,#0 strne r0,[r3,#node_parent] @ change parent node left str r0,[r1,#node_right]   ldr r3,[r0,#node_left] @ compute newbalance factor cmp r3,#0 moveq r4,#0 ldrne r4,[r3,#node_height] ldr r3,[r0,#node_right] cmp r3,#0 moveq r5,#0 ldrne r5,[r3,#node_height] cmp r4,r5 addgt r4,#1 strgt r4,[r0,#node_height] addle r5,#1 strle r5,[r0,#node_height] // ldr r3,[r1,#node_left] @ compute new balance factor cmp r3,#0 moveq r4,#0 ldrne r4,[r3,#node_height] ldr r3,[r1,#node_right] cmp r3,#0 moveq r5,#0 ldrne r5,[r3,#node_height] cmp r4,r5 addgt r4,#1 strgt r4,[r1,#node_height] addle r5,#1 strle r5,[r1,#node_height] 100: pop {r1-r5,lr} @ restaur registers bx lr /******************************************************************/ /* left rotation */ /******************************************************************/ /* r0 contains the address of the node sommet */ rotLeft: @ INFO: rotLeft push {r1-r5,lr} @ save registers // r2 r2 // r0 r1 // r1 r0 // r3 r3 ldr r1,[r0,#node_right] @ load right children ldr r2,[r0,#node_parent] @ load father (racine) cmp r2,#0 @ no father ??? beq 2f ldr r3,[r2,#node_left] @ load left node father cmp r3,r0 @ equal current node ? streq r1,[r2,#node_left] @ yes store left children strne r1,[r2,#node_right] @ no store to right 2: str r2,[r1,#node_parent] @ change parent of right children str r1,[r0,#node_parent] @ change parent of sommet ldr r3,[r1,#node_left] @ left children str r3,[r0,#node_right] @ left children pivot exists ? cmp r3,#0 strne r0,[r3,#node_parent] @ yes store in str r0,[r1,#node_left] // ldr r3,[r0,#node_left] @ compute new height for old summit cmp r3,#0 moveq r4,#0 ldrne r4,[r3,#node_height] @ left height ldr r3,[r0,#node_right] cmp r3,#0 moveq r5,#0 ldrne r5,[r3,#node_height] @ right height cmp r4,r5 addgt r4,#1 strgt r4,[r0,#node_height] @ if right > left addle r5,#1 strle r5,[r0,#node_height] @ if left > right // ldr r3,[r1,#node_left] @ compute new height for new cmp r3,#0 moveq r4,#0 ldrne r4,[r3,#node_height] ldr r3,[r1,#node_right] cmp r3,#0 moveq r5,#0 ldrne r5,[r3,#node_height] cmp r4,r5 addgt r4,#1 strgt r4,[r1,#node_height] addle r5,#1 strle r5,[r1,#node_height] 100: pop {r1-r5,lr} @ restaur registers bx lr /******************************************************************/ /* search value in tree */ /******************************************************************/ /* r0 contains the address of structure of tree */ /* r1 contains the value to search */ searchTree: @ INFO: searchTree push {r1-r4,lr} @ save registers ldr r2,[r0,#tree_root]   1: @ begin loop ldr r4,[r2,#node_value] @ load key cmp r1,r4 beq 3f @ key equal blt 2f @ key < @ key > insertion right ldr r3,[r2,#node_right] @ node empty ? cmp r3,#0 movne r2,r3 @ no -> next node bne 1b @ and loop mov r0,#-1 @ not find b 100f 2: @ left ldr r3,[r2,#node_left] @ left pointer empty ? cmp r3,#0 movne r2,r3 @ bne 1b @ no -> loop mov r0,#-1 @ not find b 100f 3: mov r0,r2 @ return node address 100: pop {r1-r4,lr} @ restaur registers bx lr /******************************************************************/ /* suppression node */ /******************************************************************/ /* r0 contains the address of the node */ /* r1 contains structure tree address */ supprimer: @ INFO: supprimer push {r1-r8,lr} @ save registers ldr r1,[r0,#node_left] cmp r1,#0 bne 5f ldr r1,[r0,#node_right] cmp r1,#0 bne 5f @ is a leaf mov r4,#0 ldr r3,[r0,#node_parent] @ father cmp r3,#0 streq r4,[r1,#tree_root] beq 100f ldr r1,[r3,#node_left] cmp r1,r0 bne 2f str r4,[r3,#node_left] @ suppression left children ldr r5,[r3,#node_right] cmp r5,#0 moveq r6,#0 ldrne r6,[r5,#node_height] add r6,#1 str r6,[r3,#node_height] b 3f 2: @ suppression right children str r4,[r3,#node_right] ldr r5,[r3,#node_left] cmp r5,#0 moveq r6,#0 ldrne r6,[r5,#node_height] add r6,#1 str r6,[r3,#node_height] 3: @ new balance mov r0,r3 bl equilibrerSupp b 100f 5: @ is not à leaf ldr r7,[r0,#node_right] cmp r7,#0 beq 7f mov r8,r0 mov r0,r7 6: ldr r6,[r0,#node_left] cmp r6,#0 movne r0,r6 bne 6b b 9f 7: ldr r7,[r0,#node_left] @ search the litle element cmp r7,#0 beq 9f mov r8,r0 mov r0,r7 8: ldr r6,[r0,#node_right] @ search the great element cmp r6,#0 movne r0,r6 bne 8b 9: ldr r5,[r0,#node_value] @ copy value str r5,[r8,#node_value] bl supprimer @ suppression node r0 100: pop {r1-r8,lr} @ restaur registers bx lr   /******************************************************************/ /* equilibrer after suppression */ /******************************************************************/ /* r0 contains the address of the node */ /* r1 contains the address of head */ equilibrerSupp: @ INFO: equilibrerSupp push {r1-r8,lr} @ save registers mov r3,#1 @ balance factor ldr r2,[r1,#tree_root] 1: ldr r5,[r0,#node_parent] @ load father cmp r5,#0 @ no father beq 100f cmp r3,#0 @ balance equilibred beq 100f mov r6,r0 @ save entry node ldr r0,[r6,#node_parent] @ current = father ldr r7,[r0,#node_left] cmp r7,#0 ldrne r8,[r7,#node_height] @ height left tree moveq r8,#0 ldr r7,[r0,#node_right] cmp r7,#0 ldrne r9,[r7,#node_height] @ height right tree moveq r9,#0 cmp r8,r9 addgt r8,#1 strgt r8,[r0,#node_height] addle r9,#1 strle r9,[r0,#node_height] // ldr r7,[r0,#node_right] cmp r7,#0 ldrne r8,[r7,#node_height] moveq r8,#0 ldr r7,[r0,#node_left] cmp r7,#0 ldrne r9,[r7,#node_height] moveq r9,#0 sub r3,r8,r9 @ compute balance factor mov r2,r1 mov r4,r0 @ save current mov r1,r6 bl equiUnSommet @ change head address ? cmp r2,r4 streq r6,[r3,#tree_root] mov r0,r4 @ restaur current b 1b   100: pop {r1-r8,lr} @ restaur registers bx lr @ return /******************************************************************/ /* preOrder */ /******************************************************************/ /* r0 contains the address of the node */ /* r1 function address */ preOrder: @ INFO: preOrder push {r1-r2,lr} @ save registers cmp r0,#0 beq 100f mov r2,r0 blx r1 @ call function   ldr r0,[r2,#node_left] bl preOrder ldr r0,[r2,#node_right] bl preOrder 100: pop {r1-r2,lr} @ restaur registers bx lr   /******************************************************************/ /* display node */ /******************************************************************/ /* r0 contains node address */ displayElement: @ INFO: displayElement push {r1,r2,r3,lr} @ save registers mov r2,r0 ldr r1,iAdrsZoneConv bl conversion16 mov r4,#0 strb r4,[r1,r0] ldr r0,iAdrszMessResult ldr r1,iAdrsZoneConv bl strInsertAtCharInc mov r3,r0 ldr r0,[r2,#node_left] ldr r1,iAdrsZoneConv bl conversion16 mov r4,#0 strb r4,[r1,r0] mov r0,r3 ldr r1,iAdrsZoneConv bl strInsertAtCharInc mov r3,r0 ldr r0,[r2,#node_right] ldr r1,iAdrsZoneConv bl conversion16 mov r4,#0 strb r4,[r1,r0] mov r0,r3 ldr r1,iAdrsZoneConv bl strInsertAtCharInc mov r3,r0 ldr r0,[r2,#node_value] ldr r1,iAdrsZoneConv bl conversion10 mov r4,#0 strb r4,[r1,r0] mov r0,r3 ldr r1,iAdrsZoneConv bl strInsertAtCharInc mov r3,r0 ldr r0,[r2,#node_height] ldr r1,iAdrsZoneConv bl conversion10 mov r4,#0 strb r4,[r1,r0] mov r0,r3 ldr r1,iAdrsZoneConv bl strInsertAtCharInc mov r3,r0 ldr r0,[r2,#node_parent] ldr r1,iAdrsZoneConv bl conversion16 mov r4,#0 strb r4,[r1,r0] mov r0,r3 ldr r1,iAdrsZoneConv bl strInsertAtCharInc bl affichageMess 100: pop {r1,r2,r3,lr} @ restaur registers bx lr @ return iAdrszMessResult: .int szMessResult iAdrsZoneConv: .int sZoneConv iAdrsValue: .int sValue   /******************************************************************/ /* memory allocation on the heap */ /******************************************************************/ /* r0 contains the size to allocate */ /* r0 returns address of memory heap or - 1 if error */ /* CAUTION : The size of the allowance must be a multiple of 4 */ allocHeap: push {r5-r7,lr} @ save registers @ allocation mov r6,r0 @ save size mov r0,#0 @ read address start heap mov r7,#0x2D @ call system 'brk' svc #0 mov r5,r0 @ save address heap for return add r0,r6 @ reservation place for size mov r7,#0x2D @ call system 'brk' svc #0 cmp r0,#-1 @ allocation error movne r0,r5 @ return address memory heap pop {r5-r7,lr} @ restaur registers bx lr @ return /***************************************************/ /* ROUTINES INCLUDE */ /***************************************************/ .include "../affichage.inc"  
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
#AutoHotkey
AutoHotkey
Angles := [[350, 10], [90, 180, 270, 360], [10, 20, 30]] MsgBox, % MeanAngle(Angles[1]) "`n" . MeanAngle(Angles[2]) "`n" . MeanAngle(Angles[3])   MeanAngle(a, x=0, y=0) { static c := ATan(1) / 45 for k, v in a { x += Cos(v * c) / a.MaxIndex() y += Sin(v * c) / a.MaxIndex() } return atan2(x, y) / c }   atan2(x, y) { return dllcall("msvcrt\atan2", "Double",y, "Double",x, "CDECL Double") }
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
#ALGOL_68
ALGOL 68
INT max_elements = 1000000;   # Return the k-th smallest item in array x of length len # PROC quick_select = (INT k, REF[]REAL x) REAL: BEGIN   PROC swap = (INT a, b) VOID: BEGIN REAL t = x[a]; x[a] := x[b]; x[b] := t END;   INT left := 1, right := UPB x; INT pos, i; REAL pivot;   WHILE left < right DO pivot := x[k]; swap (k, right); pos := left; FOR i FROM left TO right DO IF x[i] < pivot THEN swap (i, pos); pos +:= 1 FI OD; swap (right, pos); IF pos = k THEN break FI; IF pos < k THEN left := pos + 1 ELSE right := pos - 1 FI OD; break: SKIP; x[k] END;   # Initialize random length REAL array with random doubles # INT length = ENTIER (next random * max_elements); [length]REAL x; FOR i TO length DO x[i] := (next random * 1e6 - 0.5e6) OD;   REAL median := IF NOT ODD length THEN # Even number of elements, median is average of middle two # (quick_select (length % 2, x) + quick_select(length % 2 - 1, x)) / 2 ELSE # select middle element # quick_select(length % 2, x) FI;   # Sanity testing of median # INT less := 0, more := 0, eq := 0; FOR i TO length DO IF x[i] < median THEN less +:= 1 ELIF x[i] > median THEN more +:= 1 ELSE eq +:= 1 FI OD; print (("length: ", whole (length,0), new line, "median: ", median, new line, "<: ", whole (less,0), new line, ">: ", whole (more, 0), new line, "=: ", whole (eq, 0), new line))
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
#Elixir
Elixir
defmodule Means do def arithmetic(list) do Enum.sum(list) / length(list) end def geometric(list) do  :math.pow(Enum.reduce(list, &(*/2)), 1 / length(list)) end def harmonic(list) do 1 / arithmetic(Enum.map(list, &(1 / &1))) end end   list = Enum.to_list(1..10) IO.puts "Arithmetic mean: #{am = Means.arithmetic(list)}" IO.puts "Geometric mean: #{gm = Means.geometric(list)}" IO.puts "Harmonic mean: #{hm = Means.harmonic(list)}" IO.puts "(#{am} >= #{gm} >= #{hm}) is #{am >= gm and gm >= hm}"
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.
#D
D
import std.stdio, std.bigint, std.range, std.algorithm;   struct BalancedTernary { // Represented as a list of 0, 1 or -1s, // with least significant digit first. enum Dig : byte { N=-1, Z=0, P=+1 } // Digit. const Dig[] digits;   // This could also be a BalancedTernary template argument. static immutable string dig2str = "-0+";   immutable static Dig[dchar] str2dig; // = ['+': Dig.P, ...]; nothrow static this() { str2dig = ['+': Dig.P, '-': Dig.N, '0': Dig.Z]; }   immutable pure nothrow static Dig[2][] table = [[Dig.Z, Dig.N], [Dig.P, Dig.N], [Dig.N, Dig.Z], [Dig.Z, Dig.Z], [Dig.P, Dig.Z], [Dig.N, Dig.P], [Dig.Z, Dig.P]];   this(in string inp) const pure { this.digits = inp.retro.map!(c => str2dig[c]).array; }   this(in long inp) const pure nothrow { this.digits = _bint2ternary(inp.BigInt); }   this(in BigInt inp) const pure nothrow { this.digits = _bint2ternary(inp); }   this(in BalancedTernary inp) const pure nothrow { // No need to dup, they are virtually immutable. this.digits = inp.digits; }   private this(in Dig[] inp) pure nothrow { this.digits = inp; }   static Dig[] _bint2ternary(in BigInt n) pure nothrow { static py_div(T1, T2)(in T1 a, in T2 b) pure nothrow { if (a < 0) { return (b < 0) ? -a / -b : -(-a / b) - (-a % b != 0 ? 1 : 0); } else { return (b < 0) ? -(a / -b) - (a % -b != 0 ? 1 : 0) : a / b; } }   if (n == 0) return []; // This final switch in D v.2.064 is fake, not enforced. final switch (((n % 3) + 3) % 3) { // (n % 3) is the remainder. case 0: return Dig.Z ~ _bint2ternary(py_div(n, 3)); case 1: return Dig.P ~ _bint2ternary(py_div(n, 3)); case 2: return Dig.N ~ _bint2ternary(py_div(n + 1, 3)); } }   @property BigInt toBint() const pure nothrow { return reduce!((y, x) => x + 3 * y)(0.BigInt, digits.retro); }   string toString() const pure nothrow { if (digits.empty) return "0"; return digits.retro.map!(d => dig2str[d + 1]).array; }   static const(Dig)[] neg_(in Dig[] digs) pure nothrow { return digs.map!(a => -a).array; }   BalancedTernary opUnary(string op:"-")() const pure nothrow { return BalancedTernary(neg_(this.digits)); }   static const(Dig)[] add_(in Dig[] a, in Dig[] b, in Dig c=Dig.Z) pure nothrow { const a_or_b = a.length ? a : b; if (a.empty || b.empty) { if (c == Dig.Z) return a_or_b; else return BalancedTernary.add_([c], a_or_b); } else { // (const d, c) = table[...]; const dc = table[3 + (a.length ? a[0] : 0) + (b.length ? b[0] : 0) + c]; const res = add_(a[1 .. $], b[1 .. $], dc[1]); // Trim leading zeros. if (res.length || dc[0] != Dig.Z) return [dc[0]] ~ res; else return res; } }   BalancedTernary opBinary(string op:"+")(in BalancedTernary b) const pure nothrow { return BalancedTernary(add_(this.digits, b.digits)); }   BalancedTernary opBinary(string op:"-")(in BalancedTernary b) const pure nothrow { return this + (-b); }   static const(Dig)[] mul_(in Dig[] a, in Dig[] b) pure nothrow { if (a.empty || b.empty) { return []; } else { const y = Dig.Z ~ mul_(a[1 .. $], b); final switch (a[0]) { case Dig.N: return add_(neg_(b), y); case Dig.Z: return add_([], y); case Dig.P: return add_(b, y); } } }   BalancedTernary opBinary(string op:"*")(in BalancedTernary b) const pure nothrow { return BalancedTernary(mul_(this.digits, b.digits)); } }   void main() { immutable a = BalancedTernary("+-0++0+"); writeln("a: ", a.toBint, ' ', a);   immutable b = BalancedTernary(-436); writeln("b: ", b.toBint, ' ', b);   immutable c = BalancedTernary("+-++-"); writeln("c: ", c.toBint, ' ', c);   const /*immutable*/ r = a * (b - c); writeln("a * (b - c): ", r.toBint, ' ', r); }
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.
#M2000_Interpreter
M2000 Interpreter
Def Long k=1000000, T=269696, n n=Sqrt(269696) For n=n to k { If n^2 mod k = T Then Exit } Report format$("The smallest number whose square ends in {0} is {1}, Its square is {2}", T, n, n**2)  
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Solve[Mod[x^2, 10^6] == 269696 && 0 <= x <= 99736, x, Integers]
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
#Arturo
Arturo
isBalanced: function [s][ cnt: 0   loop split s [ch][ if? ch="]" [ cnt: cnt-1 if cnt<0 -> return false ] else [ if ch="[" -> cnt: cnt+1 ] ]   cnt=0 ]   loop 1..10 'i [ str: join map 0..(2*i)-1 [x][ sample ["[" "]"]]   prints str   if? isBalanced str -> print " OK" else -> print " Not OK" ]
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
#EchoLisp
EchoLisp
  (define (modes L) (define G (group* L)) ;; sorts and group equal items (define cardmax (for/max [(g G)] (length g))) (map first (filter (lambda(g) (= cardmax (length g))) G)))   (modes '( a b c a d e f)) → (a) (modes (iota 6)) → (0 1 2 3 4 5) (modes '(x)) → (x) (modes '(🎾 🏉 ☕️ 🎾 🎲 🎯 🎺 ☕️ 🎲 🎸 🎻 🏆 ☕️ 🏁 🎾 🎲 🎻 🏉 )) → (🎾 ☕️ 🎲)   (modes '()) 😖️ error: group : expected list : null 🔎 'modes'  
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
#ooRexx
ooRexx
  testdata = .array~of(1, 2, 3, 4, 5, 5, 4, 3, 2, 1)   -- run with different period sizes loop period over .array~of(3, 5) say "Period size =" period say movingaverage = .movingaverage~new(period) loop number over testdata average = movingaverage~addnumber(number) say " Next number =" number", moving average =" average end say end   ::class movingaverage ::method init expose period queue sum use strict arg period sum = 0 -- the circular queue makes this easy queue = .circularqueue~new(period)   -- add a number to the average set ::method addNumber expose queue sum use strict arg number sum += number -- add this to the queue old = queue~queue(number) -- if we pushed an element off the end of the queue, -- subtract this from our sum if old \= .nil then sum -= old -- and return the current item return sum / queue~items   -- extra method to retrieve current average ::method average expose queue sum -- undefined really, but just return 0 if queue~isempty then return 0 -- return current queue return sum / queue~items  
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
#Common_Lisp
Common Lisp
;; * Loading the split-sequence library (eval-when (:compile-toplevel :load-toplevel :execute) (ql:quickload '("split-sequence")))   ;; * The package definition (defpackage :mean-time-of-day (:use :common-lisp :iterate :split-sequence)) (in-package :mean-time-of-day)   ;; * The data (defparameter *time-values* '("23:00:17" "23:40:20" "00:12:45" "00:17:19"))   (defun time->radian (time) "Returns the radian value for TIME given as a STRING like HH:MM:SS. Assuming a valid input value." (destructuring-bind (h m s) (mapcar #'parse-integer (split-sequence #\: time)) (+ (* h (/ PI 12)) (* m (/ PI 12 60)) (* s (/ PI 12 3600)))))   (defun radian->time (radian) "Returns the corresponding time as a string like HH:MM:SS for RADIAN." (let* ((time (if (plusp radian) (round (/ (* 12 3600 radian) PI)) (round (/ (* 12 3600 (+ radian (* 2 PI))) PI)))) (h (floor time 3600)) (m (floor (- time (* h 3600)) 60)) (s (- time (* h 3600) (* m 60)))) (format nil "~2,'0D:~2,'0D:~2,'0D" h m s)))   (defun make-polar (rho theta) "Returns a complex representing the polar coordinates." (complex (* rho (cos theta)) (* rho (sin theta))))   (defun mean-time (times) "Returns the mean time value within 24h of the list of TIMES given as strings HH:MM:SS." (radian->time (phase (reduce #'+ (mapcar (lambda (time) (make-polar 1 (time->radian time))) times)))))