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/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.
#ATS
ATS
(*------------------------------------------------------------------*)   #define ATS_DYNLOADFLAG 0   #include "share/atspre_staload.hats"   (*------------------------------------------------------------------*)   (*   Persistent AVL trees.   References:   * Niklaus Wirth, 1976. Algorithms + Data Structures = Programs. Prentice-Hall, Englewood Cliffs, New Jersey.   * Niklaus Wirth, 2004. Algorithms and Data Structures. Updated by Fyodor Tkachov, 2014.   (Note: Wirth’s implementations, which are in Pascal and Oberon, are for non-persistent trees.)   *)   (*------------------------------------------------------------------*)   (*   For now, a very simple interface, without much provided in the way of proofs.   You could put all this interface stuff into a .sats file. (You would have to remove the word ‘extern’ from the definitions.)   You might also make avl_t abstract, and put these details in the .dats file; you would use ‘assume’ to identify the abstract type with an implemented type. That approach would require some name changes, and also would make pattern matching on the trees impossible outside their implementation. Having users do pattern matching on the AVL trees probably is a terrible idea, anyway.   *)   datatype bal_t = | bal_minus1 | bal_zero | bal_plus1   datatype avl_t (key_t  : t@ype+, data_t : t@ype+, size  : int) = | avl_t_nil (key_t, data_t, 0) | {size_L, size_R : nat} avl_t_cons (key_t, data_t, size_L + size_R + 1) of (key_t, data_t, bal_t, avl_t (key_t, data_t, size_L), avl_t (key_t, data_t, size_R)) typedef avl_t (key_t  : t@ype+, data_t : t@ype+) = [size : int] avl_t (key_t, data_t, size)   extern prfun lemma_avl_t_param : {key_t, data_t : t@ype} {size : int} avl_t (key_t, data_t, size) -<prf> [0 <= size] void   (* Implement this template, for whichever type of key you are using. It should return a negative number if u < v, zero if u = v, or a positive number if u > v. *) extern fun {key_t : t@ype} avl_t$compare (u : key_t, v : key_t) :<> int   (* Is the AVL tree empty? *) extern fun avl_t_is_empty {key_t  : t@ype} {data_t : t@ype} {size  : int} (avl  : avl_t (key_t, data_t, size)) :<> [b : bool | b == (size == 0)] bool b   (* Does the AVL tree contain at least one association? *) extern fun avl_t_isnot_empty {key_t  : t@ype} {data_t : t@ype} {size  : int} (avl  : avl_t (key_t, data_t, size)) :<> [b : bool | b == (size <> 0)] bool b   (* How many associations are stored in the AVL tree? (Currently we have no way to do an avl_t_size that preserves the ‘size’ static value. This is the best we can do.) *) extern fun {key_t  : t@ype} {data_t : t@ype} avl_t_size {size : int} (avl  : avl_t (key_t, data_t, size)) :<> [sz : int | (size == 0 && sz == 0) || (0 < size && 0 < sz)] size_t sz   (* Does the AVL tree contain the given key? *) extern fun {key_t  : t@ype} {data_t : t@ype} avl_t_has_key {size : int} (avl  : avl_t (key_t, data_t, size), key  : key_t) :<> bool   (* Search for a key. If the key is found, return the data value associated with it. Otherwise return the value of ‘dflt’. *) extern fun {key_t  : t@ype} {data_t : t@ype} avl_t_search_dflt {size : int} (avl  : avl_t (key_t, data_t, size), key  : key_t, dflt : data_t) :<> data_t   (* Search for a key. If the key is found, return ‘Some(data)’. Otherwise return ‘None()’. *) extern fun {key_t  : t@ype} {data_t : t@ype} avl_t_search_opt {size : int} (avl  : avl_t (key_t, data_t, size), key  : key_t) :<> Option (data_t)   (* Search for a key. If the key is found, set ‘found’ to true, and set ‘data’. Otherwise set ‘found’ to false. *) extern fun {key_t  : t@ype} {data_t : t@ype} avl_t_search_ref {size  : int} (avl  : avl_t (key_t, data_t, size), key  : key_t, data  : &data_t? >> opt (data_t, found), found : &bool? >> bool found) :<!wrt> #[found : bool] void   (* Overload avl_t_search; these functions are easy for the compiler to distinguish. *) overload avl_t_search with avl_t_search_dflt overload avl_t_search with avl_t_search_opt overload avl_t_search with avl_t_search_ref   (* If a key is not present in the AVL tree, insert the key-data association; return the new AVL tree. If the key *is* present in the AVL tree, then *replace* the key-data association; return the new AVL tree. *) extern fun {key_t  : t@ype} {data_t : t@ype} avl_t_insert {size : int} (avl  : avl_t (key_t, data_t, size), key  : key_t, data : data_t) :<> [sz : pos] avl_t (key_t, data_t, sz)   (* If a key is not present in the AVL tree, insert the key-data association; return the new AVL tree and ‘true’. If the key *is* present in the AVL tree, then *replace* the key-data association; return the new AVL tree and ‘false’. *) extern fun {key_t  : t@ype} {data_t : t@ype} avl_t_insert_or_replace {size : int} (avl  : avl_t (key_t, data_t, size), key  : key_t, data : data_t) :<> [sz : pos] (avl_t (key_t, data_t, sz), bool)   (* If a key is present in the AVL tree, delete the key-data association; otherwise return the tree as it came. *) extern fun {key_t  : t@ype} {data_t : t@ype} avl_t_delete {size : int} (avl  : avl_t (key_t, data_t, size), key  : key_t) :<> [sz : nat] avl_t (key_t, data_t, sz)   (* If a key is present in the AVL tree, delete the key-data association; otherwise return the tree as it came. Also, return a bool to indicate whether or not the key was found; ‘true’ if found, ‘false’ if not. *) extern fun {key_t  : t@ype} {data_t : t@ype} avl_t_delete_if_found {size : int} (avl  : avl_t (key_t, data_t, size), key  : key_t) :<> [sz : nat] (avl_t (key_t, data_t, sz), bool)   (* Return a sorted list of the association pairs in an AVL tree. (Currently we have no way to do an avl_t_pairs that preserves the ‘size’ static value. This is the best we can do.) *) extern fun {key_t  : t@ype} {data_t : t@ype} avl_t_pairs {size : int} (avl  : avl_t (key_t, data_t, size)) :<> [sz : int | (size == 0 && sz == 0) || (0 < size && 0 < sz)] list ((key_t, data_t), sz)   (* Return a sorted list of the keys in an AVL tree. (Currently we have no way to do an avl_t_keys that preserves the ‘size’ static value. This is the best we can do.) *) extern fun {key_t  : t@ype} {data_t : t@ype} avl_t_keys {size : int} (avl  : avl_t (key_t, data_t, size)) :<> [sz : int | (size == 0 && sz == 0) || (0 < size && 0 < sz)] list (key_t, sz)   (* Return a list of the data values in an AVL tree, sorted in the order of their keys. (Currently we have no way to do an avl_t_data that preserves the ‘size’ static value. This is the best we can do.) *) extern fun {key_t  : t@ype} {data_t : t@ype} avl_t_data {size : int} (avl  : avl_t (key_t, data_t, size)) :<> [sz : int | (size == 0 && sz == 0) || (0 < size && 0 < sz)] list (data_t, sz)   (* list2avl_t does the reverse of what avl_t_pairs does (although they are not inverses of each other). Currently we have no way to do a list2avl_t that preserves the ‘size’ static value. This is the best we can do. *) extern fun {key_t  : t@ype} {data_t : t@ype} list2avl_t {size : int} (lst  : list ((key_t, data_t), size)) :<> [sz : int | (size == 0 && sz == 0) || (0 < size && 0 < sz)] avl_t (key_t, data_t, sz)   (* Make a closure that returns association pairs in either forwards or reverse order. *) extern fun {key_t  : t@ype} {data_t : t@ype} avl_t_make_pairs_generator {size  : int} (avl  : avl_t (key_t, data_t, size), direction : int) : () -<cloref1> Option @(key_t, data_t)   (* Make a closure that returns keys in either forwards or reverse order. *) extern fun {key_t  : t@ype} {data_t : t@ype} avl_t_make_keys_generator {size  : int} (avl  : avl_t (key_t, data_t, size), direction : int) : () -<cloref1> Option key_t   (* Make a closure that returns data values in forwards or reverse order of their keys. *) extern fun {key_t  : t@ype} {data_t : t@ype} avl_t_make_data_generator {size  : int} (avl  : avl_t (key_t, data_t, size), direction : int) : () -<cloref1> Option data_t   (* Raise an assertion if the AVL condition is not met. This template is for testing the code. *) extern fun {key_t  : t@ype} {data_t : t@ype} avl_t_check_avl_condition {size : int} (avl  : avl_t (key_t, data_t, size)) : void   (* Print an AVL tree to standard output, in some useful and perhaps even pretty format. *) extern fun {key_t  : t@ype} {data_t : t@ype} avl_t_pretty_print {size : int} (avl  : avl_t (key_t, data_t, size)) : void   (* Implement this template for whichever types of keys and data you wish to pretty print. *) extern fun {key_t  : t@ype} {data_t : t@ype} avl_t_pretty_print$key_and_data (key  : key_t, data : data_t) : void   (*------------------------------------------------------------------*)   (*   What follows is the implementation. It would go into a .dats file. Note, however, that the .dats file would have to be staloaded! (Preferably anonymously.) This is because the implementation contains template functions.   Notice there are several assertions with ‘$effmask_ntm’ (as opposed to proofs) that the routines are terminating. One hopes to remedy that problem (with proofs).   Also there are some ‘$effmask_wrt’, but these effect masks are safe, because the writing is to our own stack variables.   *)   #define NIL avl_t_nil () #define CONS avl_t_cons #define LNIL list_nil () #define :: list_cons #define F false #define T true   typedef fixbal_t = bool   primplement lemma_avl_t_param avl = case+ avl of | NIL => () | CONS _ => ()   fn {} minus_neg_bal (bal : bal_t) :<> bal_t = case+ bal of | bal_minus1 () => bal_plus1 | _ => bal_zero ()   fn {} minus_pos_bal (bal : bal_t) :<> bal_t = case+ bal of | bal_plus1 () => bal_minus1 | _ => bal_zero ()   fn {} bal2int (bal : bal_t) :<> int = case+ bal of | bal_minus1 () => ~1 | bal_zero () => 0 | bal_plus1 () => 1   implement avl_t_is_empty avl = case+ avl of | NIL => T | CONS _ => F   implement avl_t_isnot_empty avl = ~avl_t_is_empty avl   implement {key_t} {data_t} avl_t_size {siz} avl = let fun traverse {size : int} (p  : avl_t (key_t, data_t, size)) :<!ntm> [sz : int | (size == 0 && sz == 0) || (0 < size && 0 < sz)] size_t sz = case+ p of | NIL => i2sz 0 | CONS (_, _, _, left, right) => let val [sz_L : int] sz_L = traverse left val [sz_R : int] sz_R = traverse right prval _ = prop_verify {0 <= sz_L} () prval _ = prop_verify {0 <= sz_R} () in succ (sz_L + sz_R) end   val [sz : int] sz = $effmask_ntm (traverse {siz} avl) prval _ = prop_verify {(siz == 0 && sz == 0) || (0 < siz && 0 < sz)} () in sz end   implement {key_t} {data_t} avl_t_has_key (avl, key) = let fun search {size : int} (p  : avl_t (key_t, data_t, size)) :<!ntm> bool = case+ p of | NIL => F | CONS (k, _, _, left, right) => begin case+ avl_t$compare<key_t> (key, k) of | cmp when cmp < 0 => search left | cmp when cmp > 0 => search right | _ => T end in $effmask_ntm search avl end   implement {key_t} {data_t} avl_t_search_dflt (avl, key, dflt) = let var data : data_t? var found : bool? val _ = $effmask_wrt avl_t_search_ref (avl, key, data, found) in if found then let prval _ = opt_unsome data in data end else let prval _ = opt_unnone data in dflt end end   implement {key_t} {data_t} avl_t_search_opt (avl, key) = let var data : data_t? var found : bool? val _ = $effmask_wrt avl_t_search_ref (avl, key, data, found) in if found then let prval _ = opt_unsome data in Some {data_t} data end else let prval _ = opt_unnone data in None {data_t} () end end   implement {key_t} {data_t} avl_t_search_ref (avl, key, data, found) = let fun search (p  : avl_t (key_t, data_t), data  : &data_t? >> opt (data_t, found), found : &bool? >> bool found) :<!wrt,!ntm> #[found : bool] void = case+ p of | NIL => { prval _ = opt_none {data_t} data val _ = found := F } | CONS (k, d, _, left, right) => begin case+ avl_t$compare<key_t> (key, k) of | cmp when cmp < 0 => search (left, data, found) | cmp when cmp > 0 => search (right, data, found) | _ => { val _ = data := d prval _ = opt_some {data_t} data val _ = found := T } end in $effmask_ntm search (avl, data, found) end   implement {key_t} {data_t} avl_t_insert (avl, key, data) = let val (avl, _) = avl_t_insert_or_replace<key_t><data_t> (avl, key, data) in avl end   implement {key_t} {data_t} avl_t_insert_or_replace (avl, key, data) = let fun search {size  : nat} (p  : avl_t (key_t, data_t, size), fixbal : fixbal_t, found  : bool) :<!ntm> [sz : pos] (avl_t (key_t, data_t, sz), fixbal_t, bool) = case+ p of | NIL => (* The key was not found. Insert a new node. The tree will need rebalancing. *) (CONS (key, data, bal_zero, NIL, NIL), T, F) | CONS (k, d, bal, left, right) => case+ avl_t$compare<key_t> (key, k) of | cmp when cmp < 0 => let val (p1, fixbal, found) = search (left, fixbal, found) in (* If fixbal is T, then a node has been inserted on the left, and rebalancing may be necessary. *) case+ (fixbal, bal) of | (F, _) => (* No rebalancing is necessary. *) (CONS (k, d, bal, p1, right), F, found) | (T, bal_plus1 ()) => (* No rebalancing is necessary. *) (CONS (k, d, bal_zero (), p1, right), F, found) | (T, bal_zero ()) => (* Rebalancing might still be necessary. *) (CONS (k, d, bal_minus1 (), p1, right), fixbal, found) | (T, bal_minus1 ()) => (* Rebalancing is necessary. *) let val+ CONS (k1, d1, bal1, left1, right1) = p1 in case+ bal1 of | bal_minus1 () => (* A single LL rotation. *) let val q = CONS (k, d, bal_zero (), right1, right) val q1 = CONS (k1, d1, bal_zero (), left1, q) in (q1, F, found) end | _ => (* A double LR rotation. *) let val p2 = right1 val- CONS (k2, d2, bal2, left2, right2) = p2 val q = CONS (k, d, minus_neg_bal bal2, right2, right) val q1 = CONS (k1, d1, minus_pos_bal bal2, left1, left2) val q2 = CONS (k2, d2, bal_zero (), q1, q) in (q2, F, found) end end end | cmp when cmp > 0 => let val (p1, fixbal, found) = search (right, fixbal, found) in (* If fixbal is T, then a node has been inserted on the right, and rebalancing may be necessary. *) case+ (fixbal, bal) of | (F, _) => (* No rebalancing is necessary. *) (CONS (k, d, bal, left, p1), F, found) | (T, bal_minus1 ()) => (* No rebalancing is necessary. *) (CONS (k, d, bal_zero (), left, p1), F, found) | (T, bal_zero ()) => (* Rebalancing might still be necessary. *) (CONS (k, d, bal_plus1 (), left, p1), fixbal, found) | (T, bal_plus1 ()) => (* Rebalancing is necessary. *) let val+ CONS (k1, d1, bal1, left1, right1) = p1 in case+ bal1 of | bal_plus1 () => (* A single RR rotation. *) let val q = CONS (k, d, bal_zero (), left, left1) val q1 = CONS (k1, d1, bal_zero (), q, right1) in (q1, F, found) end | _ => (* A double RL rotation. *) let val p2 = left1 val- CONS (k2, d2, bal2, left2, right2) = p2 val q = CONS (k, d, minus_pos_bal bal2, left, left2) val q1 = CONS (k1, d1, minus_neg_bal bal2, right2, right1) val q2 = CONS (k2, d2, bal_zero (), q, q1) in (q2, F, found) end end end | _ => (* The key was found; p is an existing node. Replace it. The tree needs no rebalancing. *) (CONS (key, data, bal, left, right), F, T) in if avl_t_is_empty avl then (* Start a new tree. *) (CONS (key, data, bal_zero, NIL, NIL), F) else let prval _ = lemma_avl_t_param avl val (avl, _, found) = $effmask_ntm search (avl, F, F) in (avl, found) end end   fn {key_t  : t@ype} {data_t : t@ype} balance_for_shrunken_left {size : pos} (p  : avl_t (key_t, data_t, size)) :<> (* Returns a new avl_t, and a ‘fixbal’ flag. *) [sz : pos] (avl_t (key_t, data_t, sz), fixbal_t) = let val+ CONS (k, d, bal, left, right) = p in case+ bal of | bal_minus1 () => (CONS (k, d, bal_zero, left, right), T) | bal_zero () => (CONS (k, d, bal_plus1, left, right), F) | bal_plus1 () => (* Rebalance. *) let val p1 = right val- CONS (k1, d1, bal1, left1, right1) = p1 in case+ bal1 of | bal_zero () => (* A single RR rotation. *) let val q = CONS (k, d, bal_plus1, left, left1) val q1 = CONS (k1, d1, bal_minus1, q, right1) in (q1, F) end | bal_plus1 () => (* A single RR rotation. *) let val q = CONS (k, d, bal_zero, left, left1) val q1 = CONS (k1, d1, bal_zero, q, right1) in (q1, T) end | bal_minus1 () => (* A double RL rotation. *) let val p2 = left1 val- CONS (k2, d2, bal2, left2, right2) = p2 val q = CONS (k, d, minus_pos_bal bal2, left, left2) val q1 = CONS (k1, d1, minus_neg_bal bal2, right2, right1) val q2 = CONS (k2, d2, bal_zero, q, q1) in (q2, T) end end end   fn {key_t  : t@ype} {data_t : t@ype} balance_for_shrunken_right {size : pos} (p  : avl_t (key_t, data_t, size)) :<> (* Returns a new avl_t, and a ‘fixbal’ flag. *) [sz : pos] (avl_t (key_t, data_t, sz), fixbal_t) = let val+ CONS (k, d, bal, left, right) = p in case+ bal of | bal_plus1 () => (CONS (k, d, bal_zero, left, right), T) | bal_zero () => (CONS (k, d, bal_minus1, left, right), F) | bal_minus1 () => (* Rebalance. *) let val p1 = left val- CONS (k1, d1, bal1, left1, right1) = p1 in case+ bal1 of | bal_zero () => (* A single LL rotation. *) let val q = CONS (k, d, bal_minus1, right1, right) val q1 = CONS (k1, d1, bal_plus1, left1, q) in (q1, F) end | bal_minus1 () => (* A single LL rotation. *) let val q = CONS (k, d, bal_zero, right1, right) val q1 = CONS (k1, d1, bal_zero, left1, q) in (q1, T) end | bal_plus1 () => (* A double LR rotation. *) let val p2 = right1 val- CONS (k2, d2, bal2, left2, right2) = p2 val q = CONS (k, d, minus_neg_bal bal2, right2, right) val q1 = CONS (k1, d1, minus_pos_bal bal2, left1, left2) val q2 = CONS (k2, d2, bal_zero, q1, q) in (q2, T) end end end   implement {key_t} {data_t} avl_t_delete (avl, key) = (avl_t_delete_if_found (avl, key)).0   implement {key_t} {data_t} avl_t_delete_if_found (avl, key) = let fn balance_L__ {size : pos} (p  : avl_t (key_t, data_t, size)) :<> [sz : pos] (avl_t (key_t, data_t, sz), fixbal_t) = balance_for_shrunken_left<key_t><data_t> p fn balance_R__ {size : pos} (p  : avl_t (key_t, data_t, size)) :<> [sz : pos] (avl_t (key_t, data_t, sz), fixbal_t) = balance_for_shrunken_right<key_t><data_t> p   fn {} balance_L {size  : pos} (p  : avl_t (key_t, data_t, size), fixbal : fixbal_t) :<> [sz : pos] (avl_t (key_t, data_t, sz), fixbal_t) = if fixbal then balance_L__ p else (p, F)   fn {} balance_R {size  : pos} (p  : avl_t (key_t, data_t, size), fixbal : fixbal_t) :<> [sz : pos] (avl_t (key_t, data_t, sz), fixbal_t) = if fixbal then balance_R__ p else (p, F)   fun del {size  : pos} (r  : avl_t (key_t, data_t, size), fixbal : fixbal_t) :<!ntm> (* Returns a new avl_t, a new fixbal, and key and data to be ‘moved up the tree’. *) [sz : nat] (avl_t (key_t, data_t, sz), fixbal_t, key_t, data_t) = case+ r of | CONS (k, d, bal, left, right) => begin case+ right of | CONS _ => let val (q, fixbalq, kq, dq) = del (right, fixbal) val q1 = CONS (k, d, bal, left, q) val (q1bal, fixbal) = balance_R (q1, fixbalq) in (q1bal, fixbal, kq, dq) end | NIL => (left, T, k, d) end   fun search {size  : nat} (p  : avl_t (key_t, data_t, size), fixbal : fixbal_t) :<!ntm> (* Return three values: a new avl_t, a new fixbal, and whether the key was found. *) [sz : nat] (avl_t (key_t, data_t, sz), fixbal_t, bool) = case+ p of | NIL => (p, F, F) | CONS (k, d, bal, left, right) => case+ avl_t$compare<key_t> (key, k) of | cmp when cmp < 0 => (* Recursive search down the left branch. *) let val (q, fixbal, found) = search (left, fixbal) val (q1, fixbal) = balance_L (CONS (k, d, bal, q, right), fixbal) in (q1, fixbal, found) end | cmp when cmp > 0 => (* Recursive search down the right branch. *) let val (q, fixbal, found) = search (right, fixbal) val (q1, fixbal) = balance_R (CONS (k, d, bal, left, q), fixbal) in (q1, fixbal, found) end | _ => if avl_t_is_empty right then (* Delete p, replace it with its left branch, then rebalance. *) (left, T, T) else if avl_t_is_empty left then (* Delete p, replace it with its right branch, then rebalance. *) (right, T, T) else (* Delete p, but it has both left and right branches, and therefore may have complicated branch structure. *) let val (q, fixbal, k1, d1) = del (left, fixbal) val (q1, fixbal) = balance_L (CONS (k1, d1, bal, q, right), fixbal) in (q1, fixbal, T) end in if avl_t_is_empty avl then (avl, F) else let prval _ = lemma_avl_t_param avl val (avl1, _, found) = $effmask_ntm search (avl, F) in (avl1, found) end end   implement {key_t} {data_t} avl_t_pairs (avl) = let fun traverse {size : pos} {n  : nat} (p  : avl_t (key_t, data_t, size), lst  : list ((key_t, data_t), n)) :<!ntm> [sz : pos] list ((key_t, data_t), sz) = (* Reverse in-order traversal, to make an in-order list by consing. *) case+ p of | CONS (k, d, _, left, right) => if avl_t_is_empty left then begin if avl_t_is_empty right then (k, d) :: lst else (k, d) :: traverse (right, lst) end else begin if avl_t_is_empty right then traverse (left, (k, d) :: lst) else traverse (left, (k, d) :: traverse (right, lst)) end in case+ avl of | NIL => LNIL | CONS _ => $effmask_ntm traverse (avl, LNIL) end     implement {key_t} {data_t} avl_t_keys (avl) = let fun traverse {size : pos} {n  : nat} (p  : avl_t (key_t, data_t, size), lst  : list (key_t, n)) :<!ntm> [sz : pos] list (key_t, sz) = (* Reverse in-order traversal, to make an in-order list by consing. *) case+ p of | CONS (k, _, _, left, right) => if avl_t_is_empty left then begin if avl_t_is_empty right then k :: lst else k :: traverse (right, lst) end else begin if avl_t_is_empty right then traverse (left, k :: lst) else traverse (left, k :: traverse (right, lst)) end in case+ avl of | NIL => LNIL | CONS _ => $effmask_ntm traverse (avl, LNIL) end   implement {key_t} {data_t} avl_t_data (avl) = let fun traverse {size : pos} {n  : nat} (p  : avl_t (key_t, data_t, size), lst  : list (data_t, n)) :<!ntm> [sz : pos] list (data_t, sz) = (* Reverse in-order traversal, to make an in-order list by consing. *) case+ p of | CONS (_, d, _, left, right) => if avl_t_is_empty left then begin if avl_t_is_empty right then d :: lst else d :: traverse (right, lst) end else begin if avl_t_is_empty right then traverse (left, d :: lst) else traverse (left, d :: traverse (right, lst)) end in case+ avl of | NIL => LNIL | CONS _ => $effmask_ntm traverse (avl, LNIL) end   implement {key_t} {data_t} list2avl_t lst = let fun traverse {n  : pos} {size : nat} .<n>. (lst  : list ((key_t, data_t), n), p  : avl_t (key_t, data_t, size)) :<> [sz : pos] avl_t (key_t, data_t, sz) = case+ lst of | (k, d) :: LNIL => avl_t_insert<key_t><data_t> (p, k, d) | (k, d) :: (_ :: _) => let val+ _ :: tail = lst in traverse (tail, avl_t_insert<key_t><data_t> (p, k, d)) end in case+ lst of | LNIL => NIL | (_ :: _) => traverse (lst, NIL) end   fun {key_t  : t@ype} {data_t : t@ype} push_all_the_way_left (stack : List (avl_t (key_t, data_t)), p  : avl_t (key_t, data_t)) : List0 (avl_t (key_t, data_t)) = let prval _ = lemma_list_param stack in case+ p of | NIL => stack | CONS (_, _, _, left, _) => push_all_the_way_left (p :: stack, left) end   fun {key_t  : t@ype} {data_t : t@ype} push_all_the_way_right (stack : List (avl_t (key_t, data_t)), p  : avl_t (key_t, data_t)) : List0 (avl_t (key_t, data_t)) = let prval _ = lemma_list_param stack in case+ p of | NIL => stack | CONS (_, _, _, _, right) => push_all_the_way_right (p :: stack, right) end   fun {key_t  : t@ype} {data_t : t@ype} push_all_the_way (stack  : List (avl_t (key_t, data_t)), p  : avl_t (key_t, data_t), direction : int) : List0 (avl_t (key_t, data_t)) = if direction < 0 then push_all_the_way_right<key_t><data_t> (stack, p) else push_all_the_way_left<key_t><data_t> (stack, p)   fun {key_t  : t@ype} {data_t : t@ype} update_generator_stack (stack  : List (avl_t (key_t, data_t)), left  : avl_t (key_t, data_t), right  : avl_t (key_t, data_t), direction : int) : List0 (avl_t (key_t, data_t)) = let prval _ = lemma_list_param stack in if direction < 0 then begin if avl_t_is_empty left then stack else push_all_the_way_right<key_t><data_t> (stack, left) end else begin if avl_t_is_empty right then stack else push_all_the_way_left<key_t><data_t> (stack, right) end end   implement {key_t} {data_t} avl_t_make_pairs_generator (avl, direction) = let typedef avl_t = avl_t (key_t, data_t)   val stack = push_all_the_way (LNIL, avl, direction) val stack_ref = ref stack   (* Cast stack_ref to its (otherwise untyped) pointer, so it can be enclosed within ‘generate’. *) val p_stack_ref = $UNSAFE.castvwtp0{ptr} stack_ref   fun generate () :<cloref1> Option @(key_t, data_t) = let (* Restore the type information for stack_ref. *) val stack_ref = $UNSAFE.castvwtp0{ref (List avl_t)} p_stack_ref   var stack : List0 avl_t = !stack_ref var retval : Option @(key_t, data_t) in begin case+ stack of | LNIL => retval := None () | p :: tail => let val- CONS (k, d, _, left, right) = p in retval := Some @(k, d); stack := update_generator_stack<key_t><data_t> (tail, left, right, direction) end end;  !stack_ref := stack; retval end in generate end   implement {key_t} {data_t} avl_t_make_keys_generator (avl, direction) = let typedef avl_t = avl_t (key_t, data_t)   val stack = push_all_the_way (LNIL, avl, direction) val stack_ref = ref stack   (* Cast stack_ref to its (otherwise untyped) pointer, so it can be enclosed within ‘generate’. *) val p_stack_ref = $UNSAFE.castvwtp0{ptr} stack_ref   fun generate () :<cloref1> Option key_t = let (* Restore the type information for stack_ref. *) val stack_ref = $UNSAFE.castvwtp0{ref (List avl_t)} p_stack_ref   var stack : List0 avl_t = !stack_ref var retval : Option key_t in begin case+ stack of | LNIL => retval := None () | p :: tail => let val- CONS (k, _, _, left, right) = p in retval := Some k; stack := update_generator_stack<key_t><data_t> (tail, left, right, direction) end end;  !stack_ref := stack; retval end in generate end   implement {key_t} {data_t} avl_t_make_data_generator (avl, direction) = let typedef avl_t = avl_t (key_t, data_t)   val stack = push_all_the_way (LNIL, avl, direction) val stack_ref = ref stack   (* Cast stack_ref to its (otherwise untyped) pointer, so it can be enclosed within ‘generate’. *) val p_stack_ref = $UNSAFE.castvwtp0{ptr} stack_ref   fun generate () :<cloref1> Option data_t = let (* Restore the type information for stack_ref. *) val stack_ref = $UNSAFE.castvwtp0{ref (List avl_t)} p_stack_ref   var stack : List0 avl_t = !stack_ref var retval : Option data_t in begin case+ stack of | LNIL => retval := None () | p :: tail => let val- CONS (_, d, _, left, right) = p in retval := Some d; stack := update_generator_stack<key_t><data_t> (tail, left, right, direction) end end;  !stack_ref := stack; retval end in generate end   implement {key_t} {data_t} avl_t_check_avl_condition (avl) = (* If any of the assertions here is triggered, there is a bug. *) let fun get_heights (p : avl_t (key_t, data_t)) : (int, int) = case+ p of | NIL => (0, 0) | CONS (k, d, bal, left, right) => let val (height_LL, height_LR) = get_heights left val (height_RL, height_RR) = get_heights right in assertloc (abs (height_LL - height_LR) <= 1); assertloc (abs (height_RL - height_RR) <= 1); (height_LL + height_LR, height_RL + height_RR) end in if avl_t_isnot_empty avl then let val (height_L, height_R) = get_heights avl in assertloc (abs (height_L - height_R) <= 1) end end   implement {key_t} {data_t} avl_t_pretty_print (avl) = let fun pad {depth : nat} .<depth>. (depth : int depth) : void = if depth <> 0 then begin print! (" "); pad (pred depth) end   fun traverse {size  : nat} {depth : nat} (p  : avl_t (key_t, data_t, size), depth : int depth) : void = if avl_t_isnot_empty p then let val+ CONS (k, d, bal, left, right) = p in traverse (left, succ depth); pad depth; avl_t_pretty_print$key_and_data<key_t><data_t> (k, d); println! ("\t\tdepth = ", depth, " bal = ", bal2int bal); traverse (right, succ depth) end in if avl_t_isnot_empty avl then let val+ CONS (k, d, bal, left, right) = avl in traverse (left, 1); avl_t_pretty_print$key_and_data<key_t><data_t> (k, d); println! ("\t\tdepth = 0 bal = ", bal2int bal); traverse (right, 1) end end   (*------------------------------------------------------------------*)   (*   Here is a little demonstration program.   Assuming you are using Boehm GC, compile this source file with   patscc -O2 -DATS_MEMALLOC_GCBDW avl_trees-postiats.dats -lgc   and run it with   ./a.out   *)   %{^ #include <time.h>   ATSinline() atstype_uint64 get_the_time (void) { return (atstype_uint64) time (NULL); } %}   (* An implementation of avl_t$compare for keys of type ‘int’. *) implement avl_t$compare<int> (u, v) = if u < v then ~1 else if u > v then 1 else 0   (* An implementation of avl_t_pretty_print$key_and_data for keys of type ‘int’ and values of type ‘double’. *) implement avl_t_pretty_print$key_and_data<int><double> (key, data) = print! ("(", key, ", ", data, ")")   implement main0 () = let (* A linear congruential random number generator attributed to Donald Knuth. *) fn next_random (seed : &uint64) : uint64 = let val a : uint64 = $UNSAFE.cast 6364136223846793005ULL val c : uint64 = $UNSAFE.cast 1442695040888963407ULL val retval = seed in seed := (a * seed) + c; retval end   fn {t : t@ype} fisher_yates_shuffle {n  : nat} (a  : &(@[t][n]), n  : size_t n, seed : &uint64) : void = let var i : [i : nat | i <= n] size_t i in for (i := i2sz 0; i < n; i := succ i) let val randnum = $UNSAFE.cast{Size_t} (next_random seed) val j = randnum mod n (* This is good enough for us. *) val xi = a[i] val xj = a[j] in a[i] := xj; a[j] := xi end end   var seed : uint64 = $extfcall (uint64, "get_the_time")   #define N 20 var keys : @[int][N] = @[int][N] (0)   var a : avl_t (int, double) var a_saved : avl_t (int, double) var a1 : (avl_t (int, double), bool)   var i : [i : nat] int i   val dflt = ~99999999.0 val not_dflt = 123456789.0 in println! ("----------------------------------------------------"); print! ("\n");   (* Initialize a shuffled array of keys. *) for (i := 0; i < N; i := succ i) keys[i] := succ i; fisher_yates_shuffle<int> {N} (keys, i2sz N, seed);   print! ("The keys\n "); for (i := 0; i < N; i := succ i) print! (" ", keys[i]); print! ("\n");   print! ("\nRunning some tests... ");   (* Insert key-data pairs in the shuffled order, checking aspects of the implementation while doing so. *) a := avl_t_nil (); for (i := 0; i < N; i := succ i) let var j : [j : nat] int j in a := avl_t_insert<int> (a, keys[i], g0i2f keys[i]); avl_t_check_avl_condition (a); assertloc (avl_t_size a = succ i); assertloc (avl_t_is_empty a = iseqz (avl_t_size a)); assertloc (avl_t_isnot_empty a = isneqz (avl_t_size a)); a := avl_t_insert<int> (a, keys[i], not_dflt); avl_t_check_avl_condition (a); assertloc (avl_t_search<int><double> (a, keys[i], dflt) = not_dflt); assertloc (avl_t_size a = succ i); assertloc (avl_t_is_empty a = iseqz (avl_t_size a)); assertloc (avl_t_isnot_empty a = isneqz (avl_t_size a)); a := avl_t_insert<int> (a, keys[i], g0i2f keys[i]); avl_t_check_avl_condition (a); assertloc (avl_t_size a = succ i); assertloc (avl_t_is_empty a = iseqz (avl_t_size a)); assertloc (avl_t_isnot_empty a = isneqz (avl_t_size a)); for (j := 0; j < N; j := succ j) let val k = keys[j] val has_key = avl_t_has_key<int> (a, k) val data_opt = avl_t_search<int><double> (a, k) val data_dflt = avl_t_search<int><double> (a, k, dflt) in assertloc (has_key = (j <= i)); assertloc (option_is_some data_opt = (j <= i)); if (j <= i) then let val- Some data = data_opt in assertloc (data = g0i2f k); assertloc (data_dflt = g0i2f k); end else let val- None () = data_opt in assertloc (data_dflt = dflt); end end end;   (* Do it again, but using avl_t_insert_or_replace and checking its second return value. *) a1 := (avl_t_nil (), false); for (i := 0; i < N; i := succ i) let var j : [j : nat] int j in a1 := avl_t_insert_or_replace<int> (a1.0, keys[i], g0i2f keys[i]); avl_t_check_avl_condition (a1.0); assertloc (~(a1.1)); assertloc (avl_t_size (a1.0) = succ i); assertloc (avl_t_is_empty a1.0 = iseqz (avl_t_size a1.0)); assertloc (avl_t_isnot_empty a1.0 = isneqz (avl_t_size a1.0)); a1 := avl_t_insert_or_replace<int> (a1.0, keys[i], not_dflt); avl_t_check_avl_condition (a1.0); assertloc (avl_t_search<int><double> (a1.0, keys[i], dflt) = not_dflt); assertloc (avl_t_size (a1.0) = succ i); assertloc (avl_t_is_empty a1.0 = iseqz (avl_t_size a1.0)); assertloc (avl_t_isnot_empty a1.0 = isneqz (avl_t_size a1.0)); a1 := avl_t_insert_or_replace<int> (a1.0, keys[i], g0i2f keys[i]); avl_t_check_avl_condition (a1.0); assertloc (a1.1); assertloc (avl_t_size (a1.0) = succ i); assertloc (avl_t_is_empty a1.0 = iseqz (avl_t_size a1.0)); assertloc (avl_t_isnot_empty a1.0 = isneqz (avl_t_size a1.0)); for (j := 0; j < N; j := succ j) let val k = keys[j] val has_key = avl_t_has_key<int> (a1.0, k) val data_opt = avl_t_search<int><double> (a1.0, k) val data_dflt = avl_t_search<int><double> (a1.0, k, dflt) in assertloc (has_key = (j <= i)); assertloc (option_is_some data_opt = (j <= i)); if (j <= i) then let val- Some data = data_opt in assertloc (data = g0i2f k); assertloc (data_dflt = g0i2f k); end else let val- None () = data_opt in assertloc (data_dflt = dflt); end end end; a := a1.0;   (* The trees are PERSISTENT, so SAVE THE CURRENT VALUE! *) a_saved := a;   (* Reshuffle the keys, and test deletion, using the reshuffled keys. *) fisher_yates_shuffle<int> {N} (keys, i2sz N, seed); for (i := 0; i < N; i := succ i) let val ix = keys[i] var j : [j : nat] int j in a := avl_t_delete<int> (a, ix); avl_t_check_avl_condition (a); assertloc (avl_t_size a = N - succ i); assertloc (avl_t_is_empty a = iseqz (avl_t_size a)); assertloc (avl_t_isnot_empty a = isneqz (avl_t_size a)); a := avl_t_delete<int> (a, ix); avl_t_check_avl_condition (a); assertloc (avl_t_size a = N - succ i); assertloc (avl_t_is_empty a = iseqz (avl_t_size a)); assertloc (avl_t_isnot_empty a = isneqz (avl_t_size a)); for (j := 0; j < N; j := succ j) let val k = keys[j] val has_key = avl_t_has_key<int> (a, k) val data_opt = avl_t_search<int><double> (a, k) val data_dflt = avl_t_search<int><double> (a, k, dflt) in assertloc (has_key = (i < j)); assertloc (option_is_some data_opt = (i < j)); if (i < j) then let val- Some data = data_opt in assertloc (data = g0i2f k); assertloc (data_dflt = g0i2f k); end else let val- None () = data_opt in assertloc (data_dflt = dflt); end end end;   (* Get back the PERSISTENT VALUE from before the deletions. *) a := a_saved;   (* Reshuffle the keys, and test deletion again, this time using avl_t_delete_if_found. *) fisher_yates_shuffle<int> {N} (keys, i2sz N, seed); for (i := 0; i < N; i := succ i) let val ix = keys[i] var j : [j : nat] int j in a1 := avl_t_delete_if_found<int> (a, ix); a := a1.0; avl_t_check_avl_condition (a); assertloc (a1.1); assertloc (avl_t_size a = N - succ i); assertloc (avl_t_is_empty a = iseqz (avl_t_size a)); assertloc (avl_t_isnot_empty a = isneqz (avl_t_size a)); a1 := avl_t_delete_if_found<int> (a, ix); a := a1.0; avl_t_check_avl_condition (a); assertloc (~(a1.1)); assertloc (avl_t_size a = N - succ i); assertloc (avl_t_is_empty a = iseqz (avl_t_size a)); assertloc (avl_t_isnot_empty a = isneqz (avl_t_size a)); for (j := 0; j < N; j := succ j) let val k = keys[j] val has_key = avl_t_has_key<int> (a, k) val data_opt = avl_t_search<int><double> (a, k) val data_dflt = avl_t_search<int><double> (a, k, dflt) in assertloc (has_key = (i < j)); assertloc (option_is_some data_opt = (i < j)); if (i < j) then let val- Some data = data_opt in assertloc (data = g0i2f k); assertloc (data_dflt = g0i2f k); end else let val- None () = data_opt in assertloc (data_dflt = dflt); end end end;   print! ("passed\n");   (* Get back the PERSISTENT VALUE from before the deletions. *) a := a_saved;   print! ("\n"); println! ("----------------------------------------------------"); print! ("\n"); print! ("*** PRETTY-PRINTING OF THE TREE ***\n\n");   avl_t_pretty_print<int><double> a;   print! ("\n"); println! ("----------------------------------------------------"); print! ("\n"); print! ("*** GENERATORS ***\n\n");   let val gen = avl_t_make_pairs_generator (a, 1) var x : Option @(int, double) in print! ("Association pairs in order\n "); for (x := gen (); option_is_some (x); x := gen ()) let val @(k, d) = option_unsome x in print! (" (", k : int, ", ", d : double, ")") end end;   print! ("\n\n");   let val gen = avl_t_make_pairs_generator (a, ~1) var x : Option @(int, double) in print! ("Association pairs in reverse order\n "); for (x := gen (); option_is_some (x); x := gen ()) let val @(k, d) = option_unsome x in print! (" (", k : int, ", ", d : double, ")") end end;   print! ("\n\n");   let val gen = avl_t_make_keys_generator (a, 1) var x : Option int in print! ("Keys in order\n "); for (x := gen (); option_is_some (x); x := gen ()) print! (" ", (option_unsome x) : int) end;   print! ("\n\n");   let val gen = avl_t_make_keys_generator (a, ~1) var x : Option int in print! ("Keys in reverse order\n "); for (x := gen (); option_is_some (x); x := gen ()) print! (" ", (option_unsome x) : int) end;   print! ("\n\n");   let val gen = avl_t_make_data_generator (a, 1) var x : Option double in print! ("Data values in order of their keys\n "); for (x := gen (); option_is_some (x); x := gen ()) print! (" ", (option_unsome x) : double) end;   print! ("\n\n");   let val gen = avl_t_make_data_generator (a, ~1) var x : Option double in print! ("Data values in reverse order of their keys\n "); for (x := gen (); option_is_some (x); x := gen ()) print! (" ", (option_unsome x) : double) end;   print! ("\n");   print! ("\n"); println! ("----------------------------------------------------"); print! ("\n"); print! ("*** AVL TREES TO LISTS ***\n\n");   print! ("Association pairs in order\n "); print! (avl_t_pairs<int><double> a);   print! ("\n\n");   print! ("Keys in order\n "); print! (avl_t_keys<int> a); print! ("\n\n");   print! ("Data values in order of their keys\n "); print! (avl_t_data<int><double> a); print! ("\n");   print! ("\n"); println! ("----------------------------------------------------"); print! ("\n"); print! ("*** LISTS TO AVL TREES ***\n\n");   let val lst = (3, 3.0) :: (1, 1.0) :: (4, 4.0) :: (2, 2.0) :: LNIL val avl = list2avl_t<int><double> lst in print! (lst : List @(int, double)); print! ("\n\n =>\n\n"); avl_t_pretty_print<int><double> avl end;   print! ("\n"); println! ("----------------------------------------------------") end   (*------------------------------------------------------------------*)
http://rosettacode.org/wiki/Averages/Mean_angle
Averages/Mean angle
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the second was of 10 degrees then the average of the numbers is 180 degrees, whereas if you can note that 350 degrees is equivalent to -10 degrees and so you have two readings at 10 degrees either side of zero degrees leading to a more fitting mean angle of zero degrees. To calculate the mean angle of several angles: Assume all angles are on the unit circle and convert them to complex numbers expressed in real and imaginary form. Compute the mean of the complex numbers. Convert the complex mean to polar coordinates whereupon the phase of the complex mean is the required angular mean. (Note that, since the mean is the sum divided by the number of numbers, and division by a positive real number does not affect the angle, you can also simply compute the sum for step 2.) You can alternatively use this formula: Given the angles α 1 , … , α n {\displaystyle \alpha _{1},\dots ,\alpha _{n}} the mean is computed by α ¯ = atan2 ⁡ ( 1 n ⋅ ∑ j = 1 n sin ⁡ α j , 1 n ⋅ ∑ j = 1 n cos ⁡ α j ) {\displaystyle {\bar {\alpha }}=\operatorname {atan2} \left({\frac {1}{n}}\cdot \sum _{j=1}^{n}\sin \alpha _{j},{\frac {1}{n}}\cdot \sum _{j=1}^{n}\cos \alpha _{j}\right)} Task[edit] write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle. (You should use a built-in function if you have one that does this for degrees or radians). Use the function to compute the means of these lists of angles (in degrees):   [350, 10]   [90, 180, 270, 360]   [10, 20, 30] Show your output here. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#AWK
AWK
#!/usr/bin/awk -f { PI = atan2(0,-1); x=0.0; y=0.0; for (i=1; i<=NF; i++) { p = $i*PI/180.0; x += sin(p); y += cos(p); } p = atan2(x,y)*180.0/PI; if (p<0) p += 360; print p; }
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
#BBC_BASIC
BBC BASIC
*FLOAT 64 DIM angles(3) angles() = 350,10 PRINT FNmeanangle(angles(), 2) angles() = 90,180,270,360 PRINT FNmeanangle(angles(), 4) angles() = 10,20,30 PRINT FNmeanangle(angles(), 3) END   DEF FNmeanangle(angles(), N%) LOCAL I%, sumsin, sumcos FOR I% = 0 TO N%-1 sumsin += SINRADangles(I%) sumcos += COSRADangles(I%) NEXT = DEGFNatan2(sumsin, sumcos)   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/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
#AntLang
AntLang
median[list]
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
#APL
APL
median←{v←⍵[⍋⍵]⋄.5×v[⌈¯1+.5×⍴v]+v[⌊.5×⍴v]} ⍝ Assumes ⎕IO←0
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
#Erlang
Erlang
%% Author: Abhay Jain <[email protected]>   -module(mean_calculator). -export([find_mean/0]).   find_mean() -> %% This is function calling. First argument is the the beginning number %% and second argument is the initial value of sum for AM & HM and initial value of product for GM. arithmetic_mean(1, 0), geometric_mean(1, 1), harmonic_mean(1, 0).   %% Function to calculate Arithmetic Mean arithmetic_mean(Number, Sum) when Number > 10 -> AM = Sum / 10, io:format("Arithmetic Mean ~p~n", [AM]); arithmetic_mean(Number, Sum) -> NewSum = Sum + Number, arithmetic_mean(Number+1, NewSum).   %% Function to calculate Geometric Mean geometric_mean(Number, Product) when Number > 10 -> GM = math:pow(Product, 0.1), io:format("Geometric Mean ~p~n", [GM]); geometric_mean(Number, Product) -> NewProd = Product * Number, geometric_mean(Number+1, NewProd).   %% Function to calculate Harmonic Mean harmonic_mean(Number, Sum) when Number > 10 -> HM = 10 / Sum, io:format("Harmonic Mean ~p~n", [HM]); harmonic_mean(Number, Sum) -> NewSum = Sum + (1/Number), harmonic_mean(Number+1, NewSum).
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.
#Elixir
Elixir
defmodule Ternary do def to_string(t), do: ( for x <- t, do: to_char(x) ) |> List.to_string   def from_string(s), do: ( for x <- to_char_list(s), do: from_char(x) )   defp to_char(-1), do: ?- defp to_char(0), do: ?0 defp to_char(1), do: ?+   defp from_char(?-), do: -1 defp from_char(?0), do: 0 defp from_char(?+), do: 1   def to_ternary(n) when n > 0, do: to_ternary(n,[]) def to_ternary(n), do: neg(to_ternary(-n))   defp to_ternary(0,acc), do: acc defp to_ternary(n,acc) when rem(n, 3) == 0, do: to_ternary(div(n, 3), [0|acc]) defp to_ternary(n,acc) when rem(n, 3) == 1, do: to_ternary(div(n, 3), [1|acc]) defp to_ternary(n,acc), do: to_ternary(div((n+1), 3), [-1|acc])   def from_ternary(t), do: from_ternary(t,0)   defp from_ternary([],acc), do: acc defp from_ternary([h|t],acc), do: from_ternary(t, acc*3 + h)   def mul(a,b), do: mul(b,a,[])   defp mul(_,[],acc), do: acc defp mul(b,[a|as],acc) do bp = case a do -1 -> neg(b) 0 -> [0] 1 -> b end a = add(bp, acc ++ [0]) mul(b,as,a) end   defp neg(t), do: ( for h <- t, do: -h )   def sub(a,b), do: add(a,neg(b))   def add(a,b) when length(a) < length(b), do: add(List.duplicate(0, length(b)-length(a)) ++ a, b) def add(a,b) when length(a) > length(b), do: add(b,a) def add(a,b), do: add(Enum.reverse(a), Enum.reverse(b), 0, [])   defp add([],[],0,acc), do: acc defp add([],[],c,acc), do: [c|acc] defp add([a|as],[b|bs],c,acc) do [c1,d] = add_util(a+b+c) add(as,bs,c1,[d|acc]) end   defp add_util(-3), do: [-1,0] defp add_util(-2), do: [-1,1] defp add_util(-1), do: [0,-1] defp add_util(3), do: [1,0] defp add_util(2), do: [1,-1] defp add_util(1), do: [0,1] defp add_util(0), do: [0,0] end   as = "+-0++0+"; at = Ternary.from_string(as); a = Ternary.from_ternary(at) b = -436; bt = Ternary.to_ternary(b); bs = Ternary.to_string(bt) cs = "+-++-"; ct = Ternary.from_string(cs); c = Ternary.from_ternary(ct) rt = Ternary.mul(at,Ternary.sub(bt,ct)) r = Ternary.from_ternary(rt) rs = Ternary.to_string(rt) IO.puts "a = #{as} -> #{a}" IO.puts "b = #{bs} -> #{b}" IO.puts "c = #{cs} -> #{c}" IO.puts "a x (b - c) = #{rs} -> #{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.
#MAXScript
MAXScript
-- MAXScript : Babbage problem : N.H. posInt = 1 while posInt < 1000000 do ( if (matchPattern((posInt * posInt) as string) pattern: "*269696") then exit posInt += 1 ) Print "The smallest number whose square ends in 269696 is " + ((posInt) as string) Print "Its square is " + (((pow posInt 2) as integer) as string)  
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
#AutoHotkey
AutoHotkey
; Generate 10 strings with equal left and right brackets Loop, 5 { B = %A_Index% loop 2 { String = Loop % B String .= "[`n" Loop % B String .= "]`n" Sort, String, Random StringReplace, String, String,`n,,All Example .= String " - " IsBalanced(String) "`n" } } MsgBox % Example return   IsBalanced(Str) { Loop, PARSE, Str { If A_LoopField = [ i++ Else if A_LoopField = ] i-- If i < 0 return "NOT OK" } Return "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
#Elena
Elena
import system'routines; import system'collections; import extensions;   extension op { get Mode() { var countMap := Dictionary.new(0); self.forEach:(item) { countMap[item] := countMap[item] + 1 };   countMap := countMap.Values.sort:(p,n => p > n);   var max := countMap.FirstMember;   ^ countMap .filterBy:(kv => max.equal(kv.Value)) .selectBy:(kv => kv.Key) .toArray() } }   public program() { var array1 := new int[]{1, 1, 2, 4, 4}; var array2 := new int[]{1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17}; var array3 := new object[]{1, "blue", 2, 7.5r, 5, "green", "red", 5, 2, "blue", "white"};   console .printLine("mode of (",array1.asEnumerable(),") is (",array1.Mode,")") .printLine("mode of (",array2.asEnumerable(),") is (",array2.Mode,")") .printLine("mode of (",array3.asEnumerable(),") is (",array3.Mode,")") .readChar() }
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
#Elixir
Elixir
defmodule Average do def mode(list) do gb = Enum.group_by(list, &(&1)) max = Enum.map(gb, fn {_,val} -> length(val) end) |> Enum.max for {key,val} <- gb, length(val)==max, do: key end end   lists = [[3,1,4,1,5,9,2,6,5,3,5,8,9], [1, 2, "qwe", "asd", 1, 2, "qwe", "asd", 2, "qwe"]] Enum.each(lists, fn list -> IO.puts "mode: #{inspect list}" IO.puts " => #{inspect Average.mode(list)}" 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
#OxygenBasic
OxygenBasic
def max 1000   Class MovingAverage '==================   indexbase 1 double average,invperiod,mdata[max] sys index,period   method Setup(double a,p) sys i Period=p invPeriod=1/p index=0 average=a for i=1 to period mdata[i]=a next end method   method Data(double v) as double sys i index++ if index>period then index=1 'recycle i=index+1 'for oldest data if i>period then i=1 'recycle mdata[index]=v average=average+invperiod*(v-mdata[i]) end method   end class   'TEST '====   MovingAverage A   A.Setup 100,10 'initial value and period   A.data 50 '... print A.average 'reult 95  
http://rosettacode.org/wiki/Attractive_numbers
Attractive numbers
A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show sequence items up to   120. Reference   The OEIS entry:   A063989: Numbers with a prime number of prime divisors.
#11l
11l
F is_prime(n) I n < 2 R 0B L(i) 2 .. Int(sqrt(n)) I n % i == 0 R 0B R 1B   F get_pfct(=n) V i = 2 [Int] factors L i * i <= n I n % i i++ E n I/= i factors.append(i) I n > 1 factors.append(n) R factors.len   [Int] pool   L(each) 0..120 pool.append(get_pfct(each))   [Int] r L(each) pool I is_prime(each) r.append(L.index)   print(r.map(String).join(‘,’))
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
#D
D
import std.stdio, std.range, std.algorithm, std.complex, std.math, std.format, std.conv;   double radians(in double d) pure nothrow @safe @nogc { return d * PI / 180; }   double degrees(in double r) pure nothrow @safe @nogc { return r * 180 / PI; }   double meanAngle(in double[] deg) pure nothrow @safe @nogc { return (deg.map!(d => fromPolar(1, d.radians)).sum / deg.length).arg.degrees; }   string meanTime(in string[] times) pure @safe { auto t = times.map!(times => times.split(':').to!(int[3])); assert(t.all!(hms => 24.iota.canFind(hms[0]) && 60.iota.canFind(hms[1]) && 60.iota.canFind(hms[2])), "Invalid time");   auto seconds = t.map!(hms => hms[2] + hms[1] * 60 + hms[0] * 3600); enum day = 24 * 60 * 60; const to_angles = seconds.map!(s => s * 360.0 / day).array;   immutable mean_as_angle = to_angles.meanAngle; auto mean_seconds_fp = mean_as_angle * day / 360.0; if (mean_seconds_fp < 0) mean_seconds_fp += day; immutable mean_seconds = mean_seconds_fp.to!uint; immutable h = mean_seconds / 3600; immutable m = mean_seconds % 3600; return "%02d:%02d:%02d".format(h, m / 60, m % 60); }   void main() @safe { ["23:00:17", "23:40:20", "00:12:45", "00:17:19"].meanTime.writeln; }
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.
#C
C
  #include <algorithm> #include <iostream>   /* AVL node */ template <class T> class AVLnode { public: T key; int balance; AVLnode *left, *right, *parent;   AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p), left(NULL), right(NULL) {}   ~AVLnode() { delete left; delete right; } };   /* AVL tree */ template <class T> class AVLtree { public: AVLtree(void); ~AVLtree(void); bool insert(T key); void deleteKey(const T key); void printBalance();   private: AVLnode<T> *root;   AVLnode<T>* rotateLeft ( AVLnode<T> *a ); AVLnode<T>* rotateRight ( AVLnode<T> *a ); AVLnode<T>* rotateLeftThenRight ( AVLnode<T> *n ); AVLnode<T>* rotateRightThenLeft ( AVLnode<T> *n ); void rebalance ( AVLnode<T> *n ); int height ( AVLnode<T> *n ); void setBalance ( AVLnode<T> *n ); void printBalance ( AVLnode<T> *n ); };   /* AVL class definition */ template <class T> void AVLtree<T>::rebalance(AVLnode<T> *n) { setBalance(n);   if (n->balance == -2) { if (height(n->left->left) >= height(n->left->right)) n = rotateRight(n); else n = rotateLeftThenRight(n); } else if (n->balance == 2) { if (height(n->right->right) >= height(n->right->left)) n = rotateLeft(n); else n = rotateRightThenLeft(n); }   if (n->parent != NULL) { rebalance(n->parent); } else { root = n; } }   template <class T> AVLnode<T>* AVLtree<T>::rotateLeft(AVLnode<T> *a) { AVLnode<T> *b = a->right; b->parent = a->parent; a->right = b->left;   if (a->right != NULL) a->right->parent = a;   b->left = a; a->parent = b;   if (b->parent != NULL) { if (b->parent->right == a) { b->parent->right = b; } else { b->parent->left = b; } }   setBalance(a); setBalance(b); return b; }   template <class T> AVLnode<T>* AVLtree<T>::rotateRight(AVLnode<T> *a) { AVLnode<T> *b = a->left; b->parent = a->parent; a->left = b->right;   if (a->left != NULL) a->left->parent = a;   b->right = a; a->parent = b;   if (b->parent != NULL) { if (b->parent->right == a) { b->parent->right = b; } else { b->parent->left = b; } }   setBalance(a); setBalance(b); return b; }   template <class T> AVLnode<T>* AVLtree<T>::rotateLeftThenRight(AVLnode<T> *n) { n->left = rotateLeft(n->left); return rotateRight(n); }   template <class T> AVLnode<T>* AVLtree<T>::rotateRightThenLeft(AVLnode<T> *n) { n->right = rotateRight(n->right); return rotateLeft(n); }   template <class T> int AVLtree<T>::height(AVLnode<T> *n) { if (n == NULL) return -1; return 1 + std::max(height(n->left), height(n->right)); }   template <class T> void AVLtree<T>::setBalance(AVLnode<T> *n) { n->balance = height(n->right) - height(n->left); }   template <class T> void AVLtree<T>::printBalance(AVLnode<T> *n) { if (n != NULL) { printBalance(n->left); std::cout << n->balance << " "; printBalance(n->right); } }   template <class T> AVLtree<T>::AVLtree(void) : root(NULL) {}   template <class T> AVLtree<T>::~AVLtree(void) { delete root; }   template <class T> bool AVLtree<T>::insert(T key) { if (root == NULL) { root = new AVLnode<T>(key, NULL); } else { AVLnode<T> *n = root, *parent;   while (true) { if (n->key == key) return false;   parent = n;   bool goLeft = n->key > key; n = goLeft ? n->left : n->right;   if (n == NULL) { if (goLeft) { parent->left = new AVLnode<T>(key, parent); } else { parent->right = new AVLnode<T>(key, parent); }   rebalance(parent); break; } } }   return true; }   template <class T> void AVLtree<T>::deleteKey(const T delKey) { if (root == NULL) return;   AVLnode<T> *n = root, *parent = root, *delNode = NULL, *child = root;   while (child != NULL) { parent = n; n = child; child = delKey >= n->key ? n->right : n->left; if (delKey == n->key) delNode = n; }   if (delNode != NULL) { delNode->key = n->key;   child = n->left != NULL ? n->left : n->right;   if (root->key == delKey) { root = child; } else { if (parent->left == n) { parent->left = child; } else { parent->right = child; }   rebalance(parent); } } }   template <class T> void AVLtree<T>::printBalance() { printBalance(root); std::cout << std::endl; }   int main(void) { AVLtree<int> t;   std::cout << "Inserting integer values 1 to 10" << std::endl; for (int i = 1; i <= 10; ++i) t.insert(i);   std::cout << "Printing balance: "; t.printBalance(); }  
http://rosettacode.org/wiki/Averages/Mean_angle
Averages/Mean angle
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the second was of 10 degrees then the average of the numbers is 180 degrees, whereas if you can note that 350 degrees is equivalent to -10 degrees and so you have two readings at 10 degrees either side of zero degrees leading to a more fitting mean angle of zero degrees. To calculate the mean angle of several angles: Assume all angles are on the unit circle and convert them to complex numbers expressed in real and imaginary form. Compute the mean of the complex numbers. Convert the complex mean to polar coordinates whereupon the phase of the complex mean is the required angular mean. (Note that, since the mean is the sum divided by the number of numbers, and division by a positive real number does not affect the angle, you can also simply compute the sum for step 2.) You can alternatively use this formula: Given the angles α 1 , … , α n {\displaystyle \alpha _{1},\dots ,\alpha _{n}} the mean is computed by α ¯ = atan2 ⁡ ( 1 n ⋅ ∑ j = 1 n sin ⁡ α j , 1 n ⋅ ∑ j = 1 n cos ⁡ α j ) {\displaystyle {\bar {\alpha }}=\operatorname {atan2} \left({\frac {1}{n}}\cdot \sum _{j=1}^{n}\sin \alpha _{j},{\frac {1}{n}}\cdot \sum _{j=1}^{n}\cos \alpha _{j}\right)} Task[edit] write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle. (You should use a built-in function if you have one that does this for degrees or radians). Use the function to compute the means of these lists of angles (in degrees):   [350, 10]   [90, 180, 270, 360]   [10, 20, 30] Show your output here. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#C
C
#include<math.h> #include<stdio.h>   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 () { double angleSet1[] = { 350, 10 }; double angleSet2[] = { 90, 180, 270, 360}; double angleSet3[] = { 10, 20, 30};   printf ("\nMean Angle for 1st set : %lf degrees", meanAngle (angleSet1, 2)); printf ("\nMean Angle for 2nd set : %lf degrees", meanAngle (angleSet2, 4)); printf ("\nMean Angle for 3rd set : %lf degrees\n", meanAngle (angleSet3, 3)); return 0; }
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
#AppleScript
AppleScript
set alist to {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0} set med to medi(alist)   on medi(alist)   set temp to {} set lcount to count alist if lcount is equal to 2 then return ((item 1 of alist) + (item 2 of alist)) / 2 else if lcount is less than 2 then return item 1 of alist else --if lcount is greater than 2 set min to findmin(alist) set max to findmax(alist) repeat with x from 1 to lcount if x is not equal to min and x is not equal to max then set end of temp to item x of alist end repeat set med to medi(temp) end if return med   end medi   on findmin(alist)   set min to 1 set alength to count every item of alist repeat with x from 1 to alength if item x of alist is less than item min of alist then set min to x end repeat return min   end findmin   on findmax(alist)   set max to 1 set alength to count every item of alist repeat with x from 1 to alength if item x of alist is greater than item max of alist then set max to x end repeat return max   end findmax
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
#ERRE
ERRE
  PROGRAM MEANS   DIM A[9]   PROCEDURE ARITHMETIC_MEAN(A[]->M) LOCAL S,I% NEL%=UBOUND(A,1) S=0 FOR I%=0 TO NEL% DO S+=A[I%] END FOR M=S/(NEL%+1) END PROCEDURE   PROCEDURE GEOMETRIC_MEAN(A[]->M) LOCAL S,I% NEL%=UBOUND(A,1) S=1 FOR I%=0 TO NEL% DO S*=A[I%] END FOR M=S^(1/(NEL%+1)) END PROCEDURE   PROCEDURE HARMONIC_MEAN(A[]->M) LOCAL S,I% NEL%=UBOUND(A,1) S=0 FOR I%=0 TO NEL% DO S+=1/A[I%] END FOR M=(NEL%+1)/S END PROCEDURE   BEGIN A[]=(1,2,3,4,5,6,7,8,9,10) ARITHMETIC_MEAN(A[]->M) PRINT("Arithmetic mean = ";M) GEOMETRIC_MEAN(A[]->M) PRINT("Geometric mean = ";M) HARMONIC_MEAN(A[]->M) PRINT("Harmonic mean = ";M) END PROGRAM  
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.
#Erlang
Erlang
  -module(ternary). -compile(export_all).   test() -> AS = "+-0++0+", AT = from_string(AS), A = from_ternary(AT), B = -436, BT = to_ternary(B), BS = to_string(BT), CS = "+-++-", CT = from_string(CS), C = from_ternary(CT), RT = mul(AT,sub(BT,CT)), R = from_ternary(RT), RS = to_string(RT), io:fwrite("A = ~s -> ~b~n",[AS, A]), io:fwrite("B = ~s -> ~b~n",[BS, B]), io:fwrite("C = ~s -> ~b~n",[CS, C]), io:fwrite("A x (B - C) = ~s -> ~b~n", [RS, R]).   to_string(T) -> [to_char(X) || X <- T].   from_string(S) -> [from_char(X) || X <- S].   to_char(-1) -> $-; to_char(0) -> $0; to_char(1) -> $+.   from_char($-) -> -1; from_char($0) -> 0; from_char($+) -> 1.   to_ternary(N) when N > 0 -> to_ternary(N,[]); to_ternary(N) -> neg(to_ternary(-N)).   to_ternary(0,Acc) -> Acc; to_ternary(N,Acc) when N rem 3 == 0 -> to_ternary(N div 3, [0|Acc]); to_ternary(N,Acc) when N rem 3 == 1 -> to_ternary(N div 3, [1|Acc]); to_ternary(N,Acc) -> to_ternary((N+1) div 3, [-1|Acc]).   from_ternary(T) -> from_ternary(T,0).   from_ternary([],Acc) -> Acc; from_ternary([H|T],Acc) -> from_ternary(T,Acc*3 + H).   mul(A,B) -> mul(B,A,[]).   mul(_,[],Acc) -> Acc; mul(B,[A|As],Acc) -> BP = case A of -1 -> neg(B); 0 -> [0]; 1 -> B end, A1 = Acc++[0], A2=add(BP,A1), mul(B,As,A2).     neg(T) -> [ -H || H <- T].   sub(A,B) -> add(A,neg(B)).   add(A,B) when length(A) < length(B) -> add(lists:duplicate(length(B)-length(A),0)++A,B); add(A,B) when length(A) > length(B) -> add(B,A); add(A,B) -> add(lists:reverse(A),lists:reverse(B),0,[]).   add([],[],0,Acc) -> Acc; add([],[],C,Acc) -> [C|Acc]; add([A|As],[B|Bs],C,Acc) -> [C1,D] = add_util(A+B+C), add(As,Bs,C1,[D|Acc]).   add_util(-3) -> [-1,0]; add_util(-2) -> [-1,1]; add_util(-1) -> [0,-1]; add_util(3) -> [1,0]; add_util(2) -> [1,-1]; add_util(1) -> [0,1]; add_util(0) -> [0,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.
#Microsoft_Small_Basic
Microsoft Small Basic
' Babbage problem ' The quote (') means a comment ' The equals sign (=) means assign n = 500 ' 500 is stored in variable n*n ' 500 because 500*500=250000 less than 269696   ' The nitty-gritty is in the 3 lines between "While" and "EndWhile". ' So, we start with 500, n is being incremented by 1 at each round ' while its square (n*n) (* means multiplication) does not have ' a remainder (function Math.Remainder) of 269696 when divided by one million. ' This means that the loop will stop when the smallest positive integer ' whose square ends in 269696 ' is found and stored in n. ' (<>) means "not equal to" While Math.Remainder( n*n , 1000000 ) <> 269696 n = n + 1 EndWhile   ' (TextWindow.WriteLine) displays the string to the monitor ' (+) concatenates strings or variables to be displayed TextWindow.WriteLine("The smallest positive integer whose square ends in 269696 is " + (n) + ".") TextWindow.WriteLine("Its square is " + (n*n) + ".")   ' End of Program.
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
#AutoIt
AutoIt
  #include <Array.au3> Local $Array[1] _ArrayAdd($Array, "[]") _ArrayAdd($Array, "[][]") _ArrayAdd($Array, "[[][]]") _ArrayAdd($Array, "][") _ArrayAdd($Array, "][][") _ArrayAdd($Array, "[]][[]")   For $i = 0 To UBound($Array) -1 Balanced_Brackets($Array[$i]) If @error Then ConsoleWrite($Array[$i] &" = NOT OK"&@CRLF) Else ConsoleWrite($Array[$i] &" = OK"&@CRLF) EndIf Next   Func Balanced_Brackets($String) Local $cnt = 0 $Split = Stringsplit($String, "") For $i = 1 To $Split[0] If $split[$i] = "[" Then $cnt += 1 If $split[$i] = "]" Then $cnt -= 1 If $cnt < 0 Then Return SetError(1,0,0) Next Return 1 EndFunc  
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
#Erlang
Erlang
  -module( mode ). -export( [example/0, values/1] ).   example() -> Set = [1, 2, "qwe", "asd", 1, 2, "qwe", "asd", 2, "qwe"], io:fwrite( "In ~p the mode(s) is(are): ~p~n", [Set, values(Set)] ).   values( Set ) -> Dict = lists:foldl( fun values_count/2, dict:new(), Set ), [X || {X, _Y} <- dict:fold( fun keep_maxs/3, [{0, 0}], Dict )].       keep_maxs( Key, Value, [{_Max_key, Max_value} | _] ) when Value > Max_value -> [{Key, Value}]; keep_maxs( Key, Value, [{_Max_key, Max_value} | _]=Maxs ) when Value =:= Max_value -> [{Key, Value} | Maxs]; keep_maxs( _Key, _Value, Maxs ) -> Maxs.   values_count( Value, Dict ) -> dict:update_counter( Value, 1, Dict ).  
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#0815
0815
  {x{+=<:2:x/%<:d:~$<:01:~><:02:~><:03:~><:04:~><:05:~><:06:~><:07:~><:08: ~><:09:~><:0a:~><:0b:~><:0c:~><:0d:~><:0e:~><:0f:~><:10:~><:11:~><:12:~> <:13:~><:14:~><:15:~><:16:~><:17:~><:18:~><:19:~><:ffffffffffffffff:~>{x {+>}:8f:{&={+>{~>&=x<:ffffffffffffffff:/#:8f:{{=<:19:x/%  
http://rosettacode.org/wiki/Average_loop_length
Average loop length
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence. Task Write a program or a script that estimates, for each N, the average length until the first such repetition. Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one. This problem comes from the end of Donald Knuth's Christmas tree lecture 2011. Example of expected output: N average analytical (error) === ========= ============ ========= 1 1.0000 1.0000 ( 0.00%) 2 1.4992 1.5000 ( 0.05%) 3 1.8784 1.8889 ( 0.56%) 4 2.2316 2.2188 ( 0.58%) 5 2.4982 2.5104 ( 0.49%) 6 2.7897 2.7747 ( 0.54%) 7 3.0153 3.0181 ( 0.09%) 8 3.2429 3.2450 ( 0.07%) 9 3.4536 3.4583 ( 0.14%) 10 3.6649 3.6602 ( 0.13%) 11 3.8091 3.8524 ( 1.12%) 12 3.9986 4.0361 ( 0.93%) 13 4.2074 4.2123 ( 0.12%) 14 4.3711 4.3820 ( 0.25%) 15 4.5275 4.5458 ( 0.40%) 16 4.6755 4.7043 ( 0.61%) 17 4.8877 4.8579 ( 0.61%) 18 4.9951 5.0071 ( 0.24%) 19 5.1312 5.1522 ( 0.41%) 20 5.2699 5.2936 ( 0.45%)
#11l
11l
F ffactorial(n) V result = 1.0 L(i) 2..n result *= i R result   V MAX_N = 20 V TIMES = 1000000   F analytical(n) R sum((1..n).map(i -> ffactorial(@n) / pow(Float(@n), Float(i)) / ffactorial(@n - i)))   F test(n, times) V count = 0 L(i) 0 .< times V (x, bits) = (1, 0) L (bits [&] x) == 0 count++ bits [|]= x x = 1 << random:(n) R Float(count) / times   print(" n avg exp. diff\n-------------------------------") L(n) 1 .. MAX_N V avg = test(n, TIMES) V theory = analytical(n) V diff = (avg / theory - 1) * 100 print(‘#2 #3.4 #3.4 #2.3%’.format(n, avg, theory, diff))
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
#Oz
Oz
declare   fun {CreateSMA Period} Xs = {NewCell nil} in fun {$ X} Xs := {List.take X|@Xs Period}   {FoldL @Xs Number.'+' 0.0} / {Int.toFloat {Min Period {Length @Xs}}} end end   in   for Period in [3 5] do SMA = {CreateSMA Period} in {System.showInfo "\nSTART PERIOD "#Period} for I in 1..5 do {System.showInfo " Number = "#I#" , SMA = "#{SMA {Int.toFloat I}}} end for I in 5..1;~1 do {System.showInfo " Number = "#I#" , SMA = "#{SMA {Int.toFloat I}}} end end
http://rosettacode.org/wiki/Attractive_numbers
Attractive numbers
A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show sequence items up to   120. Reference   The OEIS entry:   A063989: Numbers with a prime number of prime divisors.
#8080_Assembly
8080 Assembly
;;; Show attractive numbers up to 120 MAX: equ 120 ; can be up to 255 (8 bit math is used) ;;; CP/M calls puts: equ 9 bdos: equ 5 org 100h ;;; -- Zero memory ------------------------------------------------ lxi b,fctrs ; page 2 mvi e,2 ; zero out two pages xra a mov d,a zloop: stax b inx b dcr d jnz zloop dcr e jnz zloop ;;; -- Generate primes -------------------------------------------- lxi h,plist ; pointer to beginning of primes list mvi e,2 ; first prime is 2 pstore: mov m,e ; begin prime list pcand: inr e ; next candidate jz factor ; if 0, we've rolled over, so we're done mov l,d ; beginning of primes list (D=0 here) mov c,m ; C = prime to test against ptest: mov a,e ploop: sub c ; test by repeated subtraction jc notdiv ; if carry, not divisible jz pcand ; if zero, next candidate jmp ploop notdiv: inx h ; get next prime mov c,m mov a,c ; is it zero? ora a jnz ptest ; if not, test against next prime jmp pstore ; otherwise, add E to the list of primes ;;; -- Count factors ---------------------------------------------- factor: mvi c,2 ; start with two fnum: mvi a,MAX ; is candidate beyond maximum? cmp c jc output ; then stop mvi d,0 ; D = number of factors of C mov l,d ; L = first prime mov e,c ; E = number we're factorizing fprim: mvi h,ppage ; H = current prime mov h,m ftest: mvi b,0 mov a,e cpi 1 ; If one, we've counted all the factors jz nxtfac fdiv: sub h jz divi jc ndivi inr b jmp fdiv divi: inr d ; we found a factor inr b mov e,b ; we've removed it, try again jmp ftest ndivi: inr l ; not divisible, try next prime jmp fprim nxtfac: mov a,d ; store amount of factors mvi b,fcpage stax b inr c ; do next number jmp fnum ;;; -- Check which numbers are attractive and print them ---------- output: lxi b,fctrs+2 ; start with two mvi h,ppage ; H = page of primes onum: mvi a,MAX ; is candidate beyond maximum? cmp c rc ; then stop ldax b ; get amount of factors mvi l,0 ; start at beginning of prime list chprm: cmp m ; check against current prime jz print ; if it's prime, then print the number inr l ; otherwise, check next prime jp chprm next: inr c ; check next number jmp onum print: push b ; keep registers push h mov a,c ; print number call printa pop h ; restore registers pop b jmp next ;;; Subroutine: print the number in A printa: lxi d,num ; DE = string mvi b,10 ; divisor digit: mvi c,-1 ; C = quotient divlp: inr c sub b jnc divlp adi '0'+10 ; make digit dcx d ; store digit stax d mov a,c ; again with new quotient ora a ; is it zero? jnz digit ; if not, do next digit mvi c,puts ; CP/M print string (in DE) jmp bdos db '000' ; placeholder for number num: db ' $' fcpage: equ 2 ; factors in page 2 ppage: equ 3 ; primes in page 3 fctrs: equ 256*fcpage plist: equ 256*ppage
http://rosettacode.org/wiki/Attractive_numbers
Attractive numbers
A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show sequence items up to   120. Reference   The OEIS entry:   A063989: Numbers with a prime number of prime divisors.
#Action.21
Action!
INCLUDE "H6:SIEVE.ACT"   BYTE FUNC IsAttractive(BYTE n BYTE ARRAY primes) BYTE count,f   IF n<=1 THEN RETURN (0) ELSEIF primes(n) THEN RETURN (0) FI   count=0 f=2 DO IF n MOD f=0 THEN count==+1 n==/f IF n=1 THEN EXIT ELSEIF primes(n) THEN f=n FI ELSEIF f>=3 THEN f==+2 ELSE f=3 FI OD   IF primes(count) THEN RETURN (1) FI RETURN (0)   PROC Main() DEFINE MAX="120" BYTE ARRAY primes(MAX+1) BYTE i   Put(125) PutE() ;clear the screen Sieve(primes,MAX+1) PrintF("Attractive numbers in range 1..%B:%E",MAX) FOR i=1 TO MAX DO IF IsAttractive(i,primes) THEN PrintF("%B ",i) FI OD 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
#Delphi
Delphi
  program Averages_Mean_time_of_day;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Math;   const Inputs: TArray<string> = ['23:00:17', '23:40:20', '00:12:45', '00:17:19'];   function ToTimes(ts: TArray<string>): TArray<TTime>; begin SetLength(result, length(ts)); for var i := 0 to High(ts) do Result[i] := StrToTime(ts[i]); end;   function MeanTime(times: TArray<TTime>): TTime; var ssum, csum: TTime; h, m, s, ms: word; dayFrac, fsec, ssin, ccos: double; begin if Length(times) = 0 then exit(0);   ssum := 0; csum := 0; for var t in times do begin DecodeTime(t, h, m, s, ms); fsec := (h * 60 + m) * 60 + s + ms / 1000; ssin := sin(fsec * Pi / (12 * 60 * 60)); ccos := cos(fsec * Pi / (12 * 60 * 60)); ssum := ssum + ssin; csum := csum + ccos; end; if (ssum = 0) and (csum = 0) then raise Exception.Create('Error MeanTime: Mean undefined');   dayFrac := frac(1 + ArcTan2(ssum, csum) / (2 * Pi)); fsec := dayFrac * 24 * 3600;   ms := Trunc(frac(fsec) * 1000); s := trunc(fsec) mod 60; m := trunc(fsec) div 60 mod 60; h := trunc(fsec) div 3600;   Result := EncodeTime(h, m, s, ms); end;   begin writeln(TimeToStr(MeanTime(ToTimes(Inputs)))); readln; end.
http://rosettacode.org/wiki/AVL_tree
AVL tree
This page uses content from Wikipedia. The original article was at AVL tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In computer science, an AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; at no time do they differ by more than one because rebalancing is done ensure this is the case. Lookup, insertion, and deletion all take O(log n) time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations. Note the tree of nodes comprise a set, so duplicate node keys are not allowed. AVL trees are often compared with red-black trees because they support the same set of operations and because red-black trees also take O(log n) time for the basic operations. Because AVL trees are more rigidly balanced, they are faster than red-black trees for lookup-intensive applications. Similar to red-black trees, AVL trees are height-balanced, but in general not weight-balanced nor μ-balanced; that is, sibling nodes can have hugely differing numbers of descendants. Task Implement an AVL tree in the language of choice, and provide at least basic operations.
#C.23
C#
  #include <algorithm> #include <iostream>   /* AVL node */ template <class T> class AVLnode { public: T key; int balance; AVLnode *left, *right, *parent;   AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p), left(NULL), right(NULL) {}   ~AVLnode() { delete left; delete right; } };   /* AVL tree */ template <class T> class AVLtree { public: AVLtree(void); ~AVLtree(void); bool insert(T key); void deleteKey(const T key); void printBalance();   private: AVLnode<T> *root;   AVLnode<T>* rotateLeft ( AVLnode<T> *a ); AVLnode<T>* rotateRight ( AVLnode<T> *a ); AVLnode<T>* rotateLeftThenRight ( AVLnode<T> *n ); AVLnode<T>* rotateRightThenLeft ( AVLnode<T> *n ); void rebalance ( AVLnode<T> *n ); int height ( AVLnode<T> *n ); void setBalance ( AVLnode<T> *n ); void printBalance ( AVLnode<T> *n ); };   /* AVL class definition */ template <class T> void AVLtree<T>::rebalance(AVLnode<T> *n) { setBalance(n);   if (n->balance == -2) { if (height(n->left->left) >= height(n->left->right)) n = rotateRight(n); else n = rotateLeftThenRight(n); } else if (n->balance == 2) { if (height(n->right->right) >= height(n->right->left)) n = rotateLeft(n); else n = rotateRightThenLeft(n); }   if (n->parent != NULL) { rebalance(n->parent); } else { root = n; } }   template <class T> AVLnode<T>* AVLtree<T>::rotateLeft(AVLnode<T> *a) { AVLnode<T> *b = a->right; b->parent = a->parent; a->right = b->left;   if (a->right != NULL) a->right->parent = a;   b->left = a; a->parent = b;   if (b->parent != NULL) { if (b->parent->right == a) { b->parent->right = b; } else { b->parent->left = b; } }   setBalance(a); setBalance(b); return b; }   template <class T> AVLnode<T>* AVLtree<T>::rotateRight(AVLnode<T> *a) { AVLnode<T> *b = a->left; b->parent = a->parent; a->left = b->right;   if (a->left != NULL) a->left->parent = a;   b->right = a; a->parent = b;   if (b->parent != NULL) { if (b->parent->right == a) { b->parent->right = b; } else { b->parent->left = b; } }   setBalance(a); setBalance(b); return b; }   template <class T> AVLnode<T>* AVLtree<T>::rotateLeftThenRight(AVLnode<T> *n) { n->left = rotateLeft(n->left); return rotateRight(n); }   template <class T> AVLnode<T>* AVLtree<T>::rotateRightThenLeft(AVLnode<T> *n) { n->right = rotateRight(n->right); return rotateLeft(n); }   template <class T> int AVLtree<T>::height(AVLnode<T> *n) { if (n == NULL) return -1; return 1 + std::max(height(n->left), height(n->right)); }   template <class T> void AVLtree<T>::setBalance(AVLnode<T> *n) { n->balance = height(n->right) - height(n->left); }   template <class T> void AVLtree<T>::printBalance(AVLnode<T> *n) { if (n != NULL) { printBalance(n->left); std::cout << n->balance << " "; printBalance(n->right); } }   template <class T> AVLtree<T>::AVLtree(void) : root(NULL) {}   template <class T> AVLtree<T>::~AVLtree(void) { delete root; }   template <class T> bool AVLtree<T>::insert(T key) { if (root == NULL) { root = new AVLnode<T>(key, NULL); } else { AVLnode<T> *n = root, *parent;   while (true) { if (n->key == key) return false;   parent = n;   bool goLeft = n->key > key; n = goLeft ? n->left : n->right;   if (n == NULL) { if (goLeft) { parent->left = new AVLnode<T>(key, parent); } else { parent->right = new AVLnode<T>(key, parent); }   rebalance(parent); break; } } }   return true; }   template <class T> void AVLtree<T>::deleteKey(const T delKey) { if (root == NULL) return;   AVLnode<T> *n = root, *parent = root, *delNode = NULL, *child = root;   while (child != NULL) { parent = n; n = child; child = delKey >= n->key ? n->right : n->left; if (delKey == n->key) delNode = n; }   if (delNode != NULL) { delNode->key = n->key;   child = n->left != NULL ? n->left : n->right;   if (root->key == delKey) { root = child; } else { if (parent->left == n) { parent->left = child; } else { parent->right = child; }   rebalance(parent); } } }   template <class T> void AVLtree<T>::printBalance() { printBalance(root); std::cout << std::endl; }   int main(void) { AVLtree<int> t;   std::cout << "Inserting integer values 1 to 10" << std::endl; for (int i = 1; i <= 10; ++i) t.insert(i);   std::cout << "Printing balance: "; t.printBalance(); }  
http://rosettacode.org/wiki/Averages/Mean_angle
Averages/Mean angle
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the second was of 10 degrees then the average of the numbers is 180 degrees, whereas if you can note that 350 degrees is equivalent to -10 degrees and so you have two readings at 10 degrees either side of zero degrees leading to a more fitting mean angle of zero degrees. To calculate the mean angle of several angles: Assume all angles are on the unit circle and convert them to complex numbers expressed in real and imaginary form. Compute the mean of the complex numbers. Convert the complex mean to polar coordinates whereupon the phase of the complex mean is the required angular mean. (Note that, since the mean is the sum divided by the number of numbers, and division by a positive real number does not affect the angle, you can also simply compute the sum for step 2.) You can alternatively use this formula: Given the angles α 1 , … , α n {\displaystyle \alpha _{1},\dots ,\alpha _{n}} the mean is computed by α ¯ = atan2 ⁡ ( 1 n ⋅ ∑ j = 1 n sin ⁡ α j , 1 n ⋅ ∑ j = 1 n cos ⁡ α j ) {\displaystyle {\bar {\alpha }}=\operatorname {atan2} \left({\frac {1}{n}}\cdot \sum _{j=1}^{n}\sin \alpha _{j},{\frac {1}{n}}\cdot \sum _{j=1}^{n}\cos \alpha _{j}\right)} Task[edit] write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle. (You should use a built-in function if you have one that does this for degrees or radians). Use the function to compute the means of these lists of angles (in degrees):   [350, 10]   [90, 180, 270, 360]   [10, 20, 30] Show your output here. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#C.23
C#
using System; using System.Linq; using static System.Math; class Program { static double MeanAngle(double[] angles) { var x = angles.Sum(a => Cos(a * PI / 180)) / angles.Length; var y = angles.Sum(a => Sin(a * PI / 180)) / angles.Length; return Atan2(y, x) * 180 / PI; } static void Main() { Action<double[]> printMean = x => Console.WriteLine("{0:0.###}", MeanAngle(x)); printMean(new double[] { 350, 10 }); printMean(new double[] { 90, 180, 270, 360 }); printMean(new double[] { 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
#Applesoft_BASIC
Applesoft BASIC
100 REMMEDIAN 110 K = INT(L/2) : GOSUB 150 120 R = X(K) 130 IF L - 2 * INT (L / 2) THEN R = (R + X(K + 1)) / 2 140 RETURN   150 REMQUICK SELECT 160 LT = 0:RT = L - 1 170 FOR J = LT TO RT STEP 0 180 PT = X(K) 190 P1 = K:P2 = RT: GOSUB 300 200 P = LT 210 FOR I = P TO RT - 1 220 IF X(I) < PT THEN P1 = I:P2 = P: GOSUB 300:P = P + 1 230 NEXT I 240 P1 = RT:P2 = P: GOSUB 300 250 IF P = K THEN RETURN 260 IF P < K THEN LT = P + 1 270 IF P > = K THEN RT = P - 1 280 NEXT J 290 RETURN   300 REMSWAP 310 H = X(P1):X(P1) = X(P2) 320 X(P2) = H: RETURN
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
#Arturo
Arturo
arr: [1 2 3 4 5 6 7] arr2: [1 2 3 4 5 6]   print median arr print median arr2
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
#Euler_Math_Toolbox
Euler Math Toolbox
  >function A(x) := mean(x) >function G(x) := exp(mean(log(x))) >function H(x) := 1/mean(1/x) >x=1:10; A(x), G(x), H(x) 5.5 4.52872868812 3.41417152147  
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.
#Factor
Factor
USING: kernel combinators locals formatting lint literals sequences assocs strings arrays math math.functions math.order ; IN: rosetta-code.bt CONSTANT: addlookup { { 0 CHAR: 0 } { 1 CHAR: + } { -1 CHAR: - } }   <PRIVATE   : bt-add-digits ( a b c -- d e ) + + 3 + { { 0 -1 } { 1 -1 } { -1 0 } { 0 0 } { 1 0 } { -1 1 } { 0 1 } } nth first2 ;   PRIVATE>   ! Conversion : bt>integer ( seq -- x ) 0 [ swap 3 * + ] reduce ; : integer>bt ( x -- x ) [ dup zero? not ] [ dup 3 rem { { 0 [ 3 / 0 ] } { 1 [ 3 / round 1 ] } { 2 [ 1 + 3 / round -1 ] } } case ] produce nip reverse ; : bt>string ( seq -- str ) [ addlookup at ] map >string ; : string>bt ( str -- seq ) [ addlookup value-at ] { } map-as ;   ! Arithmetic : bt-neg ( a -- -a ) [ neg ] map ; :: bt-add ( u v -- w ) u v max-length :> maxl u v [ maxl 0 pad-head reverse ] bi@ :> ( u v ) 0 :> carry! u v { } [ carry bt-add-digits carry! prefix ] 2reduce carry prefix [ zero? ] trim-head ; : bt-sub ( u v -- w ) bt-neg bt-add ; :: bt-mul ( u v -- w ) u { } [ { { -1 [ v bt-neg ] } { 0 [ { } ] } { 1 [ v ] } } case bt-add 0 suffix ] reduce 1 head* ;   [let "+-0++0+" string>bt :> a -436 integer>bt  :> b "+-++-" string>bt  :> c b c bt-sub a bt-mul :> d "a" a bt>integer a bt>string "%s: %d, %s\n" printf "b" b bt>integer b bt>string "%s: %d, %s\n" printf "c" c bt>integer c bt>string "%s: %d, %s\n" printf "a*(b-c)" d bt>integer d bt>string "%s: %d, %s\n" printf ]
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.
#MiniScript
MiniScript
// Lines that start with "//" are "comments" that are ignored // by the computer. We use them to explain the code.   // Start by finding the smallest number that could possibly // square to 269696. sqrt() returns the square root of a // number, and floor() truncates any fractional part. k = floor(sqrt(269696))   // Since 269696 is even, we are only going to consider even // roots. We use the % (modulo) operator, which returns the // remainder after division, to tell if k is odd; if so, we // add 1 to make it even. if k % 2 == 1 then k = k + 1   // Now we count up by 2 from k, until we find a number that, // when squared, ends in 269696 (using % again). while k^2 % 1000000 != 269696 k = k + 2 end while   // The first such number we find is our answer. print k + "^2 = " + k^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.
#Modula-2
Modula-2
MODULE BabbageProblem; FROM FormatString IMPORT FormatString; FROM RealMath IMPORT sqrt; FROM Terminal IMPORT WriteString,ReadChar;   VAR buf : ARRAY[0..63] OF CHAR; k : INTEGER; BEGIN (* Find the greatest integer less than the square root *) k := TRUNC(sqrt(269696.0));   (* Odd numbers cannot be solutions, so decrement *) IF k MOD 2 = 1 THEN DEC(k); END;   (* Find a number that meets the criteria *) WHILE (k*k) MOD 1000000 # 269696 DO INC(k,2) END;   FormatString("%i * %i = %i", buf, k, k, k*k); WriteString(buf);   ReadChar END BabbageProblem.
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
#AWK
AWK
#!/usr/bin/awk -f BEGIN { print isbb("[]") print isbb("][") print isbb("][][") print isbb("[][]") print isbb("[][][]") print isbb("[]][[]") }   function isbb(x) { s = 0 for (k=1; k<=length(x); k++) { c = substr(x,k,1) if (c=="[") {s++} else { if (c=="]") s-- }   if (s<0) {return 0} } return (s==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
#ERRE
ERRE
PROGRAM MODE_AVG   !$INTEGER   DIM A[10],B[10],Z[10]   PROCEDURE SORT(Z[],P->Z[]) LOCAL N,FLIPS FLIPS=TRUE WHILE FLIPS DO FLIPS=FALSE FOR N=0 TO P-1 DO IF Z[N]>Z[N+1] THEN SWAP(Z[N],Z[N+1]) FLIPS=TRUE END FOR END WHILE END PROCEDURE   PROCEDURE CALC_MODE(Z[],P->MODES$) LOCAL I,OCCURRENCE,MAXOCCURRENCE,OLDVAL SORT(Z[],P->Z[]) OCCURENCE=1 MAXOCCURENCE=0 OLDVAL=Z[0] MODES$="" FOR I=1 TO P DO IF Z[I]=OLDVAL THEN OCCURENCE=OCCURENCE+1 ELSE IF OCCURENCE>MAXOCCURENCE THEN MAXOCCURENCE=OCCURENCE MODES$=STR$(OLDVAL) ELSIF OCCURENCE=MAXOCCURENCE THEN MODES$=MODES$+STR$(OLDVAL) ELSE  !$NULL END IF OCCURENCE=1 END IF OLDVAL=Z[I] END FOR  !check after loop IF OCCURENCE>MAXOCCURENCE THEN MAXOCCURENCE=OCCURENCE MODES$=STR$(OLDVAL) ELSIF OCCURENCE=MAXOCCURENCE THEN MODES$=MODES$+STR$(OLDVAL) ELSE  !$NULL END IF END PROCEDURE   BEGIN A[]=(1,3,6,6,6,6,7,7,12,12,17) B[]=(1,2,4,4,1) PRINT("Modes for array A (1,3,6,6,6,6,7,7,12,12,17)";) CALC_MODE(A[],10->MODES$) PRINT(MODES$) PRINT("Modes for array B (1,2,4,4,1)";) CALC_MODE(B[],4->MODES$) PRINT(MODES$) END PROGRAM
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
#Euphoria
Euphoria
include misc.e   function mode(sequence s) sequence uniques, counts, modes integer j,max uniques = {} counts = {} for i = 1 to length(s) do j = find(s[i], uniques) if j then counts[j] += 1 else uniques = append(uniques, s[i]) counts = append(counts, 1) end if end for   max = counts[1] for i = 2 to length(counts) do if counts[i] > max then max = counts[i] end if end for   j = 1 modes = {} while j <= length(s) do j = find_from(max, counts, j) if j = 0 then exit end if modes = append(modes, uniques[j]) j += 1 end while return modes end function   constant s = { 1, "blue", 2, 7.5, 5, "green", "red", 5, 2, "blue", "white" } pretty_print(1,mode(s),{3})
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#11l
11l
F average(x) R sum(x) / Float(x.len)   print(average([0, 0, 3, 1, 4, 1, 5, 9, 0, 0]))
http://rosettacode.org/wiki/Average_loop_length
Average loop length
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence. Task Write a program or a script that estimates, for each N, the average length until the first such repetition. Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one. This problem comes from the end of Donald Knuth's Christmas tree lecture 2011. Example of expected output: N average analytical (error) === ========= ============ ========= 1 1.0000 1.0000 ( 0.00%) 2 1.4992 1.5000 ( 0.05%) 3 1.8784 1.8889 ( 0.56%) 4 2.2316 2.2188 ( 0.58%) 5 2.4982 2.5104 ( 0.49%) 6 2.7897 2.7747 ( 0.54%) 7 3.0153 3.0181 ( 0.09%) 8 3.2429 3.2450 ( 0.07%) 9 3.4536 3.4583 ( 0.14%) 10 3.6649 3.6602 ( 0.13%) 11 3.8091 3.8524 ( 1.12%) 12 3.9986 4.0361 ( 0.93%) 13 4.2074 4.2123 ( 0.12%) 14 4.3711 4.3820 ( 0.25%) 15 4.5275 4.5458 ( 0.40%) 16 4.6755 4.7043 ( 0.61%) 17 4.8877 4.8579 ( 0.61%) 18 4.9951 5.0071 ( 0.24%) 19 5.1312 5.1522 ( 0.41%) 20 5.2699 5.2936 ( 0.45%)
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Numerics.Generic_Elementary_Functions; with Ada.Numerics.Discrete_Random; procedure Avglen is package IIO is new Ada.Text_IO.Integer_IO (Positive); use IIO; package LFIO is new Ada.Text_IO.Float_IO (Long_Float); use LFIO; subtype FactN is Natural range 0..20; TESTS : constant Natural := 1_000_000;   function Factorial (N : FactN) return Long_Float is Result : Long_Float := 1.0; begin for I in 2..N loop Result := Result * Long_Float(I); end loop; return Result; end Factorial;   function Analytical (N : FactN) return Long_Float is Sum : Long_Float := 0.0; begin for I in 1..N loop Sum := Sum + Factorial(N) / Factorial(N - I) / Long_Float(N)**I; end loop; return Sum; end Analytical;   function Experimental (N : FactN) return Long_Float is subtype RandInt is Natural range 1..N; package Random is new Ada.Numerics.Discrete_Random(RandInt); seed : Random.Generator; Num : RandInt; count : Natural := 0; bits : array(RandInt'Range) of Boolean; begin Random.Reset(seed); for run in 1..TESTS loop bits := (others => false); for I in RandInt'Range loop Num := Random.Random(seed); exit when bits(Num); bits(Num) := True; count := count + 1; end loop; end loop; return Long_Float(count)/Long_Float(TESTS); end Experimental;   A, E, err : Long_Float; begin Put_Line(" N avg calc  %diff"); for I in 1..20 loop A := Analytical(I); E := Experimental(I); err := abs(E-A)/A*100.0; Put(I, Width=>2); Put(E ,Aft=>4, exp=>0); Put(A, Aft=>4, exp=>0); Put(err, Fore=>3, Aft=>3, exp=>0); New_line; end loop; end Avglen;
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
#PARI.2FGP
PARI/GP
sma_per(n)={ sma_v=vector(n); sma_i = 0; n->if(sma_i++>#sma_v,sma_v[sma_i=1]=n;0,sma_v[sma_i]=n;0)+sum(i=1,#sma_v,sma_v[i])/#sma_v };
http://rosettacode.org/wiki/Attractive_numbers
Attractive numbers
A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show sequence items up to   120. Reference   The OEIS entry:   A063989: Numbers with a prime number of prime divisors.
#Ada
Ada
with Ada.Text_IO;   procedure Attractive_Numbers is   function Is_Prime (N : in Natural) return Boolean is D : Natural := 5; begin if N < 2 then return False; end if; if N mod 2 = 0 then return N = 2; end if; if N mod 3 = 0 then return N = 3; end if;   while D * D <= N loop if N mod D = 0 then return False; end if; D := D + 2; if N mod D = 0 then return False; end if; D := D + 4; end loop; return True; end Is_Prime;   function Count_Prime_Factors (N : in Natural) return Natural is NC  : Natural := N; Count : Natural := 0; F  : Natural := 2; begin if NC = 1 then return 0; end if; if Is_Prime (NC) then return 1; end if; loop if NC mod F = 0 then Count := Count + 1; NC := NC / F;   if NC = 1 then return Count; end if;   if Is_Prime (NC) then F := NC; end if; elsif F >= 3 then F := F + 2; else F := 3; end if; end loop; end Count_Prime_Factors;   procedure Show_Attractive (Max : in Natural) is use Ada.Text_IO; package Integer_IO is new Ada.Text_IO.Integer_IO (Integer); N  : Natural; Count : Natural := 0; begin Put_Line ("The attractive numbers up to and including " & Max'Image & " are:"); for I in 1 .. Max loop N := Count_Prime_Factors (I); if Is_Prime (N) then Integer_IO.Put (I, Width => 5); Count := Count + 1; if Count mod 20 = 0 then New_Line; end if; end if; end loop; end Show_Attractive;   begin Show_Attractive (Max => 120); end Attractive_Numbers;
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
#EchoLisp
EchoLisp
  ;; string hh:mm:ss to radians (define (time->radian time) (define-values (h m s) (map string->number (string-split time ":"))) (+ (* h (/ PI 12)) (* m (/ PI 12 60)) (* s (/ PI 12 3600))))   ;; radians to string hh:mm;ss (define (radian->time rad) (when (< rad 0) (+= rad (* 2 PI))) (define t (round (/ (* 12 3600 rad) PI))) (define h (quotient t 3600)) (define m (quotient (- t (* h 3600)) 60)) (define s (- t (* 3600 h) (* 60 m))) (string-join (map number->string (list h m s)) ":"))   (define (mean-time times) (radian->time (angle (for/sum ((t times)) (make-polar 1 (time->radian t))))))   (mean-time '{"23:00:17" "23:40:20" "00:12:45" "00:17:19"}) → "23:47:43"  
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.
#C.2B.2B
C++
  #include <algorithm> #include <iostream>   /* AVL node */ template <class T> class AVLnode { public: T key; int balance; AVLnode *left, *right, *parent;   AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p), left(NULL), right(NULL) {}   ~AVLnode() { delete left; delete right; } };   /* AVL tree */ template <class T> class AVLtree { public: AVLtree(void); ~AVLtree(void); bool insert(T key); void deleteKey(const T key); void printBalance();   private: AVLnode<T> *root;   AVLnode<T>* rotateLeft ( AVLnode<T> *a ); AVLnode<T>* rotateRight ( AVLnode<T> *a ); AVLnode<T>* rotateLeftThenRight ( AVLnode<T> *n ); AVLnode<T>* rotateRightThenLeft ( AVLnode<T> *n ); void rebalance ( AVLnode<T> *n ); int height ( AVLnode<T> *n ); void setBalance ( AVLnode<T> *n ); void printBalance ( AVLnode<T> *n ); };   /* AVL class definition */ template <class T> void AVLtree<T>::rebalance(AVLnode<T> *n) { setBalance(n);   if (n->balance == -2) { if (height(n->left->left) >= height(n->left->right)) n = rotateRight(n); else n = rotateLeftThenRight(n); } else if (n->balance == 2) { if (height(n->right->right) >= height(n->right->left)) n = rotateLeft(n); else n = rotateRightThenLeft(n); }   if (n->parent != NULL) { rebalance(n->parent); } else { root = n; } }   template <class T> AVLnode<T>* AVLtree<T>::rotateLeft(AVLnode<T> *a) { AVLnode<T> *b = a->right; b->parent = a->parent; a->right = b->left;   if (a->right != NULL) a->right->parent = a;   b->left = a; a->parent = b;   if (b->parent != NULL) { if (b->parent->right == a) { b->parent->right = b; } else { b->parent->left = b; } }   setBalance(a); setBalance(b); return b; }   template <class T> AVLnode<T>* AVLtree<T>::rotateRight(AVLnode<T> *a) { AVLnode<T> *b = a->left; b->parent = a->parent; a->left = b->right;   if (a->left != NULL) a->left->parent = a;   b->right = a; a->parent = b;   if (b->parent != NULL) { if (b->parent->right == a) { b->parent->right = b; } else { b->parent->left = b; } }   setBalance(a); setBalance(b); return b; }   template <class T> AVLnode<T>* AVLtree<T>::rotateLeftThenRight(AVLnode<T> *n) { n->left = rotateLeft(n->left); return rotateRight(n); }   template <class T> AVLnode<T>* AVLtree<T>::rotateRightThenLeft(AVLnode<T> *n) { n->right = rotateRight(n->right); return rotateLeft(n); }   template <class T> int AVLtree<T>::height(AVLnode<T> *n) { if (n == NULL) return -1; return 1 + std::max(height(n->left), height(n->right)); }   template <class T> void AVLtree<T>::setBalance(AVLnode<T> *n) { n->balance = height(n->right) - height(n->left); }   template <class T> void AVLtree<T>::printBalance(AVLnode<T> *n) { if (n != NULL) { printBalance(n->left); std::cout << n->balance << " "; printBalance(n->right); } }   template <class T> AVLtree<T>::AVLtree(void) : root(NULL) {}   template <class T> AVLtree<T>::~AVLtree(void) { delete root; }   template <class T> bool AVLtree<T>::insert(T key) { if (root == NULL) { root = new AVLnode<T>(key, NULL); } else { AVLnode<T> *n = root, *parent;   while (true) { if (n->key == key) return false;   parent = n;   bool goLeft = n->key > key; n = goLeft ? n->left : n->right;   if (n == NULL) { if (goLeft) { parent->left = new AVLnode<T>(key, parent); } else { parent->right = new AVLnode<T>(key, parent); }   rebalance(parent); break; } } }   return true; }   template <class T> void AVLtree<T>::deleteKey(const T delKey) { if (root == NULL) return;   AVLnode<T> *n = root, *parent = root, *delNode = NULL, *child = root;   while (child != NULL) { parent = n; n = child; child = delKey >= n->key ? n->right : n->left; if (delKey == n->key) delNode = n; }   if (delNode != NULL) { delNode->key = n->key;   child = n->left != NULL ? n->left : n->right;   if (root->key == delKey) { root = child; } else { if (parent->left == n) { parent->left = child; } else { parent->right = child; }   rebalance(parent); } } }   template <class T> void AVLtree<T>::printBalance() { printBalance(root); std::cout << std::endl; }   int main(void) { AVLtree<int> t;   std::cout << "Inserting integer values 1 to 10" << std::endl; for (int i = 1; i <= 10; ++i) t.insert(i);   std::cout << "Printing balance: "; t.printBalance(); }  
http://rosettacode.org/wiki/Averages/Mean_angle
Averages/Mean angle
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the second was of 10 degrees then the average of the numbers is 180 degrees, whereas if you can note that 350 degrees is equivalent to -10 degrees and so you have two readings at 10 degrees either side of zero degrees leading to a more fitting mean angle of zero degrees. To calculate the mean angle of several angles: Assume all angles are on the unit circle and convert them to complex numbers expressed in real and imaginary form. Compute the mean of the complex numbers. Convert the complex mean to polar coordinates whereupon the phase of the complex mean is the required angular mean. (Note that, since the mean is the sum divided by the number of numbers, and division by a positive real number does not affect the angle, you can also simply compute the sum for step 2.) You can alternatively use this formula: Given the angles α 1 , … , α n {\displaystyle \alpha _{1},\dots ,\alpha _{n}} the mean is computed by α ¯ = atan2 ⁡ ( 1 n ⋅ ∑ j = 1 n sin ⁡ α j , 1 n ⋅ ∑ j = 1 n cos ⁡ α j ) {\displaystyle {\bar {\alpha }}=\operatorname {atan2} \left({\frac {1}{n}}\cdot \sum _{j=1}^{n}\sin \alpha _{j},{\frac {1}{n}}\cdot \sum _{j=1}^{n}\cos \alpha _{j}\right)} Task[edit] write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle. (You should use a built-in function if you have one that does this for degrees or radians). Use the function to compute the means of these lists of angles (in degrees):   [350, 10]   [90, 180, 270, 360]   [10, 20, 30] Show your output here. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#C.2B.2B
C++
#include <iomanip> #include <iostream> #include <vector>   #define _USE_MATH_DEFINES #include <math.h>   template<typename C> double meanAngle(const C& c) { auto it = std::cbegin(c); auto end = std::cend(c);   double x = 0.0; double y = 0.0; double len = 0.0; while (it != end) { x += cos(*it * M_PI / 180); y += sin(*it * M_PI / 180); len++;   it = std::next(it); }   return atan2(y, x) * 180 / M_PI; }   void printMean(std::initializer_list<double> init) { std::cout << std::fixed << std::setprecision(3) << meanAngle(init) << '\n'; }   int main() { printMean({ 350, 10 }); printMean({ 90, 180, 270, 360 }); printMean({ 10, 20, 30 });   return 0; }
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
#AutoHotkey
AutoHotkey
seq = 4.1, 7.2, 1.7, 9.3, 4.4, 3.2, 5 MsgBox % median(seq, "`,") ; 4.1   median(seq, delimiter) { Sort, seq, ND%delimiter% StringSplit, seq, seq, % delimiter median := Floor(seq0 / 2) Return seq%median% }
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
#Euphoria
Euphoria
function arithmetic_mean(sequence s) atom sum if length(s) = 0 then return 0 else sum = 0 for i = 1 to length(s) do sum += s[i] end for return sum/length(s) end if end function   function geometric_mean(sequence s) atom p p = 1 for i = 1 to length(s) do p *= s[i] end for return power(p,1/length(s)) end function   function harmonic_mean(sequence s) atom sum if length(s) = 0 then return 0 else sum = 0 for i = 1 to length(s) do sum += 1/s[i] end for return length(s) / sum end if end function   function true_or_false(atom x) if x then return "true" else return "false" end if end function   constant s = {1,2,3,4,5,6,7,8,9,10} constant arithmetic = arithmetic_mean(s), geometric = geometric_mean(s), harmonic = harmonic_mean(s) printf(1,"Arithmetic: %g\n", arithmetic) printf(1,"Geometric: %g\n", geometric) printf(1,"Harmonic: %g\n", harmonic) printf(1,"Arithmetic>=Geometric>=Harmonic: %s\n", {true_or_false(arithmetic>=geometric and geometric>=harmonic)})
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.
#FreeBASIC
FreeBASIC
  #define MAX(a, b) iif((a) > (b), (a), (b)) Dim Shared As Integer pow, signo Dim Shared As String t t = "-0+"   Function deci(cadena As String) As Integer Dim As Integer i, deci1 Dim As String c1S pow = 1 For i = Len(cadena) To 1 Step -1 c1S = Mid(cadena,i,1) signo = Instr(t, c1S)-2 deci1 = deci1 + pow * signo pow *= 3 Next i Return deci1 End Function   Function ternary(n As Integer) As String Dim As String ternario Dim As Integer i, k While Abs(n) > 3^k/2 k += 1 Wend k -= 1   pow = 3^k For i = k To 0 Step -1 signo = (n>0) - (n<0) signo *= (Abs(n) > pow/2) ternario += Mid(t,signo+2,1) n -= signo*pow pow /= 3 Next If ternario = "" Then ternario = "0" Return ternario End Function   Function negate(cadena As String) As String Dim As String negar = "" For i As Integer = 1 To Len(cadena) negar += Mid(t, 4-Instr(t, Mid(cadena,i,1)), 1) Next i Return negar End Function   Function pad(cadenaA As String, n As Integer) As String Dim As String relleno = cadenaA While Len(relleno) < n relleno = "0" + relleno Wend Return relleno End Function   Function addTernary(cadenaA As String, cadenaB As String) As String Dim As Integer l = max(Len(cadenaA), Len(cadenaB)) Dim As Integer i, x, y, z cadenaA = pad(cadenaA, l) cadenaB = pad(cadenaB, l) Dim As String resultado = "" Dim As Byte llevar = 0 For i = l To 1 Step -1 x = Instr(t, Mid(cadenaA,i,1))-2 y = Instr(t, Mid(cadenaB,i,1))-2 z = x + y + llevar   If Abs(z) < 2 Then llevar = 0 Elseif z > 0 Then llevar = 1: z -= 3 Elseif z < 0 Then llevar = -1: z += 3 End If   resultado = Mid(t,z+2,1) + resultado Next i If llevar <> 0 Then resultado = Mid(t,llevar+2,1) + resultado   i = 0 While Mid(resultado,i+1,1) = "0" i += 1 Wend resultado = Mid(resultado,i+1) If resultado = "" Then resultado = "0" Return resultado End Function   Function subTernary(cadenaA As String, cadenaB As String) As String Return addTernary(cadenaA, negate(cadenaB)) End Function   Function multTernary(cadenaA As String, cadenaB As String) As String Dim As String resultado = "" Dim As String tS = "", cambio = "" For i As Integer = Len(cadenaA) To 1 Step -1 Select Case Mid(cadenaA,i,1) Case "+": tS = cadenaB Case "0": tS = "0" Case "-": tS = negate(cadenaB) End Select   resultado = addTernary(resultado, tS + cambio) cambio += "0" Next i Return resultado End Function     Dim As String cadenaA = "+-0++0+" Dim As Integer a = deci(cadenaA) Print " a:", a, cadenaA   Dim As Integer b = -436 Dim As String cadenaB = ternary(b) Print " b:", b, cadenaB   Dim As String cadenaC = "+-++-" Dim As Integer c = deci(cadenaC) Print " c:", c, cadenaC   'calcular en ternario Dim As String resS = multTernary(cadenaA, subTernary(cadenaB, cadenaC)) Print "a*(b-c):", deci(resS), resS   Print !"\nComprobamos:" Print "a*(b-c): ", a * (b - c) Sleep  
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.
#Nanoquery
Nanoquery
n = 0   while not (n ^ 2 % 1000000) = 269696 n += 1 end   println 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.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary utf8 numeric digits 5000 -- set up numeric precision   babbageNr = babbage() -- call a function to perform the analysis and capture the result babbageSq = babbageNr ** 2 -- calculate the square of the result -- display results using a library function System.out.printf("%,10d\u00b2 == %,12d%n", [Integer(babbageNr), Integer(babbageSq)]) return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- A function method to answer Babbage's question: -- "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.)   method babbage() public static binary n = int 104 -- (integer arithmatic) -- begin a processing loop to determine the value -- starting point: 104 loop while ((n * n) // 1000000) \= 269696 -- loop continues while the remainder of n squared divided by 1,000,000 is not equal to 269,696 if n // 10 == 4 then do -- increment n by 2 if the remainder of n divided by 10 equals 4 n = n + 2 end if n // 10 == 6 then do -- increment n by 8 if the remainder of n divided by 10 equals 6 n = n + 8 end end   return n -- end the function and return the result  
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
#BaCon
BaCon
FOR len = 0 TO 18 STEP 2   str$ = "" DOTIMES len str$ = str$ & CHR$(IIF(RANDOM(2) = 0, 91, 93)) DONE   status = 0 FOR x = 1 TO LEN(str$) IF MID$(str$, x, 1) = "[" THEN INCR status ELSE DECR status FI IF status < 0 THEN BREAK NEXT   IF status = 0 THEN PRINT "OK: ", str$ ELSE PRINT "BAD: ", str$ ENDIF NEXT
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
#F.23
F#
let mode (l:'a seq) = l |> Seq.countBy (fun item -> item) // Count individual items |> Seq.fold // Find max counts (fun (cp, lst) (item, c) -> // State is (count, list of items with that count) if c > cp then (c, [item]) // New max - keep count and a list of the single item elif c = cp then (c, item :: lst) // New element with max count - prepend it to the list else (cp,lst)) // else just keep old count/list (0, [Unchecked.defaultof<'a>]) // Start with a count of 0 and a dummy item |> snd // From (count, list) we just want the second item (the list)
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
#Factor
Factor
{ 11 9 4 9 4 9 } mode ! 9
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#360_Assembly
360 Assembly
AVGP CSECT USING AVGP,12 LR 12,15 SR 3,3 i=0 SR 6,6 sum=0 LOOP CH 3,=AL2(NN-T-1) for i=1 to nn BH ENDLOOP L 2,T(3) t(i) MH 2,=H'100' scaling factor=2 AR 6,2 sum=sum+t(i) LA 3,4(3) next i B LOOP ENDLOOP LR 5,6 sum LA 4,0 D 4,NN sum/nn XDECO 5,Z edit binary MVC U,Z+10 descale MVI Z+10,C'.' MVC Z+11(2),U XPRNT Z,80 output XR 15,15 BR 14 T DC F'10',F'9',F'8',F'7',F'6',F'5',F'4',F'3',F'2',F'1' NN DC A((NN-T)/4) Z DC CL80' ' U DS CL2 END AVGP
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#6502_Assembly
6502 Assembly
ArithmeticMean: PHA TYA PHA ;push accumulator and Y register onto stack     LDA #0 STA Temp STA Temp+1 ;temporary 16-bit storage for total   LDY NumberInts BEQ Done ;if NumberInts = 0 then return an average of zero   DEY ;start with NumberInts-1 AddLoop: LDA (ArrayPtr),Y CLC ADC Temp STA Temp LDA Temp+1 ADC #0 STA Temp+1 DEY CPY #255 BNE AddLoop   LDY #-1 DivideLoop: LDA Temp SEC SBC NumberInts STA Temp LDA Temp+1 SBC #0 STA Temp+1 INY BCS DivideLoop   Done: STY ArithMean ;store result here PLA ;restore accumulator and Y register from stack TAY PLA RTS ;return from routine
http://rosettacode.org/wiki/Average_loop_length
Average loop length
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence. Task Write a program or a script that estimates, for each N, the average length until the first such repetition. Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one. This problem comes from the end of Donald Knuth's Christmas tree lecture 2011. Example of expected output: N average analytical (error) === ========= ============ ========= 1 1.0000 1.0000 ( 0.00%) 2 1.4992 1.5000 ( 0.05%) 3 1.8784 1.8889 ( 0.56%) 4 2.2316 2.2188 ( 0.58%) 5 2.4982 2.5104 ( 0.49%) 6 2.7897 2.7747 ( 0.54%) 7 3.0153 3.0181 ( 0.09%) 8 3.2429 3.2450 ( 0.07%) 9 3.4536 3.4583 ( 0.14%) 10 3.6649 3.6602 ( 0.13%) 11 3.8091 3.8524 ( 1.12%) 12 3.9986 4.0361 ( 0.93%) 13 4.2074 4.2123 ( 0.12%) 14 4.3711 4.3820 ( 0.25%) 15 4.5275 4.5458 ( 0.40%) 16 4.6755 4.7043 ( 0.61%) 17 4.8877 4.8579 ( 0.61%) 18 4.9951 5.0071 ( 0.24%) 19 5.1312 5.1522 ( 0.41%) 20 5.2699 5.2936 ( 0.45%)
#BBC_BASIC
BBC BASIC
@% = &2040A MAX_N = 20 TIMES = 1000000   FOR n = 1 TO MAX_N avg = FNtest(n, TIMES) theory = FNanalytical(n) diff = (avg / theory - 1) * 100 PRINT STR$(n), avg, theory, diff "%" NEXT END   DEF FNanalytical(n) LOCAL i, s FOR i = 1 TO n s += FNfactorial(n) / n^i / FNfactorial(n-i) NEXT = s   DEF FNtest(n, times) LOCAL i, b, c, x FOR i = 1 TO times x = 1 : b = 0 WHILE (b AND x) = 0 c += 1 b OR= x x = 1 << (RND(n) - 1) ENDWHILE NEXT = c / times   DEF FNfactorial(n) IF n=1 OR n=0 THEN =1 ELSE = n * FNfactorial(n-1)
http://rosettacode.org/wiki/Average_loop_length
Average loop length
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence. Task Write a program or a script that estimates, for each N, the average length until the first such repetition. Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one. This problem comes from the end of Donald Knuth's Christmas tree lecture 2011. Example of expected output: N average analytical (error) === ========= ============ ========= 1 1.0000 1.0000 ( 0.00%) 2 1.4992 1.5000 ( 0.05%) 3 1.8784 1.8889 ( 0.56%) 4 2.2316 2.2188 ( 0.58%) 5 2.4982 2.5104 ( 0.49%) 6 2.7897 2.7747 ( 0.54%) 7 3.0153 3.0181 ( 0.09%) 8 3.2429 3.2450 ( 0.07%) 9 3.4536 3.4583 ( 0.14%) 10 3.6649 3.6602 ( 0.13%) 11 3.8091 3.8524 ( 1.12%) 12 3.9986 4.0361 ( 0.93%) 13 4.2074 4.2123 ( 0.12%) 14 4.3711 4.3820 ( 0.25%) 15 4.5275 4.5458 ( 0.40%) 16 4.6755 4.7043 ( 0.61%) 17 4.8877 4.8579 ( 0.61%) 18 4.9951 5.0071 ( 0.24%) 19 5.1312 5.1522 ( 0.41%) 20 5.2699 5.2936 ( 0.45%)
#C
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h>   #define MAX_N 20 #define TIMES 1000000   double factorial(int n) { double f = 1; int i; for (i = 1; i <= n; i++) f *= i; return f; }   double expected(int n) { double sum = 0; int i; for (i = 1; i <= n; i++) sum += factorial(n) / pow(n, i) / factorial(n - i); return sum; }   int randint(int n) { int r, rmax = RAND_MAX / n * n; while ((r = rand()) >= rmax); return r / (RAND_MAX / n); }   int test(int n, int times) { int i, count = 0; for (i = 0; i < times; i++) { int x = 1, bits = 0; while (!(bits & x)) { count++; bits |= x; x = 1 << randint(n); } } return count; }   int main(void) { srand(time(0)); puts(" n\tavg\texp.\tdiff\n-------------------------------");   int n; for (n = 1; n <= MAX_N; n++) { int cnt = test(n, TIMES); double avg = (double)cnt / TIMES; double theory = expected(n); double diff = (avg / theory - 1) * 100; printf("%2d %8.4f %8.4f %6.3f%%\n", n, avg, theory, diff); } 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
#Pascal
Pascal
program sma; type tsma = record smaValue : array of double; smaAverage, smaSumOld, smaSumNew, smaRezActLength : double; smaActLength, smaLength, smaPos :NativeInt; smaIsntFull: boolean; end;   procedure smaInit(var sma:tsma;p: NativeUint); Begin with sma do Begin setlength(smaValue,0); setlength(smaValue,p); smaLength:= p; smaActLength := 0; smaAverage:= 0.0; smaSumOld := 0.0; smaSumNew := 0.0; smaPos := p-1; smaIsntFull := true end; end;   function smaAddValue(var sma:tsma;v: double):double; Begin with sma do Begin IF smaIsntFull then Begin inc(smaActLength); smaRezActLength := 1/smaActLength; smaIsntFull := smaActLength < smaLength ; end; smaSumOld := smaSumOld+v-smaValue[smaPos]; smaValue[smaPos] := v; smaSumNew := smaSumNew+v;   smaPos := smaPos-1; if smaPos < 0 then begin smaSumOld:= smaSumNew; smaSumNew:= 0.0; smaPos := smaLength-1; end; smaAverage := smaSumOld *smaRezActLength; smaAddValue:= smaAverage; end; end;   var sma3,sma5:tsma; i : LongInt; begin smaInit(sma3,3); smaInit(sma5,5); For i := 1 to 5 do Begin write('Inserting ',i,' into sma3 ',smaAddValue(sma3,i):0:4); writeln(' Inserting ',i,' into sma5 ',smaAddValue(sma5,i):0:4); end; For i := 5 downto 1 do Begin write('Inserting ',i,' into sma3 ',smaAddValue(sma3,i):0:4); writeln(' Inserting ',i,' into sma5 ',smaAddValue(sma5,i):0:4); end; //speed test smaInit(sma3,3); For i := 1 to 100000000 do smaAddValue(sma3,i); writeln('100''000''000 insertions ',sma3.smaAverage:0:4); end.
http://rosettacode.org/wiki/Attractive_numbers
Attractive numbers
A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show sequence items up to   120. Reference   The OEIS entry:   A063989: Numbers with a prime number of prime divisors.
#ALGOL_68
ALGOL 68
BEGIN # find some attractive numbers - numbers whose prime factor counts are # # prime, n must be > 1 # PR read "primes.incl.a68" PR # find the attractive numbers # INT max number = 120; []BOOL sieve = PRIMESIEVE ENTIER sqrt( max number ); print( ( "The attractve numbers up to ", whole( max number, 0 ), newline ) ); INT a count := 0; FOR i FROM 2 TO max number DO IF INT v := i; INT f count := 0; WHILE NOT ODD v DO f count +:= 1; v OVERAB 2 OD; FOR j FROM 3 BY 2 TO max number WHILE v > 1 DO WHILE v > 1 AND v MOD j = 0 DO f count +:= 1; v OVERAB j OD OD; f count > 0 THEN IF sieve[ f count ] THEN print( ( " ", whole( i, -3 ) ) ); IF ( a count +:= 1 ) MOD 20 = 0 THEN print( ( newline ) ) FI FI FI OD; print( ( newline, "Found ", whole( a count, 0 ), " attractive numbers", newline ) ) END
http://rosettacode.org/wiki/Averages/Mean_time_of_day
Averages/Mean time of day
Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ideas of Averages/Mean angle compute and show the average time of the nocturnal activity to an accuracy of one second of time. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#Erlang
Erlang
  -module( mean_time_of_day ). -export( [from_times/1, task/0] ).   from_times( Times ) -> Seconds = [seconds_from_time(X) || X <- Times], Degrees = [degrees_from_seconds(X) || X <- Seconds], Average = mean_angle:from_degrees( Degrees ), time_from_seconds( seconds_from_degrees(Average) ).   task() -> Times = ["23:00:17", "23:40:20", "00:12:45", "00:17:19"], io:fwrite( "The mean time of ~p is: ~p~n", [Times, from_times(Times)] ).       degrees_from_seconds( Seconds ) when Seconds < (24 * 3600) -> (Seconds * 360) / (24 * 3600).   seconds_from_degrees( Degrees ) when Degrees < 0 -> seconds_from_degrees( Degrees + 360 ); seconds_from_degrees( Degrees ) when Degrees < 360 -> (Degrees * 24 * 3600) / 360.   seconds_from_time( Time ) -> {ok, [Hours, Minutes, Seconds], _Rest} = io_lib:fread( "~d:~d:~d", Time ), Hours * 3600 + Minutes * 60 + Seconds.   time_from_seconds( Seconds_float ) -> Seconds = erlang:round( Seconds_float ), Hours = Seconds div 3600, Minutes = (Seconds - (Hours * 3600)) div 60, Secs = Seconds - (Hours * 3600) - (Minutes * 60), lists:flatten( io_lib:format("~2.10.0B:~2.10.0B:~2.10.0B", [Hours, Minutes, Secs]) ).  
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.
#C.2B.2B.2FCLI
C++/CLI
(defpackage :avl-tree (:use :cl) (:export :avl-tree :make-avl-tree :avl-tree-count :avl-tree-p :avl-tree-key<= :gettree :remtree :clrtree :dfs-maptree :bfs-maptree))   (in-package :avl-tree)   (defstruct %tree key value (height 0 :type fixnum) left right)   (defstruct (avl-tree (:constructor %make-avl-tree)) key<= tree (count 0 :type fixnum))   (defun make-avl-tree (key<=) "Create a new AVL tree using the given comparison function KEY<= for emplacing keys into the tree." (%make-avl-tree :key<= key<=))   (declaim (inline recalc-height height balance swap-kv right-right-rotate right-left-rotate left-right-rotate left-left-rotate rotate))   (defun recalc-height (tree) "Calculate the new height of the tree from the heights of the children." (when tree (setf (%tree-height tree) (1+ (the fixnum (max (height (%tree-right tree)) (height (%tree-left tree))))))))   (declaim (ftype (function (t) fixnum) height balance)) (defun height (tree) (if tree (%tree-height tree) 0))   (defun balance (tree) (if tree (- (height (%tree-right tree)) (height (%tree-left tree))) 0))   (defmacro swap (place-a place-b) "Swap the values of two places." (let ((tmp (gensym))) `(let ((,tmp ,place-a)) (setf ,place-a ,place-b) (setf ,place-b ,tmp))))   (defun swap-kv (tree-a tree-b) "Swap the keys and values of two trees." (swap (%tree-value tree-a) (%tree-value tree-b)) (swap (%tree-key tree-a) (%tree-key tree-b)))   ;; We should really use gensyms for the variables in here. (defmacro slash-rotate (tree right left) "Rotate nodes in a slash `/` imbalance." `(let* ((a ,tree) (b (,right a)) (c (,right b)) (a-left (,left a)) (b-left (,left b))) (setf (,right a) c) (setf (,left a) b) (setf (,left b) a-left) (setf (,right b) b-left) (swap-kv a b) (recalc-height b) (recalc-height a)))   (defmacro angle-rotate (tree right left) "Rotate nodes in an angle bracket `<` imbalance." `(let* ((a ,tree) (b (,right a)) (c (,left b)) (a-left (,left a)) (c-left (,left c)) (c-right (,right c))) (setf (,left a) c) (setf (,left c) a-left) (setf (,right c) c-left) (setf (,left b) c-right) (swap-kv a c) (recalc-height c) (recalc-height b) (recalc-height a)))   (defun right-right-rotate (tree) (slash-rotate tree %tree-right %tree-left))   (defun left-left-rotate (tree) (slash-rotate tree %tree-left %tree-right))   (defun right-left-rotate (tree) (angle-rotate tree %tree-right %tree-left))   (defun left-right-rotate (tree) (angle-rotate tree %tree-left %tree-right))   (defun rotate (tree) (declare (type %tree tree)) "Perform a rotation on the given TREE if it is imbalanced." (recalc-height tree) (with-slots (left right) tree (let ((balance (balance tree))) (cond ((< 1 balance) ;; Right imbalanced tree (if (<= 0 (balance right)) (right-right-rotate tree) (right-left-rotate tree))) ((> -1 balance) ;; Left imbalanced tree (if (<= 0 (balance left)) (left-right-rotate tree) (left-left-rotate tree)))))))   (defun gettree (key avl-tree &optional default) "Finds an entry in AVL-TREE whos key is KEY and returns the associated value and T as multiple values, or returns DEFAULT and NIL if there was no such entry. Entries can be added using SETF." (with-slots (key<= tree) avl-tree (labels ((rec (tree) (if tree (with-slots ((t-key key) left right value) tree (if (funcall key<= t-key key) (if (funcall key<= key t-key) (values value t) (rec right)) (rec left))) (values default nil)))) (rec tree))))   (defun puttree (value key avl-tree) ;;(declare (optimize speed)) (declare (type avl-tree avl-tree)) "Emplace the the VALUE with the given KEY into the AVL-TREE, or overwrite the value if the given key already exists." (let ((node (make-%tree :key key :value value))) (with-slots (key<= tree count) avl-tree (cond (tree (labels ((rec (tree) (with-slots ((t-key key) left right) tree (if (funcall key<= t-key key) (if (funcall key<= key t-key) (setf (%tree-value tree) value) (cond (right (rec right)) (t (setf right node) (incf count)))) (cond (left (rec left)) (t (setf left node) (incf count)))) (rotate tree)))) (rec tree))) (t (setf tree node) (incf count)))) value))   (defun (setf gettree) (value key avl-tree &optional default) (declare (ignore default)) (puttree value key avl-tree))   (defun remtree (key avl-tree) (declare (type avl-tree avl-tree)) "Remove the entry in AVL-TREE associated with KEY. Return T if there was such an entry, or NIL if not." (with-slots (key<= tree count) avl-tree (labels ((find-left (tree) (with-slots ((t-key key) left right) tree (if left (find-left left) tree))) (rec (tree &optional parent type) (when tree (prog1 (with-slots ((t-key key) left right) tree (if (funcall key<= t-key key) (cond ((funcall key<= key t-key) (cond ((and left right) (let ((sub-left (find-left right))) (swap-kv sub-left tree) (rec right tree :right))) (t (let ((sub (or left right))) (case type (:right (setf (%tree-right parent) sub)) (:left (setf (%tree-left parent) sub)) (nil (setf (avl-tree-tree avl-tree) sub)))) (decf count))) t) (t (rec right tree :right))) (rec left tree :left))) (when parent (rotate parent)))))) (rec tree))))   (defun clrtree (avl-tree) "This removes all the entries from AVL-TREE and returns the tree itself." (setf (avl-tree-tree avl-tree) nil) (setf (avl-tree-count avl-tree) 0) avl-tree)   (defun dfs-maptree (function avl-tree) "For each entry in AVL-TREE call the two-argument FUNCTION on the key and value of each entry in depth-first order from left to right. Consequences are undefined if AVL-TREE is modified during this call." (with-slots (key<= tree) avl-tree (labels ((rec (tree) (when tree (with-slots ((t-key key) left right key value) tree (rec left) (funcall function key value) (rec right))))) (rec tree))))   (defun bfs-maptree (function avl-tree) "For each entry in AVL-TREE call the two-argument FUNCTION on the key and value of each entry in breadth-first order from left to right. Consequences are undefined if AVL-TREE is modified during this call." (with-slots (key<= tree) avl-tree (let* ((queue (cons nil nil)) (end queue)) (labels ((pushend (value) (when value (setf (cdr end) (cons value nil)) (setf end (cdr end)))) (empty-p () (eq nil (cdr queue))) (popfront () (prog1 (pop (cdr queue)) (when (empty-p) (setf end queue))))) (when tree (pushend tree) (loop until (empty-p) do (let ((current (popfront))) (with-slots (key value left right) current (funcall function key value) (pushend left) (pushend right)))))))))   (defun test () (let ((tree (make-avl-tree #'<=)) (printer (lambda (k v) (print (list k v))))) (loop for key in '(0 8 6 4 2 3 7 9 1 5 5) for value in '(a b c d e f g h i j k) do (setf (gettree key tree) value)) (loop for key in '(0 1 2 3 4 10) do (print (multiple-value-list (gettree key tree)))) (terpri) (print tree) (terpri) (dfs-maptree printer tree) (terpri) (bfs-maptree printer tree) (terpri) (loop for key in '(0 1 2 3 10 7) do (print (remtree key tree))) (terpri) (print tree) (terpri) (clrtree tree) (print tree)) (values))   (defun profile-test () (let ((tree (make-avl-tree #'<=)) (randoms (loop repeat 1000000 collect (random 100.0)))) (loop for key in randoms do (setf (gettree key tree) key))))
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
#Clojure
Clojure
(defn mean-fn [k coll] (let [n (count coll) trig (get {:sin #(Math/sin %) :cos #(Math/cos %)} k)] (* (/ 1 n) (reduce + (map trig coll)))))   (defn mean-angle [degrees] (let [radians (map #(Math/toRadians %) degrees) a (mean-fn :sin radians) b (mean-fn :cos radians)] (Math/toDegrees (Math/atan2 a b))))
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
#Common_Lisp
Common Lisp
(defun average (list) (/ (reduce #'+ list) (length list)))   (defun radians (angle) (* pi 1/180 angle))   (defun degrees (angle) (* (/ 180 pi) angle))   (defun mean-angle (angles) (let* ((angles (map 'list #'radians angles)) (cosines (map 'list #'cos angles)) (sines (map 'list #'sin angles))) (degrees (atan (average sines) (average cosines)))))   (loop for angles in '((350 10) (90 180 270 360) (10 20 30)) do (format t "~&The mean angle of ~a is ~$°." angles (mean-angle angles)))   ;; or using complex numbers (cis and phase)   (defun mean-angle-2 (angles) (degrees (phase (reduce #'+ angles :key (lambda (deg) (cis (radians deg)))))))  
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
#AWK
AWK
#!/usr/bin/awk -f   BEGIN { d[1] = 3.0 d[2] = 4.0 d[3] = 1.0 d[4] = -8.4 d[5] = 7.2 d[6] = 4.0 d[7] = 1.0 d[8] = 1.2 showD("Before: ") gnomeSortD() showD("Sorted: ") printf "Median: %f\n", medianD() exit }   function medianD( len, mid) { len = length(d) mid = int(len/2) + 1 if (len % 2) return d[mid] else return (d[mid] + d[mid-1]) / 2.0 }   function gnomeSortD( i) { for (i = 2; i <= length(d); i++) { if (d[i] < d[i-1]) gnomeSortBackD(i) } }   function gnomeSortBackD(i, t) { for (; i > 1 && d[i] < d[i-1]; i--) { t = d[i] d[i] = d[i-1] d[i-1] = t } }   function showD(p, i) { printf p for (i = 1; i <= length(d); i++) { printf d[i] " " } print "" }  
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
#Excel
Excel
  =AVERAGE(1;2;3;4;5;6;7;8;9;10) =GEOMEAN(1;2;3;4;5;6;7;8;9;10) =HARMEAN(1;2;3;4;5;6;7;8;9;10)  
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.
#Glagol
Glagol
ОТДЕЛ Сетунь+; ИСПОЛЬЗУЕТ Параметр ИЗ "...\Отделы\Обмен\", Текст ИЗ "...\Отделы\Числа\", Вывод ИЗ "...\Отделы\Обмен\"; ПЕР зч: РЯД 10 ИЗ ЗНАК; счпоз: ЦЕЛ; число: ЦЕЛ; память: ДОСТУП К НАБОР ячейки: РЯД 20 ИЗ ЦЕЛ; размер: УЗКЦЕЛ; отрицательное: КЛЮЧ КОН; ЗАДАЧА СоздатьПамять; УКАЗ СОЗДАТЬ(память); память.размер := 0; память.отрицательное := ОТКЛ КОН СоздатьПамять; ЗАДАЧА ДобавитьВПамять(что: ЦЕЛ); УКАЗ память.ячейки[память.размер] := что; УВЕЛИЧИТЬ(память.размер) КОН ДобавитьВПамять; ЗАДАЧА ОбратитьПамять; ПЕР зчсл: ЦЕЛ; сч: ЦЕЛ; УКАЗ ОТ сч := 0 ДО память.размер ДЕЛИТЬ 2 - 1 ВЫП зчсл := память.ячейки[сч]; память.ячейки[сч] := память.ячейки[память.размер-сч-1]; память.ячейки[память.размер-сч-1] := зчсл КОН КОН ОбратитьПамять; ЗАДАЧА ВывестиПамять; ПЕР сч: ЦЕЛ; УКАЗ ОТ сч := 0 ДО память.размер-1 ВЫП ЕСЛИ память.ячейки[сч] < 0 ТО Вывод.Цепь("-") АЕСЛИ память.ячейки[сч] > 0 ТО Вывод.Цепь("+") ИНАЧЕ Вывод.Цепь("0") КОН КОН КОН ВывестиПамять; ЗАДАЧА УдалитьПамять; УКАЗ память := ПУСТО КОН УдалитьПамять; ЗАДАЧА Перевести(число: ЦЕЛ); ПЕР о: ЦЕЛ; з: КЛЮЧ; ЗАДАЧА ВПамять(что: ЦЕЛ); УКАЗ ЕСЛИ память.отрицательное ТО ЕСЛИ что < 0 ТО ДобавитьВПамять(1) АЕСЛИ что > 0 ТО ДобавитьВПамять(-1) ИНАЧЕ ДобавитьВПамять(0) КОН ИНАЧЕ ДобавитьВПамять(что) КОН КОН ВПамять; УКАЗ ЕСЛИ число < 0 ТО память.отрицательное := ВКЛ КОН; число := МОДУЛЬ(число); з := ОТКЛ; ПОКА число > 0 ВЫП о := число ОСТАТОК 3; число := число ДЕЛИТЬ 3; ЕСЛИ з ТО ЕСЛИ о = 2 ТО ВПамять(0) АЕСЛИ о = 1 ТО ВПамять(-1) ИНАЧЕ ВПамять(1); з := ОТКЛ КОН ИНАЧЕ ЕСЛИ о = 2 ТО ВПамять(-1); з := ВКЛ ИНАЧЕ ВПамять(о) КОН КОН КОН; ЕСЛИ з ТО ВПамять(1) КОН; ОбратитьПамять; ВывестиПамять(ВКЛ); КОН Перевести; ЗАДАЧА ВЧисло(): ЦЕЛ; ПЕР сч, мн: ЦЕЛ; результат: ЦЕЛ; УКАЗ результат := 0; мн := 1; ОТ сч := 0 ДО память.размер-1 ВЫП УВЕЛИЧИТЬ(результат, память.ячейки[память.размер-сч-1]*мн); мн := мн * 3 КОН; ВОЗВРАТ результат КОН ВЧисло; УКАЗ Параметр.Текст(1, зч); счпоз := 0; число := Текст.ВЦел(зч, счпоз); СоздатьПамять; Перевести(число); Вывод.ЧЦел(" = %d.", ВЧисло(), 0, 0, 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.
#NewLisp
NewLisp
  ;;; Start by assigning n the integer square root of 269696 ;;; minus 1 to be even (setq n 518) ;;; Increment n by 2 till the last 6 digits of its square are 269696 (while (!= (% (* n n) 1000000) 269696) (++ n 2)) ;;; Show the result and its square (println n "^2 = " (* n 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
#BASIC
BASIC
DECLARE FUNCTION checkBrackets% (brackets AS STRING) DECLARE FUNCTION generator$ (length AS INTEGER)   RANDOMIZE TIMER   DO x$ = generator$ (10) PRINT x$, IF checkBrackets(x$) THEN PRINT "OK" ELSE PRINT "NOT OK" END IF LOOP WHILE LEN(x$)   FUNCTION checkBrackets% (brackets AS STRING) 'returns -1 (TRUE) if everything's ok, 0 (FALSE) if not DIM L0 AS INTEGER, sum AS INTEGER   FOR L0 = 1 TO LEN(brackets) SELECT CASE MID$(brackets, L0, 1) CASE "[" sum = sum + 1 CASE "]" sum = sum - 1 END SELECT IF sum < 0 THEN checkBrackets% = 0 EXIT FUNCTION END IF NEXT   IF 0 = sum THEN checkBrackets% = -1 ELSE checkBrackets% = 0 END IF END FUNCTION   FUNCTION generator$ (length AS INTEGER) z = INT(RND * length) IF z < 1 THEN generator$ = "": EXIT FUNCTION REDIM x(z * 2) AS STRING FOR i = 0 TO z STEP 2 x(i) = "[" x(i + 1) = "]" NEXT FOR i = 1 TO UBOUND(x) z = INT(RND * 2) IF z THEN SWAP x(i), x(i - 1) NEXT xx$ = "" FOR i = 0 TO UBOUND(x) xx$ = xx$ + x(i) NEXT generator$ = xx$ END FUNCTION
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
#Fortran
Fortran
program mode_test use Qsort_Module only Qsort => sort implicit none   integer, parameter :: S = 10 integer, dimension(S) :: a1 = (/ -1, 7, 7, 2, 2, 2, -1, 7, -3, -3 /) integer, dimension(S) :: a2 = (/ 1, 1, 1, 1, 1, 0, 2, 2, 2, 2 /) integer, dimension(S) :: a3 = (/ 0, 0, -1, -1, 9, 9, 3, 3, 7, 7 /)   integer, dimension(S) :: o integer :: l, trash   print *, stat_mode(a1)   trash = stat_mode(a1, o, l) print *, o(1:l) trash = stat_mode(a2, o, l) print *, o(1:l) trash = stat_mode(a3, o, l) print *, o(1:l)   contains   ! stat_mode returns the lowest (if not unique) mode ! others can hold other modes, if the mode is not unique ! if others is provided, otherslen should be provided too, and ! it says how many other modes are there. ! ok can be used to know if the return value has a meaning ! or the mode can't be found (void arrays) integer function stat_mode(a, others, otherslen, ok) integer, dimension(:), intent(in) :: a logical, optional, intent(out) :: ok integer, dimension(size(a,1)), optional, intent(out) :: others integer, optional, intent(out) :: otherslen   ! ta is a copy of a, we sort ta modifying it, freq ! holds the frequencies and idx the index (for ta) so that ! the value appearing freq(i)-time is ta(idx(i)) integer, dimension(size(a, 1)) :: ta, freq, idx integer :: rs, i, tm, ml, tf   if ( present(ok) ) ok = .false.   select case ( size(a, 1) ) case (0) ! no mode... ok is false return case (1) if ( present(ok) ) ok = .true. stat_mode = a(1) return case default if ( present(ok) ) ok = .true. ta = a ! copy the array call sort(ta) ! sort it in place (cfr. sort algos on RC) freq = 1 idx = 0 rs = 1 ! rs will be the number of different values   do i = 2, size(ta, 1) if ( ta(i-1) == ta(i) ) then freq(rs) = freq(rs) + 1 else idx(rs) = i-1 rs = rs + 1 end if end do idx(rs) = i-1   ml = maxloc(freq(1:rs), 1) ! index of the max value of freq tf = freq(ml) ! the max frequency tm = ta(idx(ml)) ! the value with that freq   ! if we want all the possible modes, we provide others if ( present(others) ) then i = 1 others(1) = tm do freq(ml) = 0 ml = maxloc(freq(1:rs), 1) if ( tf == freq(ml) ) then ! the same freq i = i + 1 ! as the max one others(i) = ta(idx(ml)) else exit end if end do   if ( present(otherslen) ) then otherslen = i end if   end if stat_mode = tm end select   end function stat_mode   end program mode_test
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#8th
8th
  : avg \ a -- avg(a) dup ' n:+ 0 a:reduce swap a:len nip n:/ ;   \ test: [ 1.0, 2.3, 1.1, 5.0, 3, 2.8, 2.01, 3.14159 ] avg . cr [ ] avg . cr [ 10 ] avg . cr bye  
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#ACL2
ACL2
(defun mean-r (xs) (if (endp xs) (mv 0 0) (mv-let (m j) (mean-r (rest xs)) (mv (+ (first xs) m) (+ j 1)))))   (defun mean (xs) (if (endp xs) 0 (mv-let (n d) (mean-r xs) (/ n d))))
http://rosettacode.org/wiki/Associative_array/Merging
Associative array/Merging
Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be: Key Value "name" "Rocket Skates" "price" 15.25 "color" "red" "year" 1974
#11l
11l
V base = [‘name’ = ‘Rocket Skates’, ‘price’ = ‘12.75’, ‘color’ = ‘yellow’] V update = [‘price’ = ‘15.25’, ‘color’ = ‘red’, ‘year’ = ‘1974’]   V result = copy(base) result.update(update)   print(result)
http://rosettacode.org/wiki/Average_loop_length
Average loop length
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence. Task Write a program or a script that estimates, for each N, the average length until the first such repetition. Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one. This problem comes from the end of Donald Knuth's Christmas tree lecture 2011. Example of expected output: N average analytical (error) === ========= ============ ========= 1 1.0000 1.0000 ( 0.00%) 2 1.4992 1.5000 ( 0.05%) 3 1.8784 1.8889 ( 0.56%) 4 2.2316 2.2188 ( 0.58%) 5 2.4982 2.5104 ( 0.49%) 6 2.7897 2.7747 ( 0.54%) 7 3.0153 3.0181 ( 0.09%) 8 3.2429 3.2450 ( 0.07%) 9 3.4536 3.4583 ( 0.14%) 10 3.6649 3.6602 ( 0.13%) 11 3.8091 3.8524 ( 1.12%) 12 3.9986 4.0361 ( 0.93%) 13 4.2074 4.2123 ( 0.12%) 14 4.3711 4.3820 ( 0.25%) 15 4.5275 4.5458 ( 0.40%) 16 4.6755 4.7043 ( 0.61%) 17 4.8877 4.8579 ( 0.61%) 18 4.9951 5.0071 ( 0.24%) 19 5.1312 5.1522 ( 0.41%) 20 5.2699 5.2936 ( 0.45%)
#C.23
C#
public class AverageLoopLength { private static int N = 100000;   private static double analytical(int n) { double[] factorial = new double[n + 1]; double[] powers = new double[n + 1]; powers[0] = 1.0; factorial[0] = 1.0; for (int i = 1; i <= n; i++) { factorial[i] = factorial[i - 1] * i; powers[i] = powers[i - 1] * n; } double sum = 0;   for (int i = 1; i <= n; i++) { sum += factorial[n] / factorial[n - i] / powers[i]; } return sum; }   private static double average(int n) { Random rnd = new Random(); double sum = 0.0; for (int a = 0; a < N; a++) { int[] random = new int[n]; for (int i = 0; i < n; i++) { random[i] = rnd.Next(n); } var seen = new HashSet<double>(n); int current = 0; int length = 0; while (seen.Add(current)) { length++; current = random[current]; } sum += length; } return sum / N; }   public static void Main(string[] args) { Console.WriteLine(" N average analytical (error)"); Console.WriteLine("=== ========= ============ ========="); for (int i = 1; i <= 20; i++) { var average = AverageLoopLength.average(i); var analytical = AverageLoopLength.analytical(i); Console.WriteLine("{0,3} {1,10:N4} {2,13:N4} {3,8:N2}%", i, average, analytical, (analytical - average) / analytical * 100); } } }  
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
#Perl
Perl
sub sma_generator { my $period = shift; my (@list, $sum);   return sub { my $number = shift; push @list, $number; $sum += $number; $sum -= shift @list if @list > $period; return $sum / @list; } }   # Usage: my $sma = sma_generator(3); for (1, 2, 3, 2, 7) { printf "append $_ --> sma = %.2f (with period 3)\n", $sma->($_); }
http://rosettacode.org/wiki/Attractive_numbers
Attractive numbers
A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show sequence items up to   120. Reference   The OEIS entry:   A063989: Numbers with a prime number of prime divisors.
#ALGOL_W
ALGOL W
% find some attractive numbers - numbers whose prime factor count is prime  % begin  % implements the sieve of Eratosthenes  %  % s(i) is set to true if i is prime, false otherwise  %  % algol W doesn't have a upb operator, so we pass the size of the  %  % array in n  % procedure sieve( logical array s ( * ); integer value n ) ; begin  % start with everything flagged as prime  % for i := 1 until n do s( i ) := true;  % sieve out the non-primes  % s( 1 ) := false; for i := 2 until truncate( sqrt( n ) ) do begin if s( i ) then for p := i * i step i until n do s( p ) := false end for_i ; end sieve ;  % returns the count of prime factors of n, using the sieve of primes s  %  % n must be greater than 0  % integer procedure countPrimeFactors ( integer value n; logical array s ( * ) ) ; if s( n ) then 1 else begin integer count, rest; rest  := n; count := 0; while rest rem 2 = 0 do begin count := count + 1; rest  := rest div 2 end while_divisible_by_2 ; for factor := 3 step 2 until n - 1 do begin if s( factor ) then begin while rest > 1 and rest rem factor = 0 do begin count := count + 1; rest  := rest div factor end while_divisible_by_factor end if_prime_factor end for_factor ; count end countPrimeFactors ;  % maximum number for the task  % integer maxNumber; maxNumber := 120;  % show the attractive numbers  % begin logical array s ( 1 :: maxNumber ); sieve( s, maxNumber ); i_w := 2; % set output field width  % s_w := 1; % and output separator width  %  % find and display the attractive numbers  % for i := 2 until maxNumber do if s( countPrimeFactors( i, s ) ) then writeon( i ) end end.
http://rosettacode.org/wiki/Attractive_numbers
Attractive numbers
A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show sequence items up to   120. Reference   The OEIS entry:   A063989: Numbers with a prime number of prime divisors.
#AppleScript
AppleScript
on isPrime(n) if (n < 4) then return (n > 1) if ((n mod 2 is 0) or (n mod 3 is 0)) then return false repeat with i from 5 to (n ^ 0.5) div 1 by 6 if ((n mod i is 0) or (n mod (i + 2) is 0)) then return false end repeat   return true end isPrime   on primeFactorCount(n) set x to n set counter to 0 if (n > 1) then repeat while (n mod 2 = 0) set counter to counter + 1 set n to n div 2 end repeat repeat while (n mod 3 = 0) set counter to counter + 1 set n to n div 3 end repeat set i to 5 set limit to (n ^ 0.5) div 1 repeat until (i > limit) repeat while (n mod i = 0) set counter to counter + 1 set n to n div i end repeat tell (i + 2) to repeat while (n mod it = 0) set counter to counter + 1 set n to n div it end repeat set i to i + 6 set limit to (n ^ 0.5) div 1 end repeat if (n > 1) then set counter to counter + 1 end if   return counter end primeFactorCount   -- Task code: local output, n set output to {} repeat with n from 1 to 120 if (isPrime(primeFactorCount(n))) then set end of output to n end repeat return output
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
#Euphoria
Euphoria
  include std/console.e include std/math.e include std/mathcons.e include std/sequence.e include std/get.e   function T2D(sequence TimeSeq) return (360 * TimeSeq[1] / 24 + 360 * TimeSeq[2] / (24 * 60) + 360 * TimeSeq[3] / (24 * 3600)) end function   function D2T(atom angle) sequence TimeSeq = {0,0,0} atom seconds = 24 * 60 * 60 * angle / 360   TimeSeq[3] = mod(seconds,60) TimeSeq[2] = (mod(seconds,3600) - TimeSeq[3]) / 60 TimeSeq[1] = seconds / 3600   return TimeSeq end function   function MeanAngle(sequence angles) atom x = 0, y = 0 integer l = length(angles)   for i = 1 to length(angles) do x += cos(angles[i] * PI / 180) y += sin(angles[i] * PI / 180) end for   return atan2(y / l, x / l) * 180 / PI end function   sequence TimeEntry, TimeList = {}, TimeSeq   puts(1,"Enter times. Enter with no input to end\n") while 1 do TimeEntry = prompt_string("") if equal(TimeEntry,"") then -- no more entries for i = 1 to length(TimeList) do TimeList[i] = split(TimeList[i],":") -- split the times into sequences for j = 1 to 3 do TimeList[i][j] = defaulted_value(TimeList[i][j],0) -- convert to numerical values end for end for exit end if TimeList = append(TimeList,TimeEntry) end while   sequence AngleList = repeat({},length(TimeList))   for i = 1 to length(AngleList) do AngleList[i] = T2D(TimeList[i]) end for   sequence MeanTime = D2T(360+MeanAngle(AngleList))   printf(1,"\nMean Time: %d:%d:%d\n",MeanTime)     if getc(0) then end if  
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.
#Common_Lisp
Common Lisp
(defpackage :avl-tree (:use :cl) (:export :avl-tree :make-avl-tree :avl-tree-count :avl-tree-p :avl-tree-key<= :gettree :remtree :clrtree :dfs-maptree :bfs-maptree))   (in-package :avl-tree)   (defstruct %tree key value (height 0 :type fixnum) left right)   (defstruct (avl-tree (:constructor %make-avl-tree)) key<= tree (count 0 :type fixnum))   (defun make-avl-tree (key<=) "Create a new AVL tree using the given comparison function KEY<= for emplacing keys into the tree." (%make-avl-tree :key<= key<=))   (declaim (inline recalc-height height balance swap-kv right-right-rotate right-left-rotate left-right-rotate left-left-rotate rotate))   (defun recalc-height (tree) "Calculate the new height of the tree from the heights of the children." (when tree (setf (%tree-height tree) (1+ (the fixnum (max (height (%tree-right tree)) (height (%tree-left tree))))))))   (declaim (ftype (function (t) fixnum) height balance)) (defun height (tree) (if tree (%tree-height tree) 0))   (defun balance (tree) (if tree (- (height (%tree-right tree)) (height (%tree-left tree))) 0))   (defmacro swap (place-a place-b) "Swap the values of two places." (let ((tmp (gensym))) `(let ((,tmp ,place-a)) (setf ,place-a ,place-b) (setf ,place-b ,tmp))))   (defun swap-kv (tree-a tree-b) "Swap the keys and values of two trees." (swap (%tree-value tree-a) (%tree-value tree-b)) (swap (%tree-key tree-a) (%tree-key tree-b)))   ;; We should really use gensyms for the variables in here. (defmacro slash-rotate (tree right left) "Rotate nodes in a slash `/` imbalance." `(let* ((a ,tree) (b (,right a)) (c (,right b)) (a-left (,left a)) (b-left (,left b))) (setf (,right a) c) (setf (,left a) b) (setf (,left b) a-left) (setf (,right b) b-left) (swap-kv a b) (recalc-height b) (recalc-height a)))   (defmacro angle-rotate (tree right left) "Rotate nodes in an angle bracket `<` imbalance." `(let* ((a ,tree) (b (,right a)) (c (,left b)) (a-left (,left a)) (c-left (,left c)) (c-right (,right c))) (setf (,left a) c) (setf (,left c) a-left) (setf (,right c) c-left) (setf (,left b) c-right) (swap-kv a c) (recalc-height c) (recalc-height b) (recalc-height a)))   (defun right-right-rotate (tree) (slash-rotate tree %tree-right %tree-left))   (defun left-left-rotate (tree) (slash-rotate tree %tree-left %tree-right))   (defun right-left-rotate (tree) (angle-rotate tree %tree-right %tree-left))   (defun left-right-rotate (tree) (angle-rotate tree %tree-left %tree-right))   (defun rotate (tree) (declare (type %tree tree)) "Perform a rotation on the given TREE if it is imbalanced." (recalc-height tree) (with-slots (left right) tree (let ((balance (balance tree))) (cond ((< 1 balance) ;; Right imbalanced tree (if (<= 0 (balance right)) (right-right-rotate tree) (right-left-rotate tree))) ((> -1 balance) ;; Left imbalanced tree (if (<= 0 (balance left)) (left-right-rotate tree) (left-left-rotate tree)))))))   (defun gettree (key avl-tree &optional default) "Finds an entry in AVL-TREE whos key is KEY and returns the associated value and T as multiple values, or returns DEFAULT and NIL if there was no such entry. Entries can be added using SETF." (with-slots (key<= tree) avl-tree (labels ((rec (tree) (if tree (with-slots ((t-key key) left right value) tree (if (funcall key<= t-key key) (if (funcall key<= key t-key) (values value t) (rec right)) (rec left))) (values default nil)))) (rec tree))))   (defun puttree (value key avl-tree) ;;(declare (optimize speed)) (declare (type avl-tree avl-tree)) "Emplace the the VALUE with the given KEY into the AVL-TREE, or overwrite the value if the given key already exists." (let ((node (make-%tree :key key :value value))) (with-slots (key<= tree count) avl-tree (cond (tree (labels ((rec (tree) (with-slots ((t-key key) left right) tree (if (funcall key<= t-key key) (if (funcall key<= key t-key) (setf (%tree-value tree) value) (cond (right (rec right)) (t (setf right node) (incf count)))) (cond (left (rec left)) (t (setf left node) (incf count)))) (rotate tree)))) (rec tree))) (t (setf tree node) (incf count)))) value))   (defun (setf gettree) (value key avl-tree &optional default) (declare (ignore default)) (puttree value key avl-tree))   (defun remtree (key avl-tree) (declare (type avl-tree avl-tree)) "Remove the entry in AVL-TREE associated with KEY. Return T if there was such an entry, or NIL if not." (with-slots (key<= tree count) avl-tree (labels ((find-left (tree) (with-slots ((t-key key) left right) tree (if left (find-left left) tree))) (rec (tree &optional parent type) (when tree (prog1 (with-slots ((t-key key) left right) tree (if (funcall key<= t-key key) (cond ((funcall key<= key t-key) (cond ((and left right) (let ((sub-left (find-left right))) (swap-kv sub-left tree) (rec right tree :right))) (t (let ((sub (or left right))) (case type (:right (setf (%tree-right parent) sub)) (:left (setf (%tree-left parent) sub)) (nil (setf (avl-tree-tree avl-tree) sub)))) (decf count))) t) (t (rec right tree :right))) (rec left tree :left))) (when parent (rotate parent)))))) (rec tree))))   (defun clrtree (avl-tree) "This removes all the entries from AVL-TREE and returns the tree itself." (setf (avl-tree-tree avl-tree) nil) (setf (avl-tree-count avl-tree) 0) avl-tree)   (defun dfs-maptree (function avl-tree) "For each entry in AVL-TREE call the two-argument FUNCTION on the key and value of each entry in depth-first order from left to right. Consequences are undefined if AVL-TREE is modified during this call." (with-slots (key<= tree) avl-tree (labels ((rec (tree) (when tree (with-slots ((t-key key) left right key value) tree (rec left) (funcall function key value) (rec right))))) (rec tree))))   (defun bfs-maptree (function avl-tree) "For each entry in AVL-TREE call the two-argument FUNCTION on the key and value of each entry in breadth-first order from left to right. Consequences are undefined if AVL-TREE is modified during this call." (with-slots (key<= tree) avl-tree (let* ((queue (cons nil nil)) (end queue)) (labels ((pushend (value) (when value (setf (cdr end) (cons value nil)) (setf end (cdr end)))) (empty-p () (eq nil (cdr queue))) (popfront () (prog1 (pop (cdr queue)) (when (empty-p) (setf end queue))))) (when tree (pushend tree) (loop until (empty-p) do (let ((current (popfront))) (with-slots (key value left right) current (funcall function key value) (pushend left) (pushend right)))))))))   (defun test () (let ((tree (make-avl-tree #'<=)) (printer (lambda (k v) (print (list k v))))) (loop for key in '(0 8 6 4 2 3 7 9 1 5 5) for value in '(a b c d e f g h i j k) do (setf (gettree key tree) value)) (loop for key in '(0 1 2 3 4 10) do (print (multiple-value-list (gettree key tree)))) (terpri) (print tree) (terpri) (dfs-maptree printer tree) (terpri) (bfs-maptree printer tree) (terpri) (loop for key in '(0 1 2 3 10 7) do (print (remtree key tree))) (terpri) (print tree) (terpri) (clrtree tree) (print tree)) (values))   (defun profile-test () (let ((tree (make-avl-tree #'<=)) (randoms (loop repeat 1000000 collect (random 100.0)))) (loop for key in randoms do (setf (gettree key tree) key))))
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
#D
D
import std.stdio, std.algorithm, std.complex; import std.math: PI;   auto radians(T)(in T d) pure nothrow @nogc { return d * PI / 180; } auto degrees(T)(in T r) pure nothrow @nogc { return r * 180 / PI; }   real meanAngle(T)(in T[] D) pure nothrow @nogc { immutable t = reduce!((a, d) => a + d.radians.expi)(0.complex, D); return (t / D.length).arg.degrees; }   void main() { foreach (angles; [[350, 10], [90, 180, 270, 360], [10, 20, 30]]) writefln("The mean angle of %s is: %.2f degrees", angles, angles.meanAngle); }
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
#BaCon
BaCon
DECLARE a[] = { 4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2 } TYPE FLOATING DECLARE b[] = { 4.1, 7.2, 1.7, 9.3, 4.4, 3.2 } TYPE FLOATING   DEF FN Dim(x) = SIZEOF(x) / SIZEOF(double)   DEF FN Median(x) = IIF(ODD(Dim(x)), x[(Dim(x)-1)/2], (x[Dim(x)/2-1]+x[Dim(x)/2])/2 )   SORT a PRINT "Median of a: ", Median(a)   SORT b PRINT "Median of b: ", Median(b)
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of positive integers. The most common of the three means, the arithmetic mean, is the sum of the list divided by its length: A ( x 1 , … , x n ) = x 1 + ⋯ + x n n {\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}} The geometric mean is the n {\displaystyle n} th root of the product of the list: G ( x 1 , … , x n ) = x 1 ⋯ x n n {\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}} The harmonic mean is n {\displaystyle n} divided by the sum of the reciprocal of each item in the list: H ( x 1 , … , x n ) = n 1 x 1 + ⋯ + 1 x n {\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}} See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#F.23
F#
let P = [1.0; 2.0; 3.0; 4.0; 5.0; 6.0; 7.0; 8.0; 9.0; 10.0]   let arithmeticMean (x : float list) = x |> List.sum |> (fun acc -> acc / float (List.length(x)))   let geometricMean (x: float list) = x |> List.reduce (*) |> (fun acc -> Math.Pow(acc, 1.0 / (float (List.length(x)))))   let harmonicMean (x: float list) = x |> List.map (fun a -> 1.0 / a) |> List.sum |> (fun acc -> float (List.length(x)) / acc)   printfn "Arithmetic Mean: %A" (arithmeticMean P) printfn "Geometric Mean: %A" (geometricMean P) printfn "Harmonic Mean: %A" (harmonicMean P)
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.
#Go
Go
package main   import ( "fmt" "strings" )   // R1: representation is a slice of int8 digits of -1, 0, or 1. // digit at index 0 is least significant. zero value of type is // representation of the number 0. type bt []int8   // R2: string conversion:   // btString is a constructor. valid input is a string of any length // consisting of only '+', '-', and '0' characters. // leading zeros are allowed but are trimmed and not represented. // false return means input was invalid. func btString(s string) (*bt, bool) { s = strings.TrimLeft(s, "0") b := make(bt, len(s)) for i, last := 0, len(s)-1; i < len(s); i++ { switch s[i] { case '-': b[last-i] = -1 case '0': b[last-i] = 0 case '+': b[last-i] = 1 default: return nil, false } } return &b, true }   // String method converts the other direction, returning a string of // '+', '-', and '0' characters representing the number. func (b bt) String() string { if len(b) == 0 { return "0" } last := len(b) - 1 r := make([]byte, len(b)) for i, d := range b { r[last-i] = "-0+"[d+1] } return string(r) }   // R3: integer conversion // int chosen as "native integer"   // btInt is a constructor like btString. func btInt(i int) *bt { if i == 0 { return new(bt) } var b bt var btDigit func(int) btDigit = func(digit int) { m := int8(i % 3) i /= 3 switch m { case 2: m = -1 i++ case -2: m = 1 i-- } if i == 0 { b = make(bt, digit+1) } else { btDigit(digit + 1) } b[digit] = m } btDigit(0) return &b }   // Int method converts the other way, returning the value as an int type. // !ok means overflow occurred during conversion, not necessarily that the // value is not representable as an int. (Of course there are other ways // of doing it but this was chosen as "reasonable.") func (b bt) Int() (r int, ok bool) { pt := 1 for _, d := range b { dp := int(d) * pt neg := r < 0 r += dp if neg { if r > dp { return 0, false } } else { if r < dp { return 0, false } } pt *= 3 } return r, true }   // R4: negation, addition, and multiplication   func (z *bt) Neg(b *bt) *bt { if z != b { if cap(*z) < len(*b) { *z = make(bt, len(*b)) } else { *z = (*z)[:len(*b)] } } for i, d := range *b { (*z)[i] = -d } return z }   func (z *bt) Add(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } r := *z r = r[:cap(r)] var carry int8 for i, da := range *a { if i == len(r) { n := make(bt, len(*a)+4) copy(n, r) r = n } sum := da + carry if i < len(*b) { sum += (*b)[i] } carry = sum / 3 sum %= 3 switch { case sum > 1: sum -= 3 carry++ case sum < -1: sum += 3 carry-- } r[i] = sum } last := len(*a) if carry != 0 { if len(r) == last { n := make(bt, last+4) copy(n, r) r = n } r[last] = carry *z = r[:last+1] return z } for { if last == 0 { *z = nil break } last-- if r[last] != 0 { *z = r[:last+1] break } } return z }   func (z *bt) Mul(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } var na bt for _, d := range *b { if d == -1 { na.Neg(a) break } } r := make(bt, len(*a)+len(*b)) for i := len(*b) - 1; i >= 0; i-- { switch (*b)[i] { case 1: p := r[i:] p.Add(&p, a) case -1: p := r[i:] p.Add(&p, &na) } } i := len(r) for i > 0 && r[i-1] == 0 { i-- } *z = r[:i] return z }   func main() { a, _ := btString("+-0++0+") b := btInt(-436) c, _ := btString("+-++-") show("a:", a) show("b:", b) show("c:", c) show("a(b-c):", a.Mul(a, b.Add(b, c.Neg(c)))) }   func show(label string, b *bt) { fmt.Printf("%7s %12v ", label, b) if i, ok := b.Int(); ok { fmt.Printf("%7d\n", i) } else { fmt.Println("int overflow") } }
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.
#Nim
Nim
  var n : int = 0 while n*n mod 1_000_000 != 269_696: inc(n) echo 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.
#Objeck
Objeck
class Babbage { function : Main(args : String[]) ~ Nil { cur := 0; do { cur++; } while(cur * cur % 1000000 <> 269696);   cur_sqr := cur * cur; "The square of {$cur} is {$cur_sqr}!"->PrintLine(); } }  
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
#BASIC256
BASIC256
s$ = "[[]][]" print s$; " = ";   if not check_brackets(s$) then print "not "; print "ok" end   function check_brackets(s$) level = 0 for i = 1 to length(s$) c$ = mid(s$, i, 1) begin case case c$ = "[" level = level + 1 case c$ = "]" level = level - 1 if level < 0 then exit for end case next i return level = 0 end function
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
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Sub quicksort(a() As Integer, first As Integer, last As Integer) Dim As Integer length = last - first + 1 If length < 2 Then Return Dim pivot As Integer = a(first + length\ 2) Dim lft As Integer = first Dim rgt As Integer = last While lft <= rgt While a(lft) < pivot lft +=1 Wend While a(rgt) > pivot rgt -= 1 Wend If lft <= rgt Then Swap a(lft), a(rgt) lft += 1 rgt -= 1 End If Wend quicksort(a(), first, rgt) quicksort(a(), lft, last) End Sub   ' The modal value(s) is/are stored in 'm'. ' The function returns the modal count. Function mode(a() As Integer, m() As Integer, sorted As Boolean = false) As Integer Dim lb As Integer = LBound(a) Dim ub As Integer = UBound(a) If ub = -1 Then Return 0 '' empty array If Not sorted Then quicksort(a(), lb, ub) Dim cValue As Integer = a(lb) Dim cCount As Integer = 1 Dim cMax As Integer = 0 '' We iterate to the end of the array plus 1 to ensure the '' final value is dealt with properly For i As Integer = lb + 1 To ub + 1 If i <= ub AndAlso a(i) = cValue Then cCount += 1 Else If cCount > cMax Then Erase m Redim m(1 To 1) m(1) = cValue cMax = cCount ElseIf cCount = cMax Then Redim Preserve m(1 To UBound(m) + 1) m(UBound(m)) = cValue End If If i = ub + 1 Then Exit For cValue = a(i) cCount = 1 End If Next Return cMax End Function   Dim a(1 To 14) As Integer = {1, 2, 3, 1, 2, 4, 2, 5, 2, 3, 3, 1, 3, 6} Dim m() As Integer '' to store the mode(s) Dim mCount As Integer = mode(a(), m()) Print "The following are the modes which occur"; mCount; " times : " For i As Integer = LBound(m) To UBound(m) : Print m(i); " "; : Next Print Print "Press any key to quit" Sleep
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#Action.21
Action!
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit   PROC Mean(INT ARRAY a INT count REAL POINTER result) INT i REAL x,sum,tmp   IntToReal(0,sum) FOR i=0 TO count-1 DO IntToReal(a(i),x) RealAdd(sum,x,tmp) RealAssign(tmp,sum) OD IntToReal(count,tmp) RealDiv(sum,tmp,result) RETURN   PROC Test(INT ARRAY a INT count) INT i REAL result   Mean(a,count,result) Print("mean(") FOR i=0 TO count-1 DO PrintI(a(i)) IF i<count-1 THEN Put(',) FI OD Print(")=") PrintRE(result) RETURN   PROC Main() INT ARRAY a1=[1 2 3 4 5 6] INT ARRAY a2=[1 10 100 1000 10000] INT ARRAY a3=[9]   Put(125) PutE() ;clear screen Test(a1,6) Test(a2,5) Test(a3,1) Test(a3,0) RETURN
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#ActionScript
ActionScript
function mean(vector:Vector.<Number>):Number { var sum:Number = 0; for(var i:uint = 0; i < vector.length; i++) sum += vector[i]; return vector.length == 0 ? 0 : sum / vector.length; }
http://rosettacode.org/wiki/Associative_array/Merging
Associative array/Merging
Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be: Key Value "name" "Rocket Skates" "price" 15.25 "color" "red" "year" 1974
#Ada
Ada
with Ada.Text_Io; with Ada.Containers.Indefinite_Ordered_Maps;   procedure Merge_Maps is use Ada.Text_Io;   type Key_Type is new String; type Value_Type is new String;   package Maps is new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => Key_Type, Element_Type => Value_Type); use Maps;   function Merge (Original : Map; Update : Map) return Map is Result : Map  := Original; Cur  : Cursor := Update.First; begin while Has_Element (Cur) loop if Original.Contains (Key (Cur)) then Result.Replace_Element (Result.Find (Key (Cur)), Element (Cur)); else Result.Insert (Key (Cur), Element (Cur)); end if; Next (Cur); end loop; return Result; end Merge;   procedure Put_Map (M : Map) is Cur : Cursor := M.First; begin while Has_Element (Cur) loop Put (String (Key (Cur))); Set_Col (12); Put (String (Element (Cur))); New_Line; Next (Cur); end loop; end Put_Map;   Original : Map; Update  : Map; Result  : Map; begin Original.Insert ("name", "Rocket Skates"); Original.Insert ("price", "12.75"); Original.Insert ("color", "yellow");   Update.Insert ("price", "15.25"); Update.Insert ("color", "red"); Update.Insert ("year", "1974");   Result := Merge (Original, Update);   Put_Line ("Original:"); Put_Map (Original); New_Line;   Put_Line ("Update:"); Put_Map (Update); New_Line;   Put_Line ("Result of merge:"); Put_Map (Result); New_Line;   end Merge_Maps;
http://rosettacode.org/wiki/Associative_array/Merging
Associative array/Merging
Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be: Key Value "name" "Rocket Skates" "price" 15.25 "color" "red" "year" 1974
#ALGOL_68
ALGOL 68
# associative array merging #   # the modes allowed as associative array element values - change to suit # MODE AAVALUE = UNION( STRING, INT, REAL ); # the modes allowed as associative array element keys - change to suit # MODE AAKEY = STRING; # initial value for an array element # AAVALUE init element value = "";   # include the associative array code # PR read "aArrayBase.a68" PR   # adds or replaces all elements from b into a # PRIO UPDATE = 9; OP UPDATE = ( REF AARRAY a, REF AARRAY b )REF AARRAY: BEGIN REF AAELEMENT e := FIRST b; WHILE e ISNT nil element DO a // key OF e := value OF e; e := NEXT b OD; a END # UPDATE # ;   # construct the associative arrays for the task # REF AARRAY a := INIT LOC AARRAY; REF AARRAY b := INIT LOC AARRAY; a // "name" := "Rocket Skates"; a // "price" := 12.75; a // "color" := "yellow"; b // "price" := 15.25; b // "color" := "red"; b // "year" := 1974; # merge the arrays # REF AARRAY c := INIT LOC AARRAY; c UPDATE a UPDATE b; # show the merged array # REF AAELEMENT e := FIRST c; WHILE e ISNT nil element DO print( ( key OF e , ": " , CASE value OF e IN (STRING s): s , (INT i): whole( i, 0 ) , (REAL r): fixed( r, -12, 2 ) OUT "????" ESAC , newline ) ); e := NEXT c OD
http://rosettacode.org/wiki/Average_loop_length
Average loop length
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence. Task Write a program or a script that estimates, for each N, the average length until the first such repetition. Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one. This problem comes from the end of Donald Knuth's Christmas tree lecture 2011. Example of expected output: N average analytical (error) === ========= ============ ========= 1 1.0000 1.0000 ( 0.00%) 2 1.4992 1.5000 ( 0.05%) 3 1.8784 1.8889 ( 0.56%) 4 2.2316 2.2188 ( 0.58%) 5 2.4982 2.5104 ( 0.49%) 6 2.7897 2.7747 ( 0.54%) 7 3.0153 3.0181 ( 0.09%) 8 3.2429 3.2450 ( 0.07%) 9 3.4536 3.4583 ( 0.14%) 10 3.6649 3.6602 ( 0.13%) 11 3.8091 3.8524 ( 1.12%) 12 3.9986 4.0361 ( 0.93%) 13 4.2074 4.2123 ( 0.12%) 14 4.3711 4.3820 ( 0.25%) 15 4.5275 4.5458 ( 0.40%) 16 4.6755 4.7043 ( 0.61%) 17 4.8877 4.8579 ( 0.61%) 18 4.9951 5.0071 ( 0.24%) 19 5.1312 5.1522 ( 0.41%) 20 5.2699 5.2936 ( 0.45%)
#C.2B.2B
C++
#include <random> #include <vector> #include <iostream>   #define MAX_N 20 #define TIMES 1000000   /** * Used to generate a uniform random distribution */ static std::random_device rd; //Will be used to obtain a seed for the random number engine static std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd() static std::uniform_int_distribution<> dis;   int randint(int n) { int r, rmax = RAND_MAX / n * n; dis=std::uniform_int_distribution(0,rmax) ; r = dis(gen); return r / (RAND_MAX / n); }   unsigned long factorial(size_t n) { //Factorial using dynamic programming to memoize the values. static std::vector<unsigned long>factorials{1,1,2}; for (;factorials.size() <= n;) factorials.push_back(factorials.back()*factorials.size()); return factorials[n]; }   long double expected(size_t n) { long double sum = 0; for (size_t i = 1; i <= n; i++) sum += factorial(n) / pow(n, i) / factorial(n - i); return sum; }   int test(int n, int times) { int i, count = 0; for (i = 0; i < times; i++) { unsigned int x = 1, bits = 0; while (!(bits & x)) { count++; bits |= x; x = static_cast<unsigned int>(1 << randint(n)); } } return count; }   int main() { puts(" n\tavg\texp.\tdiff\n-------------------------------");   int n; for (n = 1; n <= MAX_N; n++) { int cnt = test(n, TIMES); long double avg = (double)cnt / TIMES; long double theory = expected(static_cast<size_t>(n)); long double diff = (avg / theory - 1) * 100; printf("%2d %8.4f %8.4f %6.3f%%\n", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff)); } 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
#Phix
Phix
with javascript_semantics sequence sma = {} -- ((period,history,circnxt)) (private to sma.e) integer sma_free = 0 global function new_sma(integer period) integer res if sma_free then res = sma_free sma_free = sma[sma_free] sma[res] = {period,{},0} else sma = append(sma,{period,{},0}) res = length(sma) end if return res end function global procedure add_sma(integer sidx, atom val) integer period, circnxt sequence history {period,history,circnxt} = sma[sidx] sma[sidx][2] = 0 -- (kill refcount) if length(history)<period then history = append(history,val) else circnxt += 1 if circnxt>period then circnxt = 1 end if sma[sidx][3] = circnxt history[circnxt] = val end if sma[sidx][2] = history end procedure global function get_sma_average(integer sidx) sequence history = sma[sidx][2] integer l = length(history) if l=0 then return 0 end if return sum(history)/l end function global function moving_average(integer sidx, atom val) add_sma(sidx,val) return get_sma_average(sidx) end function global procedure free_sma(integer sidx) sma[sidx] = sma_free sma_free = sidx end procedure
http://rosettacode.org/wiki/Attractive_numbers
Attractive numbers
A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show sequence items up to   120. Reference   The OEIS entry:   A063989: Numbers with a prime number of prime divisors.
#Arturo
Arturo
attractive?: function [x] -> prime? size factors.prime x   print select 1..120 => attractive?
http://rosettacode.org/wiki/Attractive_numbers
Attractive numbers
A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show sequence items up to   120. Reference   The OEIS entry:   A063989: Numbers with a prime number of prime divisors.
#AWK
AWK
  # syntax: GAWK -f ATTRACTIVE_NUMBERS.AWK # converted from C BEGIN { limit = 120 printf("attractive numbers from 1-%d:\n",limit) for (i=1; i<=limit; i++) { n = count_prime_factors(i) if (is_prime(n)) { printf("%d ",i) } } printf("\n") exit(0) } function count_prime_factors(n, count,f) { f = 2 if (n == 1) { return(0) } if (is_prime(n)) { return(1) } while (1) { if (!(n % f)) { count++ n /= f if (n == 1) { return(count) } if (is_prime(n)) { f = n } } else if (f >= 3) { f += 2 } else { f = 3 } } } function is_prime(x, i) { if (x <= 1) { return(0) } for (i=2; i<=int(sqrt(x)); i++) { if (x % i == 0) { return(0) } } return(1) }  
http://rosettacode.org/wiki/Averages/Mean_time_of_day
Averages/Mean time of day
Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ideas of Averages/Mean angle compute and show the average time of the nocturnal activity to an accuracy of one second of time. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#F.23
F#
open System open System.Numerics   let deg2rad d = d * Math.PI / 180. let rad2deg r = r * 180. / Math.PI let makeComplex = fun r -> Complex.FromPolarCoordinates(1., r) // 1 msec = 10000 ticks let time2deg = TimeSpan.Parse >> (fun ts -> ts.Ticks) >> (float) >> (*) (10e-9/24.) let deg2time = (*) (24. * 10e7) >> (int64) >> TimeSpan   [<EntryPoint>] let main argv = let msg = "Average time for [" + (String.Join("; ",argv)) + "] is" argv |> Seq.map (time2deg >> deg2rad >> makeComplex) |> Seq.fold (fun x y -> Complex.Add(x,y)) Complex.Zero |> fun c -> c.Phase |> rad2deg |> fun d -> if d < 0. then d + 360. else d |> deg2time |> fun t -> t.ToString(@"hh\:mm\:ss") |> printfn "%s: %s" msg 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.
#D
D
import std.stdio, std.algorithm;   class AVLtree { private Node* root;   private static struct Node { private int key, balance; private Node* left, right, parent;   this(in int k, Node* p) pure nothrow @safe @nogc { key = k; parent = p; } }   public bool insert(in int key) pure nothrow @safe { if (root is null) root = new Node(key, null); else { Node* n = root; Node* parent; while (true) { if (n.key == key) return false;   parent = n;   bool goLeft = n.key > key; n = goLeft ? n.left : n.right;   if (n is null) { if (goLeft) { parent.left = new Node(key, parent); } else { parent.right = new Node(key, parent); } rebalance(parent); break; } } } return true; }   public void deleteKey(in int delKey) pure nothrow @safe @nogc { if (root is null) return; Node* n = root; Node* parent = root; Node* delNode = null; Node* child = root;   while (child !is null) { parent = n; n = child; child = delKey >= n.key ? n.right : n.left; if (delKey == n.key) delNode = n; }   if (delNode !is null) { delNode.key = n.key;   child = n.left !is null ? n.left : n.right;   if (root.key == delKey) { root = child; } else { if (parent.left is n) { parent.left = child; } else { parent.right = child; } rebalance(parent); } } }   private void rebalance(Node* n) pure nothrow @safe @nogc { setBalance(n);   if (n.balance == -2) { if (height(n.left.left) >= height(n.left.right)) n = rotateRight(n); else n = rotateLeftThenRight(n);   } else if (n.balance == 2) { if (height(n.right.right) >= height(n.right.left)) n = rotateLeft(n); else n = rotateRightThenLeft(n); }   if (n.parent !is null) { rebalance(n.parent); } else { root = n; } }   private Node* rotateLeft(Node* a) pure nothrow @safe @nogc { Node* b = a.right; b.parent = a.parent;   a.right = b.left;   if (a.right !is null) a.right.parent = a;   b.left = a; a.parent = b;   if (b.parent !is null) { if (b.parent.right is a) { b.parent.right = b; } else { b.parent.left = b; } }   setBalance(a, b);   return b; }   private Node* rotateRight(Node* a) pure nothrow @safe @nogc { Node* b = a.left; b.parent = a.parent;   a.left = b.right;   if (a.left !is null) a.left.parent = a;   b.right = a; a.parent = b;   if (b.parent !is null) { if (b.parent.right is a) { b.parent.right = b; } else { b.parent.left = b; } }   setBalance(a, b);   return b; }   private Node* rotateLeftThenRight(Node* n) pure nothrow @safe @nogc { n.left = rotateLeft(n.left); return rotateRight(n); }   private Node* rotateRightThenLeft(Node* n) pure nothrow @safe @nogc { n.right = rotateRight(n.right); return rotateLeft(n); }   private int height(in Node* n) const pure nothrow @safe @nogc { if (n is null) return -1; return 1 + max(height(n.left), height(n.right)); }   private void setBalance(Node*[] nodes...) pure nothrow @safe @nogc { foreach (n; nodes) n.balance = height(n.right) - height(n.left); }   public void printBalance() const @safe { printBalance(root); }   private void printBalance(in Node* n) const @safe { if (n !is null) { printBalance(n.left); write(n.balance, ' '); printBalance(n.right); } } }   void main() @safe { auto tree = new AVLtree();   writeln("Inserting values 1 to 10"); foreach (immutable i; 1 .. 11) tree.insert(i);   write("Printing balance: "); tree.printBalance; }
http://rosettacode.org/wiki/Averages/Mean_angle
Averages/Mean angle
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the second was of 10 degrees then the average of the numbers is 180 degrees, whereas if you can note that 350 degrees is equivalent to -10 degrees and so you have two readings at 10 degrees either side of zero degrees leading to a more fitting mean angle of zero degrees. To calculate the mean angle of several angles: Assume all angles are on the unit circle and convert them to complex numbers expressed in real and imaginary form. Compute the mean of the complex numbers. Convert the complex mean to polar coordinates whereupon the phase of the complex mean is the required angular mean. (Note that, since the mean is the sum divided by the number of numbers, and division by a positive real number does not affect the angle, you can also simply compute the sum for step 2.) You can alternatively use this formula: Given the angles α 1 , … , α n {\displaystyle \alpha _{1},\dots ,\alpha _{n}} the mean is computed by α ¯ = atan2 ⁡ ( 1 n ⋅ ∑ j = 1 n sin ⁡ α j , 1 n ⋅ ∑ j = 1 n cos ⁡ α j ) {\displaystyle {\bar {\alpha }}=\operatorname {atan2} \left({\frac {1}{n}}\cdot \sum _{j=1}^{n}\sin \alpha _{j},{\frac {1}{n}}\cdot \sum _{j=1}^{n}\cos \alpha _{j}\right)} Task[edit] write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle. (You should use a built-in function if you have one that does this for degrees or radians). Use the function to compute the means of these lists of angles (in degrees):   [350, 10]   [90, 180, 270, 360]   [10, 20, 30] Show your output here. See also Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#Delphi
Delphi
  (define-syntax-rule (deg->radian deg) (* deg 1/180 PI)) (define-syntax-rule (radian->deg rad) (* 180 (/ PI) rad))   (define (mean-angles angles) (radian->deg (angle (for/sum ((a angles)) (make-polar 1 (deg->radian a))))))   (mean-angles '( 350 10)) → -0 (mean-angles '[90 180 270 360]) → -90 (mean-angles '[10 20 30]) → 20  
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
#EchoLisp
EchoLisp
  (define-syntax-rule (deg->radian deg) (* deg 1/180 PI)) (define-syntax-rule (radian->deg rad) (* 180 (/ PI) rad))   (define (mean-angles angles) (radian->deg (angle (for/sum ((a angles)) (make-polar 1 (deg->radian a))))))   (mean-angles '( 350 10)) → -0 (mean-angles '[90 180 270 360]) → -90 (mean-angles '[10 20 30]) → 20  
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
#BASIC
BASIC
DECLARE FUNCTION median! (vector() AS SINGLE)   DIM vec1(10) AS SINGLE, vec2(11) AS SINGLE, n AS INTEGER   RANDOMIZE TIMER   FOR n = 0 TO 10 vec1(n) = RND * 100 vec2(n) = RND * 100 NEXT vec2(11) = RND * 100   PRINT median(vec1()) PRINT median(vec2())   FUNCTION median! (vector() AS SINGLE) DIM lb AS INTEGER, ub AS INTEGER, L0 AS INTEGER lb = LBOUND(vector) ub = UBOUND(vector) REDIM v(lb TO ub) AS SINGLE FOR L0 = lb TO ub v(L0) = vector(L0) NEXT quicksort v(), lb, ub IF ((ub - lb + 1) MOD 2) THEN median = v((ub + lb) / 2) ELSE median = (v(INT((ub + lb) / 2)) + v(INT((ub + lb) / 2) + 1)) / 2 END IF END FUNCTION