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/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
| #Factor | Factor | : a-mean ( seq -- mean )
[ sum ] [ length ] bi / ;
: g-mean ( seq -- mean )
[ product ] [ length recip ] bi ^ ;
: h-mean ( seq -- mean )
[ length ] [ [ recip ] map-sum ] bi / ; |
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.
| #Groovy | Groovy | enum T {
m('-', -1), z('0', 0), p('+', 1)
final String symbol
final int value
private T(String symbol, int value) {
this.symbol = symbol
this.value = value
}
static T get(Object key) {
switch (key) {
case [m.value, m.symbol] : return m
case [z.value, z.symbol] : return z
case [p.value, p.symbol] : return p
default: return null
}
}
T negative() {
T.get(-this.value)
}
String toString() { this.symbol }
}
class BalancedTernaryInteger {
static final MINUS = new BalancedTernaryInteger(T.m)
static final ZERO = new BalancedTernaryInteger(T.z)
static final PLUS = new BalancedTernaryInteger(T.p)
private static final LEADING_ZEROES = /^0+/
final String value
BalancedTernaryInteger(String bt) {
assert bt && bt.toSet().every { T.get(it) }
value = bt ==~ LEADING_ZEROES ? T.z : bt.replaceAll(LEADING_ZEROES, '');
}
BalancedTernaryInteger(BigInteger i) {
this(i == 0 ? T.z.symbol : valueFromInt(i));
}
BalancedTernaryInteger(T...tArray) {
this(tArray.sum{ it.symbol });
}
BalancedTernaryInteger(List<T> tList) {
this(tList.sum{ it.symbol });
}
private static String valueFromInt(BigInteger i) {
assert i != null
if (i < 0) return negate(valueFromInt(-i))
if (i == 0) return ''
int bRem = (((i % 3) - 2) ?: -3) + 2
valueFromInt((i - bRem).intdiv(3)) + T.get(bRem)
}
private static String negate(String bt) {
bt.collect{ T.get(it) }.inject('') { str, t ->
str + (-t)
}
}
private static final Map INITIAL_SUM_PARTS = [carry:T.z, sum:[]]
private static final prepValueLen = { int len, String s ->
s.padLeft(len + 1, T.z.symbol).collect{ T.get(it) }
}
private static final partCarrySum = { partialSum, carry, trit ->
[carry: carry, sum: [trit] + partialSum]
}
private static final partSum = { parts, trits ->
def carrySum = partCarrySum.curry(parts.sum)
switch ((trits + parts.carry).sort()) {
case [[T.m, T.m, T.m]]: return carrySum(T.m, T.z) //-3
case [[T.m, T.m, T.z]]: return carrySum(T.m, T.p) //-2
case [[T.m, T.z, T.z], [T.m, T.m, T.p]]: return carrySum(T.z, T.m) //-1
case [[T.z, T.z, T.z], [T.m, T.z, T.p]]: return carrySum(T.z, T.z) //+0
case [[T.z, T.z, T.p], [T.m, T.p, T.p]]: return carrySum(T.z, T.p) //+1
case [[T.z, T.p, T.p]]: return carrySum(T.p, T.m) //+2
case [[T.p, T.p, T.p]]: default: return carrySum(T.p, T.z) //+3
}
}
BalancedTernaryInteger plus(BalancedTernaryInteger that) {
assert that != null
if (this == ZERO) return that
if (that == ZERO) return this
def prep = prepValueLen.curry([value.size(), that.value.size()].max())
List values = [prep(value), prep(that.value)].transpose()
new BalancedTernaryInteger(values[-1..(-values.size())].inject(INITIAL_SUM_PARTS, partSum).sum)
}
BalancedTernaryInteger negative() {
!this ? this : new BalancedTernaryInteger(negate(value))
}
BalancedTernaryInteger minus(BalancedTernaryInteger that) {
assert that != null
this + -that
}
private static final INITIAL_PRODUCT_PARTS = [sum:ZERO, pad:'']
private static final sigTritCount = { it.value.replaceAll(T.z.symbol,'').size() }
private BalancedTernaryInteger paddedValue(String pad) {
new BalancedTernaryInteger(value + pad)
}
private BalancedTernaryInteger partialProduct(T multiplier, String pad){
switch (multiplier) {
case T.z: return ZERO
case T.m: return -paddedValue(pad)
case T.p: default: return paddedValue(pad)
}
}
BalancedTernaryInteger multiply(BalancedTernaryInteger that) {
assert that != null
if (that == ZERO) return ZERO
if (that == PLUS) return this
if (that == MINUS) return -this
if (this.value.size() == 1 || sigTritCount(this) < sigTritCount(that)) {
return that.multiply(this)
}
that.value.collect{ T.get(it) }[-1..(-value.size())].inject(INITIAL_PRODUCT_PARTS) { parts, multiplier ->
[sum: parts.sum + partialProduct(multiplier, parts.pad), pad: parts.pad + T.z]
}.sum
}
BigInteger asBigInteger() {
value.collect{ T.get(it) }.inject(0) { i, trit -> i * 3 + trit.value }
}
def asType(Class c) {
switch (c) {
case Integer: return asBigInteger() as Integer
case Long: return asBigInteger() as Long
case [BigInteger, Number]: return asBigInteger()
case Boolean: return this != ZERO
case String: return toString()
default: return super.asType(c)
}
}
boolean equals(Object that) {
switch (that) {
case BalancedTernaryInteger: return this.value == that?.value
default: return super.equals(that)
}
}
int hashCode() { this.value.hashCode() }
String toString() { value }
} |
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.
| #OCaml | OCaml |
let rec f a=
if (a*a) mod 1000000 != 269696
then f(a+1)
else a
in
let a= f 1 in
Printf.printf "smallest positive integer whose square ends in the digits 269696 is %d\n" a
|
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
| #Batch_File | Batch File | :: Balanced Brackets Task from Rosetta Code
:: Batch File Implementation
@echo off
setlocal enabledelayedexpansion
set "num_pairs=10"
set "num_strings=10"
:: the main thing
for /l %%s in (1, 1, %num_strings%) do (
call :generate
call :check
)
echo(
pause
exit /b 0
:: generate strings of brackets
:generate
set "string="
rem put %num_pairs% number of "[" in string
for /l %%c in (1, 1, %num_pairs%) do set "string=!string!["
rem put %num_pairs% number of "]" in random spots of string
set "ctr=%num_pairs%"
for /l %%c in (1, 1, %num_pairs%) do (
set /a "rnd=!random! %% (!ctr! + 1)"
for %%x in (!rnd!) do (
set "left=!string:~0,%%x!"
set "right=!string:~%%x!"
)
set "string=!left!]!right!"
set /a "ctr+=1"
)
goto :EOF
:: check for balance
:check
set "new=%string%"
:check_loop
if "%new%" equ "" (
echo(
echo(%string% is Balanced.
goto :EOF
) else if "%old%" equ "%new%" ( %== unchangeable already? ==%
echo(
echo(%string% is NOT Balanced.
goto :EOF
)
rem apply rewrite rule "[]" -> null
set "old=%new%"
set "new=%old:[]=%"
goto check_loop |
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
| #GAP | GAP | mode := function(v)
local c, m;
c := Collected(SortedList(v));
m := Maximum(List(c, x -> x[2]));
return List(Filtered(c, x -> x[2] = m), y -> y[1]);
end;
mode([ 7, 5, 6, 1, 5, 5, 7, 12, 17, 6, 6, 5, 12, 3, 6 ]);
# [ 5, 6 ] |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Ada | Ada | with Ada.Float_Text_Io; use Ada.Float_Text_Io;
with Ada.Text_IO; use Ada.Text_IO;
procedure Mean_Main is
type Vector is array (Positive range <>) of Float;
function Mean (Item : Vector) return float with pre => Item'length > 0;
function Mean (Item : Vector) return Float is
Sum : Float := 0.0;
begin
for I in Item'range loop
Sum := Sum + Item(I);
end loop;
return Sum / Float(Item'Length);
end Mean;
A : Vector := (3.0, 1.0, 4.0, 1.0, 5.0, 9.0);
begin
Put(Item => Mean (A), Fore => 1, Exp => 0);
New_Line;
-- test for zero length vector
Put(Item => Mean(A (1..0)), Fore => 1, Exp => 0);
New_Line;
end Mean_Main; |
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
| #AppleScript | AppleScript | set baseRecord to {|name|:"Rocket Skates", price:12.75, |color|:"yellow"}
set updateRecord to {price:15.25, |color|:"red", |year|:1974}
set mergedRecord to updateRecord & baseRecord
return mergedRecord |
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
| #Arturo | Arturo | details: #[name: "Rocket Skates" price: 12.75 colour: 'yellow]
newDetails: extend details #[price: 15.25 colour: 'red year: 1974]
print newDetails |
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
| #AutoHotkey | AutoHotkey | merge(base, update){
Merged := {}
for k, v in base
Merged[k] := v
for k, v in update
Merged[k] := v
return Merged
} |
http://rosettacode.org/wiki/Average_loop_length | Average loop length | Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence.
Task
Write a program or a script that estimates, for each N, the average length until the first such repetition.
Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.
This problem comes from the end of Donald Knuth's Christmas tree lecture 2011.
Example of expected output:
N average analytical (error)
=== ========= ============ =========
1 1.0000 1.0000 ( 0.00%)
2 1.4992 1.5000 ( 0.05%)
3 1.8784 1.8889 ( 0.56%)
4 2.2316 2.2188 ( 0.58%)
5 2.4982 2.5104 ( 0.49%)
6 2.7897 2.7747 ( 0.54%)
7 3.0153 3.0181 ( 0.09%)
8 3.2429 3.2450 ( 0.07%)
9 3.4536 3.4583 ( 0.14%)
10 3.6649 3.6602 ( 0.13%)
11 3.8091 3.8524 ( 1.12%)
12 3.9986 4.0361 ( 0.93%)
13 4.2074 4.2123 ( 0.12%)
14 4.3711 4.3820 ( 0.25%)
15 4.5275 4.5458 ( 0.40%)
16 4.6755 4.7043 ( 0.61%)
17 4.8877 4.8579 ( 0.61%)
18 4.9951 5.0071 ( 0.24%)
19 5.1312 5.1522 ( 0.41%)
20 5.2699 5.2936 ( 0.45%)
| #Clojure | Clojure | (ns cyclelengths
(:gen-class))
(defn factorial [n]
" n! "
(apply *' (range 1 (inc n)))) ; Use *' (vs. *) to allow arbitrary length arithmetic
(defn pow [n i]
" n^i"
(apply *' (repeat i n)))
(defn analytical [n]
" Analytical Computation "
(->>(range 1 (inc n))
(map #(/ (factorial n) (pow n %) (factorial (- n %)))) ;calc n %))
(reduce + 0)))
;; Number of random times to test each n
(def TIMES 1000000)
(defn single-test-cycle-length [n]
" Single random test of cycle length "
(loop [count 0
bits 0
x 1]
(if (zero? (bit-and x bits))
(recur (inc count) (bit-or bits x) (bit-shift-left 1 (rand-int n)))
count)))
(defn avg-cycle-length [n times]
" Average results of single tests of cycle lengths "
(/
(reduce +
(for [i (range times)]
(single-test-cycle-length n)))
times))
;; Show Results
(println "\tAvg\t\tExp\t\tDiff")
(doseq [q (range 1 21)
:let [anal (double (analytical q))
avg (double (avg-cycle-length q TIMES))
diff (Math/abs (* 100 (- 1 (/ avg anal))))]]
(println (format "%3d\t%.4f\t%.4f\t%.2f%%" q avg anal 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
| #Picat | Picat | main =>
L=[1, 2, 3, 4, 5, 5, 4, 3, 2, 1],
Map3 = new_map([p=3]),
Map5 = new_map([p=5]),
foreach(N in L)
printf("n: %-2d sma3: %-17w sma5: %-17w\n",N, sma(N,Map3), sma(N,Map5))
end.
sma(N,Map) = Average =>
Stream = Map.get(stream,[]) ++ [N],
if Stream.len > Map.get(p) then
Stream := Stream.tail
end,
Average = cond(Stream.len == 0,
0,
sum(Stream) / Stream.len),
Map.put(stream,Stream). |
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.
| #BASIC | BASIC | 10 DEFINT A-Z
20 M=120
30 DIM C(M): C(0)=-1: C(1)=-1
40 FOR I=2 TO SQR(M)
50 IF NOT C(I) THEN FOR J=I+I TO M STEP I: C(J)=-1: NEXT
60 NEXT
70 FOR I=2 TO M
80 N=I: C=0
90 FOR J=2 TO M
100 IF NOT C(J) THEN IF N MOD J=0 THEN N=N\J: C=C+1: GOTO 100
110 NEXT
120 IF NOT C(C) THEN PRINT I,
130 NEXT |
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.
| #BCPL | BCPL | get "libhdr"
manifest $( MAXIMUM = 120 $)
let sieve(prime, max) be
$( for i=0 to max do i!prime := i>=2
for i=2 to max>>1 if i!prime
$( let j = i<<1
while j <= max do
$( j!prime := false
j := j+i
$)
$)
$)
let factors(n, prime, max) = valof
$( let count = 0
for i=2 to max if i!prime
until n rem i
$( count := count + 1
n := n / i
$)
resultis count
$)
let start() be
$( let n = 0 and prime = vec MAXIMUM
sieve(prime, MAXIMUM)
for i=2 to MAXIMUM
if factors(i, prime, MAXIMUM)!prime
$( writed(i, 4)
n := n + 1
unless n rem 18 do wrch('*N')
$)
wrch('*N')
$) |
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
| #Factor | Factor | USING: arrays formatting kernel math math.combinators
math.functions math.libm math.parser math.trig qw sequences
splitting ;
IN: rosetta-code.mean-time
CONSTANT: input qw{ 23:00:17 23:40:20 00:12:45 00:17:19 }
: time>deg ( hh:mm:ss -- x )
":" split [ string>number ] map first3
[ 15 * ] [ 1/4 * ] [ 1/240 * ] tri* + + ;
: mean-angle ( seq -- x )
[ deg>rad ] map [ [ sin ] map-sum ] [ [ cos ] map-sum ]
[ length ] tri recip [ * ] curry bi@ fatan2 rad>deg ;
: cutf ( x -- str y )
[ >integer number>string ] [ dup floor - ] bi ;
: mean-time ( seq -- str )
[ time>deg ] map mean-angle [ 360 + ] when-negative 24 *
360 / cutf 60 * cutf 60 * round cutf drop 3array ":" join ;
: mean-time-demo ( -- )
input dup mean-time "Mean time for %u is %s.\n" printf ;
MAIN: mean-time-demo |
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
| #Fortran | Fortran |
program mean_time_of_day
implicit none
integer(kind=4), parameter :: dp = kind(0.0d0)
type time_t
integer(kind=4) :: hours, minutes, seconds
end type
character(len=8), dimension(4), parameter :: times = &
(/ '23:00:17', '23:40:20', '00:12:45', '00:17:19' /)
real(kind=dp), dimension(size(times)) :: angles
real(kind=dp) :: mean
angles = time_to_angle(str_to_time(times))
mean = mean_angle(angles)
if (mean < 0) mean = 360 + mean
write(*, fmt='(I2.2, '':'', I2.2, '':'', I2.2)') angle_to_time(mean)
contains
real(kind=dp) function mean_angle(angles)
real(kind=dp), dimension(:), intent (in) :: angles
real(kind=dp) :: x, y
x = sum(sin(radians(angles)))/size(angles)
y = sum(cos(radians(angles)))/size(angles)
mean_angle = degrees(atan2(x, y))
end function
elemental real(kind=dp) function radians(angle)
real(kind=dp), intent (in) :: angle
real(kind=dp), parameter :: pi = 4d0*atan(1d0)
radians = angle/180*pi
end function
elemental real(kind=dp) function degrees(angle)
real(kind=dp), intent (in) :: angle
real(kind=dp), parameter :: pi = 4d0*atan(1d0)
degrees = 180*angle/pi
end function
elemental type(time_t) function str_to_time(str)
character(len=*), intent (in) :: str
! Assuming time in format hh:mm:ss
read(str, fmt='(I2, 1X, I2, 1X, I2)') str_to_time
end function
elemental real(kind=dp) function time_to_angle(time) result (res)
type(time_t), intent (in) :: time
real(kind=dp) :: seconds
real(kind=dp), parameter :: seconds_in_day = 24*60*60
seconds = time%seconds + 60*time%minutes + 60*60*time%hours
res = 360*seconds/seconds_in_day
end function
elemental type(time_t) function angle_to_time(angle)
real(kind=dp), intent (in) :: angle
real(kind=dp) :: seconds
real(kind=dp), parameter :: seconds_in_day = 24*60*60
seconds = seconds_in_day*angle/360d0
angle_to_time%hours = int(seconds/60d0/60d0)
seconds = mod(seconds, 60d0*60d0)
angle_to_time%minutes = int(seconds/60d0)
angle_to_time%seconds = mod(seconds, 60d0)
end function
end program
|
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.
| #Fortran | Fortran | module 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.
!
implicit none
private
! The type for an AVL tree.
public :: avl_tree_t
! The type for a pair of pointers to key and data within the tree.
! (Be careful with these!)
public :: avl_pointer_pair_t
! Insertion, replacement, modification, etc.
public :: avl_insert_or_modify
! Insert or replace.
public :: avl_insert
! Is the key in the tree?
public :: avl_contains
! Retrieve data from a tree.
public :: avl_retrieve
! Delete data from a tree. This is a generic function.
public :: avl_delete
! Implementations of avl_delete.
public :: avl_delete_with_found
public :: avl_delete_without_found
! How many nodes are there in the tree?
public :: avl_size
! Return a list of avl_pointer_pair_t for the elements in the
! tree. The list will be in order.
public :: avl_pointer_pairs
! Print a representation of the tree to an output unit.
public :: avl_write
! Check the AVL condition (that the heights of the two branches from
! a node should differ by zero or one). ERROR STOP if the condition
! is not met.
public :: avl_check
! Procedure types.
public :: avl_less_than_t
public :: avl_insertion_t
public :: avl_key_data_writer_t
type :: avl_node_t
class(*), allocatable :: key, data
type(avl_node_t), pointer :: left
type(avl_node_t), pointer :: right
integer :: bal ! bal == -1, 0, 1
end type avl_node_t
type :: avl_tree_t
type(avl_node_t), pointer :: p => null ()
contains
final :: avl_tree_t_final
end type avl_tree_t
type :: avl_pointer_pair_t
class(*), pointer :: p_key, p_data
class(avl_pointer_pair_t), pointer :: next => null ()
contains
final :: avl_pointer_pair_t_final
end type avl_pointer_pair_t
interface avl_delete
module procedure avl_delete_with_found
module procedure avl_delete_without_found
end interface avl_delete
interface
function avl_less_than_t (key1, key2) result (key1_lt_key2)
!
! The ordering predicate (‘<’).
!
! Two keys a,b are considered equivalent if neither a<b nor
! b<a.
!
class(*), intent(in) :: key1, key2
logical key1_lt_key2
end function avl_less_than_t
subroutine avl_insertion_t (key, data, p_is_new, p)
!
! Insertion or modification of a found node.
!
import avl_node_t
class(*), intent(in) :: key, data
logical, intent(in) :: p_is_new
type(avl_node_t), pointer, intent(inout) :: p
end subroutine avl_insertion_t
subroutine avl_key_data_writer_t (unit, key, data)
!
! Printing the key and data of a node.
!
integer, intent(in) :: unit
class(*), intent(in) :: key, data
end subroutine avl_key_data_writer_t
end interface
contains
subroutine avl_tree_t_final (tree)
type(avl_tree_t), intent(inout) :: tree
type(avl_node_t), pointer :: p
p => tree%p
call free_the_nodes (p)
contains
recursive subroutine free_the_nodes (p)
type(avl_node_t), pointer, intent(inout) :: p
if (associated (p)) then
call free_the_nodes (p%left)
call free_the_nodes (p%right)
deallocate (p)
end if
end subroutine free_the_nodes
end subroutine avl_tree_t_final
recursive subroutine avl_pointer_pair_t_final (node)
type(avl_pointer_pair_t), intent(inout) :: node
if (associated (node%next)) deallocate (node%next)
end subroutine avl_pointer_pair_t_final
function avl_contains (less_than, key, tree) result (found)
procedure(avl_less_than_t) :: less_than
class(*), intent(in) :: key
class(avl_tree_t), intent(in) :: tree
logical :: found
found = avl_contains_recursion (less_than, key, tree%p)
end function avl_contains
recursive function avl_contains_recursion (less_than, key, p) result (found)
procedure(avl_less_than_t) :: less_than
class(*), intent(in) :: key
type(avl_node_t), pointer, intent(in) :: p
logical :: found
if (.not. associated (p)) then
found = .false.
else if (less_than (key, p%key)) then
found = avl_contains_recursion (less_than, key, p%left)
else if (less_than (p%key, key)) then
found = avl_contains_recursion (less_than, key, p%right)
else
found = .true.
end if
end function avl_contains_recursion
subroutine avl_retrieve (less_than, key, tree, found, data)
procedure(avl_less_than_t) :: less_than
class(*), intent(in) :: key
class(avl_tree_t), intent(in) :: tree
logical, intent(out) :: found
class(*), allocatable, intent(inout) :: data
call avl_retrieve_recursion (less_than, key, tree%p, found, data)
end subroutine avl_retrieve
recursive subroutine avl_retrieve_recursion (less_than, key, p, found, data)
procedure(avl_less_than_t) :: less_than
class(*), intent(in) :: key
type(avl_node_t), pointer, intent(in) :: p
logical, intent(out) :: found
class(*), allocatable, intent(inout) :: data
if (.not. associated (p)) then
found = .false.
else if (less_than (key, p%key)) then
call avl_retrieve_recursion (less_than, key, p%left, found, data)
else if (less_than (p%key, key)) then
call avl_retrieve_recursion (less_than, key, p%right, found, data)
else
found = .true.
data = p%data
end if
end subroutine avl_retrieve_recursion
subroutine avl_insert (less_than, key, data, tree)
procedure(avl_less_than_t) :: less_than
class(*), intent(in) :: key, data
class(avl_tree_t), intent(inout) :: tree
call avl_insert_or_modify (less_than, insert_or_replace, key, data, tree)
end subroutine avl_insert
subroutine insert_or_replace (key, data, p_is_new, p)
class(*), intent(in) :: key, data
logical, intent(in) :: p_is_new
type(avl_node_t), pointer, intent(inout) :: p
p%data = data
end subroutine insert_or_replace
subroutine avl_insert_or_modify (less_than, insertion, key, data, tree)
procedure(avl_less_than_t) :: less_than
procedure(avl_insertion_t) :: insertion ! Or modification in place.
class(*), intent(in) :: key, data
class(avl_tree_t), intent(inout) :: tree
logical :: fix_balance
fix_balance = .false.
call insertion_search (less_than, insertion, key, data, tree%p, fix_balance)
end subroutine avl_insert_or_modify
recursive subroutine insertion_search (less_than, insertion, key, data, p, fix_balance)
procedure(avl_less_than_t) :: less_than
procedure(avl_insertion_t) :: insertion
class(*), intent(in) :: key, data
type(avl_node_t), pointer, intent(inout) :: p
logical, intent(inout) :: fix_balance
type(avl_node_t), pointer :: p1, p2
if (.not. associated (p)) then
! The key was not found. Make a new node.
allocate (p)
p%key = key
p%left => null ()
p%right => null ()
p%bal = 0
call insertion (key, data, .true., p)
fix_balance = .true.
else if (less_than (key, p%key)) then
! Continue searching.
call insertion_search (less_than, insertion, key, data, p%left, fix_balance)
if (fix_balance) then
! A new node has been inserted on the left side.
select case (p%bal)
case (1)
p%bal = 0
fix_balance = .false.
case (0)
p%bal = -1
case (-1)
! Rebalance.
p1 => p%left
select case (p1%bal)
case (-1)
! A single LL rotation.
p%left => p1%right
p1%right => p
p%bal = 0
p => p1
p%bal = 0
fix_balance = .false.
case (0, 1)
! A double LR rotation.
p2 => p1%right
p1%right => p2%left
p2%left => p1
p%left => p2%right
p2%right => p
p%bal = -(min (p2%bal, 0))
p1%bal = -(max (p2%bal, 0))
p => p2
p%bal = 0
fix_balance = .false.
case default
error stop
end select
case default
error stop
end select
end if
else if (less_than (p%key, key)) then
call insertion_search (less_than, insertion, key, data, p%right, fix_balance)
if (fix_balance) then
! A new node has been inserted on the right side.
select case (p%bal)
case (-1)
p%bal = 0
fix_balance = .false.
case (0)
p%bal = 1
case (1)
! Rebalance.
p1 => p%right
select case (p1%bal)
case (1)
! A single RR rotation.
p%right => p1%left
p1%left => p
p%bal = 0
p => p1
p%bal = 0
fix_balance = .false.
case (-1, 0)
! A double RL rotation.
p2 => p1%left
p1%left => p2%right
p2%right => p1
p%right => p2%left
p2%left => p
p%bal = -(max (p2%bal, 0))
p1%bal = -(min (p2%bal, 0))
p => p2
p%bal = 0
fix_balance = .false.
case default
error stop
end select
case default
error stop
end select
end if
else
! The key was found. The pointer p points to an existing node.
call insertion (key, data, .false., p)
end if
end subroutine insertion_search
subroutine avl_delete_with_found (less_than, key, tree, found)
procedure(avl_less_than_t) :: less_than
class(*), intent(in) :: key
class(avl_tree_t), intent(inout) :: tree
logical, intent(out) :: found
logical :: fix_balance
fix_balance = .false.
call deletion_search (less_than, key, tree%p, fix_balance, found)
end subroutine avl_delete_with_found
subroutine avl_delete_without_found (less_than, key, tree)
procedure(avl_less_than_t) :: less_than
class(*), intent(in) :: key
class(avl_tree_t), intent(inout) :: tree
logical :: found
call avl_delete_with_found (less_than, key, tree, found)
end subroutine avl_delete_without_found
recursive subroutine deletion_search (less_than, key, p, fix_balance, found)
procedure(avl_less_than_t) :: less_than
class(*), intent(in) :: key
type(avl_node_t), pointer, intent(inout) :: p
logical, intent(inout) :: fix_balance
logical, intent(out) :: found
type(avl_node_t), pointer :: q
if (.not. associated (p)) then
! The key is not in the tree.
found = .false.
else if (less_than (key, p%key)) then
call deletion_search (less_than, key, p%left, fix_balance, found)
if (fix_balance) call balance_for_shrunken_left (p, fix_balance)
else if (less_than (p%key, key)) then
call deletion_search (less_than, key, p%right, fix_balance, found)
if (fix_balance) call balance_for_shrunken_right (p, fix_balance)
else
q => p
if (.not. associated (q%right)) then
p => q%left
fix_balance = .true.
else if (.not. associated (q%left)) then
p => q%right
fix_balance = .true.
else
call del (q%left, q, fix_balance)
if (fix_balance) call balance_for_shrunken_left (p, fix_balance)
end if
deallocate (q)
found = .true.
end if
end subroutine deletion_search
recursive subroutine del (r, q, fix_balance)
type(avl_node_t), pointer, intent(inout) :: r, q
logical, intent(inout) :: fix_balance
if (associated (r%right)) then
call del (r%right, q, fix_balance)
if (fix_balance) call balance_for_shrunken_right (r, fix_balance)
else
q%key = r%key
q%data = r%data
q => r
r => r%left
fix_balance = .true.
end if
end subroutine del
subroutine balance_for_shrunken_left (p, fix_balance)
type(avl_node_t), pointer, intent(inout) :: p
logical, intent(inout) :: fix_balance
! The left side has lost a node.
type(avl_node_t), pointer :: p1, p2
if (.not. fix_balance) error stop
select case (p%bal)
case (-1)
p%bal = 0
case (0)
p%bal = 1
fix_balance = .false.
case (1)
! Rebalance.
p1 => p%right
select case (p1%bal)
case (0)
! A single RR rotation.
p%right => p1%left
p1%left => p
p%bal = 1
p1%bal = -1
p => p1
fix_balance = .false.
case (1)
! A single RR rotation.
p%right => p1%left
p1%left => p
p%bal = 0
p1%bal = 0
p => p1
fix_balance = .true.
case (-1)
! A double RL rotation.
p2 => p1%left
p1%left => p2%right
p2%right => p1
p%right => p2%left
p2%left => p
p%bal = -(max (p2%bal, 0))
p1%bal = -(min (p2%bal, 0))
p => p2
p2%bal = 0
case default
error stop
end select
case default
error stop
end select
end subroutine balance_for_shrunken_left
subroutine balance_for_shrunken_right (p, fix_balance)
type(avl_node_t), pointer, intent(inout) :: p
logical, intent(inout) :: fix_balance
! The right side has lost a node.
type(avl_node_t), pointer :: p1, p2
if (.not. fix_balance) error stop
select case (p%bal)
case (1)
p%bal = 0
case (0)
p%bal = -1
fix_balance = .false.
case (-1)
! Rebalance.
p1 => p%left
select case (p1%bal)
case (0)
! A single LL rotation.
p%left => p1%right
p1%right => p
p1%bal = 1
p%bal = -1
p => p1
fix_balance = .false.
case (-1)
! A single LL rotation.
p%left => p1%right
p1%right => p
p1%bal = 0
p%bal = 0
p => p1
fix_balance = .true.
case (1)
! A double LR rotation.
p2 => p1%right
p1%right => p2%left
p2%left => p1
p%left => p2%right
p2%right => p
p%bal = -(min (p2%bal, 0))
p1%bal = -(max (p2%bal, 0))
p => p2
p2%bal = 0
case default
error stop
end select
case default
error stop
end select
end subroutine balance_for_shrunken_right
function avl_size (tree) result (size)
class(avl_tree_t), intent(in) :: tree
integer :: size
size = traverse (tree%p)
contains
recursive function traverse (p) result (size)
type(avl_node_t), pointer, intent(in) :: p
integer :: size
if (associated (p)) then
! The order of traversal is arbitrary.
size = 1 + traverse (p%left) + traverse (p%right)
else
size = 0
end if
end function traverse
end function avl_size
function avl_pointer_pairs (tree) result (lst)
class(avl_tree_t), intent(in) :: tree
type(avl_pointer_pair_t), pointer :: lst
! Reverse in-order traversal of the tree, to produce a CONS-list
! of pointers to the contents.
lst => null ()
if (associated (tree%p)) lst => traverse (tree%p, lst)
contains
recursive function traverse (p, lst1) result (lst2)
type(avl_node_t), pointer, intent(in) :: p
type(avl_pointer_pair_t), pointer, intent(in) :: lst1
type(avl_pointer_pair_t), pointer :: lst2
type(avl_pointer_pair_t), pointer :: new_entry
lst2 => lst1
if (associated (p%right)) lst2 => traverse (p%right, lst2)
allocate (new_entry)
new_entry%p_key => p%key
new_entry%p_data => p%data
new_entry%next => lst2
lst2 => new_entry
if (associated (p%left)) lst2 => traverse (p%left, lst2)
end function traverse
end function avl_pointer_pairs
subroutine avl_write (write_key_data, unit, tree)
procedure(avl_key_data_writer_t) :: write_key_data
integer, intent(in) :: unit
class(avl_tree_t), intent(in) :: tree
character(len = *), parameter :: tab = achar (9)
type(avl_node_t), pointer :: p
p => tree%p
if (.not. associated (p)) then
continue
else
call traverse (p%left, 1, .true.)
call write_key_data (unit, p%key, p%data)
write (unit, '(2A, "depth = ", I0, " bal = ", I0)') tab, tab, 0, p%bal
call traverse (p%right, 1, .false.)
end if
contains
recursive subroutine traverse (p, depth, left)
type(avl_node_t), pointer, intent(in) :: p
integer, value :: depth
logical, value :: left
if (.not. associated (p)) then
continue
else
call traverse (p%left, depth + 1, .true.)
call pad (depth, left)
call write_key_data (unit, p%key, p%data)
write (unit, '(2A, "depth = ", I0, " bal = ", I0)') tab, tab, depth, p%bal
call traverse (p%right, depth + 1, .false.)
end if
end subroutine traverse
subroutine pad (depth, left)
integer, value :: depth
logical, value :: left
integer :: i
do i = 1, depth
write (unit, '(2X)', advance = 'no')
end do
end subroutine pad
end subroutine avl_write
subroutine avl_check (tree)
use, intrinsic :: iso_fortran_env, only: error_unit
class(avl_tree_t), intent(in) :: tree
type(avl_node_t), pointer :: p
integer :: height_L, height_R
p => tree%p
call get_heights (p, height_L, height_R)
call check_heights (height_L, height_R)
contains
recursive subroutine get_heights (p, height_L, height_R)
type(avl_node_t), pointer, intent(in) :: p
integer, intent(out) :: height_L, height_R
integer :: height_LL, height_LR
integer :: height_RL, height_RR
height_L = 0
height_R = 0
if (associated (p)) then
call get_heights (p%left, height_LL, height_LR)
call check_heights (height_LL, height_LR)
height_L = height_LL + height_LR
call get_heights (p%right, height_RL, height_RR)
call check_heights (height_RL, height_RR)
height_R = height_RL + height_RR
end if
end subroutine get_heights
subroutine check_heights (height_L, height_R)
integer, value :: height_L, height_R
if (2 <= abs (height_L - height_R)) then
write (error_unit, '("*** AVL condition violated ***")')
error stop
end if
end subroutine check_heights
end subroutine avl_check
end module avl_trees
program avl_trees_demo
use, intrinsic :: iso_fortran_env, only: output_unit
use, non_intrinsic :: avl_trees
implicit none
integer, parameter :: keys_count = 20
type(avl_tree_t) :: tree
logical :: found
class(*), allocatable :: retval
integer :: the_keys(1:keys_count)
integer :: i, j
do i = 1, keys_count
the_keys(i) = i
end do
call fisher_yates_shuffle (the_keys, keys_count)
call avl_check (tree)
do i = 1, keys_count
call avl_insert (lt, the_keys(i), real (the_keys(i)), tree)
call avl_check (tree)
if (avl_size (tree) /= i) error stop
do j = 1, keys_count
if (avl_contains (lt, the_keys(j), tree) .neqv. (j <= i)) error stop
end do
do j = 1, keys_count
call avl_retrieve (lt, the_keys(j), tree, found, retval)
if (found .neqv. (j <= i)) error stop
if (found) then
! This crazy way to write ‘/=’ is to quell those tiresome
! warnings about using ‘==’ or ‘/=’ with floating point
! numbers. Floating point numbers can represent integers
! *exactly*.
if (0 < abs (real_cast (retval) - real (the_keys(j)))) error stop
end if
if (found) then
block
character(len = 1), parameter :: ch = '*'
!
! Try replacing the data with a character and then
! restoring the number.
!
call avl_insert (lt, the_keys(j), ch, tree)
call avl_retrieve (lt, the_keys(j), tree, found, retval)
if (.not. found) error stop
if (char_cast (retval) /= ch) error stop
call avl_insert (lt, the_keys(j), real (the_keys(j)), tree)
call avl_retrieve (lt, the_keys(j), tree, found, retval)
if (.not. found) error stop
if (0 < abs (real_cast (retval) - real (the_keys(j)))) error stop
end block
end if
end do
end do
write (output_unit, '(70("-"))')
call avl_write (int_real_writer, output_unit, tree)
write (output_unit, '(70("-"))')
call print_contents (output_unit, tree)
write (output_unit, '(70("-"))')
call fisher_yates_shuffle (the_keys, keys_count)
do i = 1, keys_count
call avl_delete (lt, the_keys(i), tree)
call avl_check (tree)
if (avl_size (tree) /= keys_count - i) error stop
! Try deleting a second time.
call avl_delete (lt, the_keys(i), tree)
call avl_check (tree)
if (avl_size (tree) /= keys_count - i) error stop
do j = 1, keys_count
if (avl_contains (lt, the_keys(j), tree) .neqv. (i < j)) error stop
end do
do j = 1, keys_count
call avl_retrieve (lt, the_keys(j), tree, found, retval)
if (found .neqv. (i < j)) error stop
if (found) then
if (0 < abs (real_cast (retval) - real (the_keys(j)))) error stop
end if
end do
end do
contains
subroutine fisher_yates_shuffle (keys, n)
integer, intent(inout) :: keys(*)
integer, intent(in) :: n
integer :: i, j
real :: randnum
integer :: tmp
do i = 1, n - 1
call random_number (randnum)
j = i + floor (randnum * (n - i + 1))
tmp = keys(i)
keys(i) = keys(j)
keys(j) = tmp
end do
end subroutine fisher_yates_shuffle
function int_cast (u) result (v)
class(*), intent(in) :: u
integer :: v
select type (u)
type is (integer)
v = u
class default
! This case is not handled.
error stop
end select
end function int_cast
function real_cast (u) result (v)
class(*), intent(in) :: u
real :: v
select type (u)
type is (real)
v = u
class default
! This case is not handled.
error stop
end select
end function real_cast
function char_cast (u) result (v)
class(*), intent(in) :: u
character(len = 1) :: v
select type (u)
type is (character(*))
v = u
class default
! This case is not handled.
error stop
end select
end function char_cast
function lt (u, v) result (u_lt_v)
class(*), intent(in) :: u, v
logical :: u_lt_v
select type (u)
type is (integer)
select type (v)
type is (integer)
u_lt_v = (u < v)
class default
! This case is not handled.
error stop
end select
class default
! This case is not handled.
error stop
end select
end function lt
subroutine int_real_writer (unit, key, data)
integer, intent(in) :: unit
class(*), intent(in) :: key, data
write (unit, '("(", I0, ", ", F0.1, ")")', advance = 'no') &
& int_cast(key), real_cast(data)
end subroutine int_real_writer
subroutine print_contents (unit, tree)
integer, intent(in) :: unit
class(avl_tree_t), intent(in) :: tree
type(avl_pointer_pair_t), pointer :: ppairs, pp
write (unit, '("tree size = ", I0)') avl_size (tree)
ppairs => avl_pointer_pairs (tree)
pp => ppairs
do while (associated (pp))
write (unit, '("(", I0, ", ", F0.1, ")")') &
& int_cast (pp%p_key), real_cast (pp%p_data)
pp => pp%next
end do
if (associated (ppairs)) deallocate (ppairs)
end subroutine print_contents
end program avl_trees_demo |
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
| #Elixir | Elixir |
defmodule MeanAngle do
def mean_angle(angles) do
rad_angles = Enum.map(angles, °_to_rad/1)
sines = rad_angles |> Enum.map(&:math.sin/1) |> Enum.sum
cosines = rad_angles |> Enum.map(&:math.cos/1) |> Enum.sum
rad_to_deg(:math.atan2(sines, cosines))
end
defp deg_to_rad(a) do
(:math.pi/180) * a
end
defp rad_to_deg(a) do
(180/:math.pi) * a
end
end
IO.inspect MeanAngle.mean_angle([10, 350])
IO.inspect MeanAngle.mean_angle([90, 180, 270, 360])
IO.inspect MeanAngle.mean_angle([10, 20, 30])
|
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
| #Erlang | Erlang |
-module( mean_angle ).
-export( [from_degrees/1, task/0] ).
from_degrees( Angles ) ->
Radians = [radians(X) || X <- Angles],
Sines = [math:sin(X) || X <- Radians],
Coses = [math:cos(X) || X <- Radians],
degrees( math:atan2( average(Sines), average(Coses) ) ).
task() ->
Angles = [[350, 10], [90, 180, 270, 360], [10, 20, 30]],
[io:fwrite( "Mean angle of ~p is: ~p~n", [X, erlang:round(from_degrees(X))] ) || X <- Angles].
average( List ) -> lists:sum( List ) / erlang:length( List ).
degrees( Radians ) -> Radians * 180 / math:pi().
radians( Degrees ) -> Degrees * math:pi() / 180.
|
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
| #BBC_BASIC | BBC BASIC | INSTALL @lib$+"SORTLIB"
Sort% = FN_sortinit(0,0)
DIM a(6), b(5)
a() = 4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2
b() = 4.1, 7.2, 1.7, 9.3, 4.4, 3.2
PRINT "Median of a() is " ; FNmedian(a())
PRINT "Median of b() is " ; FNmedian(b())
END
DEF FNmedian(a())
LOCAL C%
C% = DIM(a(),1) + 1
CALL Sort%, a(0)
= (a(C% DIV 2) + a((C%-1) DIV 2)) / 2
|
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of positive integers.
The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
A
(
x
1
,
…
,
x
n
)
=
x
1
+
⋯
+
x
n
n
{\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}}
The geometric mean is the
n
{\displaystyle n}
th root of the product of the list:
G
(
x
1
,
…
,
x
n
)
=
x
1
⋯
x
n
n
{\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}}
The harmonic mean is
n
{\displaystyle n}
divided by the sum of the reciprocal of each item in the list:
H
(
x
1
,
…
,
x
n
)
=
n
1
x
1
+
⋯
+
1
x
n
{\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Fantom | Fantom |
class Main
{
static Float arithmeticMean (Int[] nums)
{
if (nums.size == 0) return 0.0f
sum := 0
nums.each |n| { sum += n }
return sum.toFloat / nums.size
}
static Float geometricMean (Int[] nums)
{
if (nums.size == 0) return 0.0f
product := 1
nums.each |n| { product *= n }
return product.toFloat.pow(1f/nums.size)
}
static Float harmonicMean (Int[] nums)
{
if (nums.size == 0) return 0.0f
reciprocals := 0f
nums.each |n| { reciprocals += 1f / n }
return nums.size.toFloat / reciprocals
}
public static Void main ()
{
items := (1..10).toList
// display results
echo (arithmeticMean (items))
echo (geometricMean (items))
echo (harmonicMean (items))
// check given relation
if ((arithmeticMean (items) >= geometricMean (items)) &&
(geometricMean (items) >= harmonicMean (items)))
echo ("relation holds")
else
echo ("relation failed")
}
}
|
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.
| #Haskell | Haskell | data BalancedTernary = Bt [Int]
zeroTrim a = if null s then [0] else s where
s = fst $ foldl f ([],[]) a
f (x,y) 0 = (x, y++[0])
f (x,y) z = (x++y++[z], [])
btList (Bt a) = a
instance Eq BalancedTernary where
(==) a b = btList a == btList b
btNormalize = listBt . _carry 0 where
_carry c [] = if c == 0 then [] else [c]
_carry c (a:as) = r:_carry cc as where
(cc, r) = f $ (a+c) `quotRem` 3 where
f (x, 2) = (x + 1, -1)
f (x, -2) = (x - 1, 1)
f x = x
listBt = Bt . zeroTrim
instance Show BalancedTernary where
show = reverse . map (\d->case d of -1->'-'; 0->'0'; 1->'+') . btList
strBt = Bt . zeroTrim.reverse.map (\c -> case c of '-' -> -1; '0' -> 0; '+' -> 1)
intBt :: Integral a => a -> BalancedTernary
intBt = fromIntegral . toInteger
btInt = foldr (\a z -> a + 3 * z) 0 . btList
listAdd a b = take (max (length a) (length b)) $ zipWith (+) (a++[0,0..]) (b++[0,0..])
-- mostly for operators, also small stuff to make GHC happy
instance Num BalancedTernary where
negate = Bt . map negate . btList
(+) x y = btNormalize $ listAdd (btList x) (btList y)
(*) x y = btNormalize $ mul_ (btList x) (btList y) where
mul_ _ [] = []
mul_ as b = foldr (\a z -> listAdd (map (a*) b) (0:z)) [] as
-- we don't need to define binary "-" by hand
signum (Bt a) = if a == [0] then 0 else Bt [last a]
abs x = if signum x == Bt [-1] then negate x else x
fromInteger = btNormalize . f where
f 0 = []
f x = fromInteger (rem x 3) : f (quot x 3)
main = let (a,b,c) = (strBt "+-0++0+", intBt (-436), strBt "+-++-")
r = a * (b - c)
in do
print $ map btInt [a,b,c]
print $ r
print $ btInt 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.
| #Ol | Ol |
(print
(let loop ((i 2))
(if (eq? (mod (* i i) 1000000) 269696)
i
(loop (+ i 1)))))
|
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #BBC_BASIC | BBC BASIC | FOR x%=1 TO 10
test$=FNgenerate(RND(10))
PRINT "Bracket string ";test$;" is ";FNvalid(test$)
NEXT x%
END
:
DEFFNgenerate(n%)
LOCAL l%,r%,t%,output$
WHILE l%<n% AND r%<n%
CASE RND(2) OF
WHEN 1:
l%+=1
output$+="["
WHEN 2:
r%+=1
output$+="]"
ENDCASE
ENDWHILE
IF l%=n% THEN output$+=STRING$(n%-r%,"]") ELSE output$+=STRING$(n%-l%,"[")
=output$
:
DEFFNvalid(q$)
LOCAL x%,count%
IF LEN(q$)=0 THEN ="OK."
FOR x%=1 TO LEN(q$)
IF MID$(q$,x%,1)="[" THEN count%+=1 ELSE count%-=1
IF count%<0 THEN ="not OK."
NEXT x%
="OK." |
http://rosettacode.org/wiki/Atomic_updates | Atomic updates |
Task
Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to:
get the current value of any bucket
remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the transferred amount to ensure the values remain non-negative
In order to exercise this data type, create one set of buckets, and start three concurrent tasks:
As often as possible, pick two buckets and make their values closer to equal.
As often as possible, pick two buckets and arbitrarily redistribute their values.
At whatever rate is convenient, display (by any means) the total value and, optionally, the individual values of each bucket.
The display task need not be explicit; use of e.g. a debugger or trace tool is acceptable provided it is simple to set up to provide the display.
This task is intended as an exercise in atomic operations. The sum of the bucket values must be preserved even if the two tasks attempt to perform transfers simultaneously, and a straightforward solution is to ensure that at any time, only one transfer is actually occurring — that the transfer operation is atomic.
| #8th | 8th | var bucket
var bucket-size
\ The 'bucket' will be a simple array of some values:
: genbucket \ n --
a:new swap
(
\ make a random int up to 1000
rand-pcg n:abs 1000 n:mod
a:push
) swap times
bucket ! ;
\ display bucket and its total:
: .bucket
bucket lock @
dup . space
' n:+ 0 a:reduce . cr
bucket unlock drop ;
\ Get current value of bucket #x
: bucket@ \ n -- bucket[n]
bucket @
swap a:@ nip ;
\ Transfer x from bucket n to bucket m
: bucket-xfer \ m n x --
>r bucket @
\ m n bucket
over a:@ r@ n:-
rot swap a:!
\ m bucket
over a:@ r> n:+
rot swap a:!
drop ;
\ Get two random indices to check (ensure they're not the same):
: pick2
rand-pcg n:abs bucket-size @ n:mod dup >r
repeat
drop
rand-pcg n:abs bucket-size @ n:mod
r@ over n:=
while!
r> ;
\ Pick two buckets and make them more equal (by a quarter of their difference):
: make-equal
repeat
pick2
bucket lock @
third a:@ >r
over a:@ r> n:-
\ if they are equal, do nothing
dup not if
\ equal, so do nothing
drop -rot 2drop
else
4 n:/ n:int
>r -rot r>
bucket-xfer
then
drop
bucket unlock drop
again ;
\ Moves a quarter of the smaller value from one (random) bucket to another:
: make-redist
repeat
pick2 bucket lock @
\ n m bucket
over a:@ >r \ n m b b[m]
third a:@ r> \ n m b b[n]
n:min 4 n:/ n:int
nip bucket-xfer
bucket unlock drop
again ;
: app:main
\ create 10 buckets with random positive integer values:
10 genbucket bucket @ a:len bucket-size ! drop
\ print the bucket
.bucket
\ the problem's tasks:
' make-equal t:task
' make-redist t:task
\ the print-the-bucket task. We'll do it just 10 times and then quit:
( 1 sleep .bucket ) 10 times
bye ; |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #11l | 11l | V a = 5
assert(a == 42)
assert(a == 42, ‘Error message’) |
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
| #Go | Go | package main
import "fmt"
func main() {
fmt.Println(mode([]int{2, 7, 1, 8, 2}))
fmt.Println(mode([]int{2, 7, 1, 8, 2, 8}))
}
func mode(a []int) []int {
m := make(map[int]int)
for _, v := range a {
m[v]++
}
var mode []int
var n int
for k, v := range m {
switch {
case v < n:
case v > n:
n = v
mode = append(mode[:0], k)
default:
mode = append(mode, k)
}
}
return mode
} |
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
| #Aime | Aime | real
mean(list l)
{
real sum, x;
sum = 0;
for (, x in l) {
sum += x;
}
sum / ~l;
}
integer
main(void)
{
o_form("%f\n", mean(list(4.5, 7.25, 5r, 5.75)));
0;
} |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #ALGOL_68 | ALGOL 68 | PROC mean = (REF[]REAL p)REAL:
# Calculates the mean of qty REALs beginning at p. #
IF LWB p > UPB p THEN 0.0
ELSE
REAL total := 0.0;
FOR i FROM LWB p TO UPB p DO total +:= p[i] OD;
total / (UPB p - LWB p + 1)
FI;
main:(
[6]REAL test := (1.0, 2.0, 5.0, -5.0, 9.5, 3.14159);
print((mean(test),new line))
) |
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
| #AWK | AWK |
# syntax: GAWK -f ASSOCIATIVE_ARRAY_MERGING.AWK
#
# sorting:
# PROCINFO["sorted_in"] is used by GAWK
# SORTTYPE is used by Thompson Automation's TAWK
#
BEGIN {
PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 1
arr1["name"] = "Rocket Skates"
arr1["price"] = "12.75"
arr1["color"] = "yellow"
show_array(arr1,"base")
arr2["price"] = "15.25"
arr2["color"] = "red"
arr2["year"] = "1974"
show_array(arr2,"update")
for (i in arr1) { arr3[i] = arr1[i] }
for (i in arr2) { arr3[i] = arr2[i] }
show_array(arr3,"merged")
exit(0)
}
function show_array(arr,desc, i) {
printf("\n%s array\n",desc)
for (i in arr) {
printf("%-5s : %s\n",i,arr[i])
}
}
|
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
| #B4X | B4X | Dim m1 As Map = CreateMap("name": "Rocket Skates", "price": 12.75, "color": "yellow")
Dim m2 As Map = CreateMap("price": 15.25, "color": "red", "year": 1974)
Dim merged As Map
merged.Initialize
For Each m As Map In Array(m1, m2)
For Each key As Object In m.Keys
merged.Put(key, m.Get(key))
Next
Next
Log(merged) |
http://rosettacode.org/wiki/Average_loop_length | Average loop length | Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence.
Task
Write a program or a script that estimates, for each N, the average length until the first such repetition.
Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.
This problem comes from the end of Donald Knuth's Christmas tree lecture 2011.
Example of expected output:
N average analytical (error)
=== ========= ============ =========
1 1.0000 1.0000 ( 0.00%)
2 1.4992 1.5000 ( 0.05%)
3 1.8784 1.8889 ( 0.56%)
4 2.2316 2.2188 ( 0.58%)
5 2.4982 2.5104 ( 0.49%)
6 2.7897 2.7747 ( 0.54%)
7 3.0153 3.0181 ( 0.09%)
8 3.2429 3.2450 ( 0.07%)
9 3.4536 3.4583 ( 0.14%)
10 3.6649 3.6602 ( 0.13%)
11 3.8091 3.8524 ( 1.12%)
12 3.9986 4.0361 ( 0.93%)
13 4.2074 4.2123 ( 0.12%)
14 4.3711 4.3820 ( 0.25%)
15 4.5275 4.5458 ( 0.40%)
16 4.6755 4.7043 ( 0.61%)
17 4.8877 4.8579 ( 0.61%)
18 4.9951 5.0071 ( 0.24%)
19 5.1312 5.1522 ( 0.41%)
20 5.2699 5.2936 ( 0.45%)
| #D | D | import std.stdio, std.random, std.math, std.algorithm, std.range, std.format;
real analytical(in int n) pure nothrow @safe /*@nogc*/ {
enum aux = (int k) => reduce!q{a * b}(1.0L, iota(n - k + 1, n + 1));
return iota(1, n + 1)
.map!(k => (aux(k) * k ^^ 2) / (real(n) ^^ (k + 1)))
.sum;
}
size_t loopLength(size_t maxN)(in int size, ref Xorshift rng) {
__gshared static bool[maxN + 1] seen;
seen[0 .. size + 1] = false;
int current = 1;
size_t steps = 0;
while (!seen[current]) {
seen[current] = true;
current = uniform(1, size + 1, rng);
steps++;
}
return steps;
}
void main() {
enum maxN = 40;
enum nTrials = 300_000;
auto rng = Xorshift(unpredictableSeed);
writeln(" n average analytical (error)");
writeln("=== ========= ============ ==========");
foreach (immutable n; 1 .. maxN + 1) {
long total = 0;
foreach (immutable _; 0 .. nTrials)
total += loopLength!maxN(n, rng);
immutable average = total / real(nTrials);
immutable an = n.analytical;
immutable percentError = abs(an - average) / an * 100;
immutable errorS = format("%2.4f", percentError);
writefln("%3d %9.5f %12.5f (%7s%%)",
n, average, an, errorS);
}
} |
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
| #PicoLisp | PicoLisp | (de sma (@Len)
(curry (@Len (Data)) (N)
(push 'Data N)
(and (nth Data @Len) (con @)) # Truncate
(*/ (apply + Data) (length Data)) ) ) |
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.
| #C | C | #include <stdio.h>
#define TRUE 1
#define FALSE 0
#define MAX 120
typedef int bool;
bool is_prime(int n) {
int d = 5;
if (n < 2) return FALSE;
if (!(n % 2)) return n == 2;
if (!(n % 3)) return n == 3;
while (d *d <= n) {
if (!(n % d)) return FALSE;
d += 2;
if (!(n % d)) return FALSE;
d += 4;
}
return TRUE;
}
int count_prime_factors(int n) {
int count = 0, f = 2;
if (n == 1) return 0;
if (is_prime(n)) return 1;
while (TRUE) {
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;
}
}
int main() {
int i, n, count = 0;
printf("The attractive numbers up to and including %d are:\n", MAX);
for (i = 1; i <= MAX; ++i) {
n = count_prime_factors(i);
if (is_prime(n)) {
printf("%4d", i);
if (!(++count % 20)) printf("\n");
}
}
printf("\n");
return 0;
} |
http://rosettacode.org/wiki/Averages/Mean_time_of_day | Averages/Mean time of day | Task[edit]
A particular activity of bats occurs at these times of the day:
23:00:17, 23:40:20, 00:12:45, 00:17:19
Using the idea that there are twenty-four hours in a day,
which is analogous to there being 360 degrees in a circle,
map times of day to and from angles;
and using the ideas of Averages/Mean angle
compute and show the average time of the nocturnal activity
to an accuracy of one second of time.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Const pi As Double = 3.1415926535897932
Function meanAngle(angles() As Double) As Double
Dim As Integer length = Ubound(angles) - Lbound(angles) + 1
Dim As Double sinSum = 0.0
Dim As Double cosSum = 0.0
For i As Integer = LBound(angles) To UBound(angles)
sinSum += Sin(angles(i) * pi / 180.0)
cosSum += Cos(angles(i) * pi / 180.0)
Next
Return Atan2(sinSum / length, cosSum / length) * 180.0 / pi
End Function
' time string assumed to be in format "hh:mm:ss"
Function timeToSecs(t As String) As Integer
Dim As Integer hours = Val(Left(t, 2))
Dim As Integer mins = Val(Mid(t, 4, 2))
Dim As Integer secs = Val(Right(t, 2))
Return 3600 * hours + 60 * mins + secs
End Function
' 1 second of time = 360/(24 * 3600) = 1/240th degree
Function timeToDegrees(t As String) As Double
Dim secs As Integer = timeToSecs(t)
Return secs/240.0
End Function
Function degreesToTime(d As Double) As String
If d < 0 Then d += 360.0
Dim secs As Integer = d * 240.0
Dim hours As Integer = secs \ 3600
Dim mins As Integer = secs Mod 3600
secs = mins Mod 60
mins = mins \ 60
Dim hBuffer As String = Right("0" + Str(hours), 2)
Dim mBuffer As String = Right("0" + Str(mins), 2)
Dim sBuffer As String = Right("0" + Str(secs), 2)
Return hBuffer + ":" + mBuffer + ":" + sBuffer
End Function
Dim tm(1 To 4) As String = {"23:00:17", "23:40:20", "00:12:45", "00:17:19"}
Dim angles(1 To 4) As Double
For i As Integer = 1 To 4
angles(i) = timeToDegrees(tm(i))
Next
Dim mean As Double = meanAngle(angles())
Print "Average time is : "; degreesToTime(mean)
Print
Print "Press any key to quit"
Sleep |
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.
| #Generic | Generic |
space system
{
enum state
{
header
balanced
left_high
right_high
}
enum direction
{
from_left
from_right
}
class node
{
left
right
parent
balance
data
node()
{
left = this
right = this
balance = state.header
parent = null
data = null
}
node(root d)
{
left = null
right = null
parent = root
balance = state.balanced
data = d
}
is_header
{
get
{
return balance == state.header
}
}
next
{
get
{
if is_header return left
if !right.null()
{
n = right
while !n.left.null() n = n.left
return n
}
else
{
y = parent
if y.is_header return y
n = this
while n == y.right
{
n = y
y = y.parent
if y.is_header break
}
return y
}
}
}
previous
{
get
{
if is_header return right
if !left.null()
{
n = left
while !n.right.null() n = right
return n
}
else
{
y = parent
if y.is_header return y
n = this
while n == y.left
{
n = y
y = y.parent
if y.is_header break
}
return y
}
}
}
rotate_left()
{
_right = right
_parent = parent
parent = _right
_right.parent = _parent
if !_right.left.null() _right.left.parent = this
right = _right.left
_right.left = this
this = _right
}
rotate_right()
{
_left = left
_parent = parent
parent = _left
_left.parent = _parent
if !_left.right.null() _left.right.parent = this
left = _left.right
_left.right = this
this = _left
}
balance_left()
{
select left.balance
{
left_high
{
balance = state.balanced
left.balance = state.balanced
rotate_right()
}
right_high
{
subright = left.right
select subright.balance
{
balanced
{
balance = state.balanced
left.balance = state.balanced
}
right_high
{
balance = state.balanced
left.balance = state.left_high
}
left_high
{
balance = state.right_high
lehpt.balance = state.balanced
}
}
subright.balance = state.balanced
left.rotate_left()
rotate_right()
}
balanced
{
balance = state.left_high
left.balance = state.right_high
rotate_right()
}
}
}
balance_right()
{
select right.balance
{
right_high
{
balance = state.balanced
right.balance = state.balanced
rotate_left()
}
left_high
{
subleft = right.left
select subleft.balance
{
balanced
{
balance = state.balanced
right.balance = state.balanced
}
left_high
{
balance = state.balanced
right.balance = state.right_high
}
right_high
{
balance = state.left_high
right.balance = state.balanced
}
}
subleft.balance = state.balanced
right.rotate_right()
rotate_left()
}
balanced
{
balance = state.right_high
right.balance = state.left_high
rotate_left()
}
}
}
balance_tree(from)
{
taller = true
while taller
{
p = parent
next_from = direction.from_left
if this != parent.left next_from = direction.from_right
if from == direction.from_left
select balance
{
left_high
{
if parent.is_header
parent.parent.balance_left()
else
{
if parent.left == this
parent.left.balance_left()
else
parent.right.balance_left()
taller = false
}
}
balanced
{
balance = state.left_high
taller = true
}
right_high
{
balance = state.balanced
taller = false
}
}
else
select balance
{
left_high
{
balance = state.balanced
taller = false
}
balanced
{
balance = state.right_high
taller = true
}
right_high
{
if parent.is_header
parent.parent.balance_right()
else
{
if parent.left == this
parent.left.balance_right()
else
parent.right.balance_right()
}
taller = false
}
}
if taller
{
if p.is_header
taller = false
else
{
this = p
from = next_from
}
}
}
}
balance_tree_remove(from)
{
shorter = true
while shorter
{
next_from = direction.from_left
if this != parent.left next_from = direction.from_right
if from == direction.from_left
select balance
{
left_high
{
balance = state.balanced
shorter = true
}
balanced
{
balance = state.right_high
shorter = false
}
right_high
{
if right.balance == state.right_high
shorter = false
else
shorter = true
if parent.is_header
parent.parent.balance_right()
else
{
if parent.left == this
parent.left.balance_right()
else
parent.right.balance_right()
}
}
}
else
select balance
{
right_high
{
balance = state.balanced
shorter = true
}
balanced
{
balance = state.left_high
shorter = false
}
left_high
{
if left.balance == state.balanced
shorter = false
else
shorter = true
if parent.is_header
parent.parent.balance_left()
else
{
if parent.is_header
parent.left.balance_left()
else
parent.right.balance_left()
}
}
}
if shorter
{
if parent.is_header
shorter = false
else
{
this = parent
from = next_from
}
}
}
}
count
{
get
{
result = +a
if !null()
{
cleft = +a
if !left.null() cleft = left.count
cright = +a
if !right.null() cright = right.count
result = result + cleft + cright + +b
}
return result
}
}
depth
{
get
{
result = +a
if !null()
{
cleft = +a
if !left.null() cleft = left.depth
cright = +a
if !right.null() cright = right.depth
if cleft > cright
result = cleft + +b
else
result = cright + +b
}
return result
}
}
}
class default_comparer
{
default_comparer() {}
compare_to(a b)
{
if a < b return -1
if b < a return 1
return 0
}
}
class set
{
header
iterator
comparer
set()
{
header = node()
iterator = null
comparer = default_comparer()
}
set(c_set)
{
header = node()
iterator = null
comparer = c_set
}
left_most
{
get
{
return header.left
}
set
{
header.left = value
}
}
right_most
{
get
{
return header.right
}
set
{
header.right = value
}
}
root
{
get
{
return header.parent
}
set
{
header.parent = value
}
}
empty
{
get
{
return header.parent.null()
}
}
operator<<(data)
{
if header.parent.null()
{
root = node(header data)
left_most = root
right_most = root
}
else
{
node = root
repeat
{
result = comparer.compare_to(data node.data)
if result < 0
{
if !node.left.null()
node = node.left
else
{
new_node = node(node data)
node.left = new_node
if left_most == node left_most = new_node
node.balance_tree(direction.from_left)
break
}
}
else if result > 0
{
if !node.right.null()
node = node.right
else
{
new_node = node(node data)
node.right = new_node
if right_most == node right_most = new_node
node.balance_tree(direction.from_right)
break
}
}
else // item already exists
throw "entry " + (string)data + " already exists"
}
}
return this
}
update(data)
{
if empty
{
root = node(header data)
left_most = root
right_most = root
}
else
{
node = root
repeat
{
result = comparer.compare_to(data node.data)
if result < 0
{
if !node.left.null()
node = node.left
else
{
new_node = node(node data)
node.left = new_node
if left_most == node left_most = new_node
node.balance_tree(direction.from_left)
break
}
}
else if result > 0
{
if !node.right.null()
node = node.right
else
{
new_node = node(node data)
node.right = new_node
if right_most == node right_most = new_node
node.balance_tree(direction.from_right)
break
}
}
else // item already exists
{
node.data = data
break
}
}
}
}
operator>>(data)
{
node = root
repeat
{
if node.null()
{
throw "entry " + (string)data + " not found"
}
result = comparer.compare_to(data node.data)
if result < 0
node = node.left
else if result > 0
node = node.right
else // item found
{
if !node.left.null() && !node.right.null()
{
replace = node.left
while !replace.right.null() replace = replace.right
temp = node.data
node.data = replace.data
replace.data = temp
node = replace
}
from = direction.from_left
if node != node.parent.left from = direction.from_right
if left_most == node
{
next = node
next = next.next
if header == next
{
left_most = header
right_most = header
}
else
left_most = next
}
if right_most == node
{
previous = node
previous = previous.previous
if header == previous
{
left_most = header
right_most = header
}
else
right_most = previous
}
if node.left.null()
{
if node.parent == header
root = node.right
else
{
if node.parent.left == node
node.parent.left = node.right
else
node.parent.right = node.right
}
if !node.right.null()
node.right.parent = node.parent
}
else
{
if node.parent == header
root = node.left
else
{
if node.parent.left == node
node.parent.left = node.left
else
node.parent.right = node.left
}
if !node.left.null()
node.left.parent = node.parent
}
node.parent.balance_tree_remove(from)
break
}
}
return this
}
remove(data)
{
node = root
repeat
{
if node.null()
{
throw "entry " + (string)data + " not found"
}
result = comparer.compare_to(data node.data)
if result < 0
node = node.left
else if result > 0
node = node.right
else // item found
{
if !node.left.null() && !node.right.null()
{
replace = node.left
while !replace.right.null() replace = replace.right
temp = node.data
node.data = replace.data
replace.data = temp
node = replace
}
from = direction.from_left
if node != node.parent.left from = direction.from_right
if left_most == node
{
next = node
next = next.next
if header == next
{
left_most = header
right_most = header
}
else
left_most = next
}
if right_most == node
{
previous = node
previous = previous.previous
if header == previous
{
left_most = header
right_most = header
}
else
right_most = previous
}
if node.left.null()
{
if node.parent == header
root = node.right
else
{
if node.parent.left == node
node.parent.left = node.right
else
node.parent.right = node.right
}
if !node.right.null()
node.right.parent = node.parent
}
else
{
if node.parent == header
root = node.left
else
{
if node.parent.left == node
node.parent.left = node.left
else
node.parent.right = node.left
}
if !node.left.null()
node.left.parent = node.parent
}
node.parent.balance_tree_remove(from)
break
}
}
return this
}
remove2(data)
{
node = root
repeat
{
if node.null()
{
return null
}
result = comparer.compare_to(data node.data)
if result < 0
node = node.left
else if result > 0
node = node.right
else // item found
{
if !node.left.null() && !node.right.null()
{
replace = node.left
while !replace.right.null() replace = replace.right
temp = node.data
node.data = replace.data
replace.data = temp
node = replace
}
from = direction.from_left
if node != node.parent.left from = direction.from_right
if left_most == node
{
next = node
next = next.next
if header == next
{
left_most = header
right_most = header
}
else
left_most = next
}
if right_most == node
{
previous = node
previous = previous.previous
if header == previous
{
left_most = header
right_most = header
}
else
right_most = previous
}
if node.left.null()
{
if node.parent == header
root = node.right
else
{
if node.parent.left == node
node.parent.left = node.right
else
node.parent.right = node.right
}
if !node.right.null()
node.right.parent = node.parent
}
else
{
if node.parent == header
root = node.left
else
{
if node.parent.left == node
node.parent.left = node.left
else
node.parent.right = node.left
}
if !node.left.null()
node.left.parent = node.parent
}
node.parent.balance_tree_remove(from)
break
}
}
}
operator[data]
{
get
{
if empty
{
return false
}
else
{
node = root
repeat
{
result = comparer.compare_to(data node.data)
if result < 0
{
if !node.left.null()
node = node.left
else
return false
}
else if result > 0
{
if !node.right.null()
node = node.right
else
return false
}
else // item exists
return true
}
}
}
}
get(data)
{
if empty throw "empty collection"
node = root
repeat
{
result = comparer.compare_to(data node.data)
if result < 0
{
if !node.left.null()
node = node.left
else
throw "item: " + (string)data + " not found in collection"
}
else if result > 0
{
if !node.right.null()
node = node.right
else
throw "item: " + (string)data + " not found in collection"
}
else // item exists
return node.data
}
}
last
{
get
{
if empty
throw "empty set"
else
return header.right.data
}
}
iterate()
{
if iterator.null()
{
iterator = left_most
if iterator == header
return iterator(false none())
else
return iterator(true iterator.data)
}
else
{
iterator = iterator.next
if iterator == header
return iterator(false none())
else
return iterator(true iterator.data)
}
}
count
{
get
{
return root.count
}
}
depth
{
get
{
return root.depth
}
}
operator==(compare)
{
if this < compare return false
if compare < this return false
return true
}
operator!=(compare)
{
if this < compare return true
if compare < this return true
return false
}
operator<(c)
{
first1 = begin
last1 = end
first2 = c.begin
last2 = c.end
while first1 != last1 && first2 != last2
{
result = comparer.compare_to(first1.data first2.data)
if result >= 0
{
first1 = first1.next
first2 = first2.next
}
else return true
}
a = count
b = c.count
return a < b
}
begin { get { return header.left } }
end { get { return header } }
operator string()
{
out = "{"
first1 = begin
last1 = end
while first1 != last1
{
out = out + (string)first1.data
first1 = first1.next
if first1 != last1 out = out + ","
}
out = out + "}"
return out
}
operator|(b)
{
r = new set()
first1 = begin
last1 = end
first2 = b.begin
last2 = b.end
while first1 != last1 && first2 != last2
{
result = comparer.compare_to(first1.data first2.data)
if result < 0
{
r << first1.data
first1 = first1.next
}
else if result > 0
{
r << first2.data
first2 = first2.next
}
else
{
r << first1.data
first1 = first1.next
first2 = first2.next
}
}
while first1 != last1
{
r << first1.data
first1 = first1.next
}
while first2 != last2
{
r << first2.data
first2 = first2.next
}
return r
}
operator&(b)
{
r = new set()
first1 = begin
last1 = end
first2 = b.begin
last2 = b.end
while first1 != last1 && first2 != last2
{
result = comparer.compare_to(first1.data first2.data)
if result < 0
{
first1 = first1.next
}
else if result > 0
{
first2 = first2.next
}
else
{
r << first1.data
first1 = first1.next
first2 = first2.next
}
}
return r
}
operator^(b)
{
r = new set()
first1 = begin
last1 = end
first2 = b.begin
last2 = b.end
while first1 != last1 && first2 != last2
{
result = comparer.compare_to(first1.data first2.data)
if result < 0
{
r << first1.data
first1 = first1.next
}
else if result > 0
{
r << first2.data
first2 = first2.next
}
else
{
first1 = first1.next
first2 = first2.next
}
}
while first1 != last1
{
r << first1.data
first1 = first1.next
}
while first2 != last2
{
r << first2.data
first2 = first2.next
}
return r
}
operator-(b)
{
r = new set()
first1 = begin
last1 = end
first2 = b.begin
last2 = b.end
while first1 != last1 && first2 != last2
{
result = comparer.compare_to(first1.data first2.data)
if result < 0
{
r << first1.data
first1 = first1.next
}
else if result > 0
{
r << first2.data
first1 = first1.next
first2 = first2.next
}
else
{
first1 = first1.next
first2 = first2.next
}
}
while first1 != last1
{
r << first1.data
first1 = first1.next
}
return r
}
}
class tree
{
s
tree()
{
s = set()
}
operator<<(e)
{
s << e
return this
}
operator[key]
{
get
{
if empty
throw "entry not found exception"
else
{
node = s.root
repeat
{
if key < node.data
{
if !node.left.null()
node = node.left
else
throw "entry not found exception"
}
else
{
if key == node.data
return node.data
else
{
if !node.right.null()
node = node.right
else
throw "entry not found exception"
}
}
}
}
}
}
operator>>(e)
{
entry = this[e]
s >> entry
}
remove(key)
{
s >> key_value(key)
}
iterate()
{
return s.iterate()
}
count
{
get
{
return s.count
}
}
empty
{
get
{
return s.empty
}
}
last
{
get
{
if empty
throw "empty tree"
else
return s.last
}
}
operator string()
{
return (string)s
}
}
class dictionary
{
s
dictionary()
{
s = set()
}
operator<<(key_value)
{
s << key_value
return this
}
add(key value)
{
s << key_value(key value)
}
operator[key]
{
set
{
try { s >> key_value(key) } catch {}
s << key_value(key value)
}
get
{
r = s.get(key_value(key))
return r.value
}
}
operator>>(key)
{
s >> key_value(key)
return this
}
iterate()
{
return s.iterate()
}
count
{
get
{
return s.count
}
}
operator string()
{
return (string)s
}
}
class key_value
{
key
value
key_value(key_set)
{
key = key_set
value = nul
}
key_value(key_set value_set)
{
key = key_set
value = value_set
}
operator<(kv)
{
return key < kv.key
}
operator string()
{
if value.nul()
return "(" + (string)key + " null)"
else
return "(" + (string)key + " " + (string)value + ")"
}
}
class array
{
s // this is a set of key/value pairs.
iterator // this field holds an iterator for the array.
array() // no parameters required phor array construction.
{
s = set() // create a set of key/value pairs.
iterator = null // the iterator is initially set to null.
}
begin { get { return s.header.left } } // property: used to commence manual iteration.
end { get { return s.header } } // property: used to define the end item of iteration.
operator<(a) // less than operator is called by the avl tree algorithms
{ // this operator implies phor instance that you could potentially have sets of arrays.
if keys < a.keys // compare the key sets first.
return true
else if a.keys < keys
return false
else // the key sets are equal therephore compare array elements.
{
first1 = begin
last1 = end
first2 = a.begin
last2 = a.end
while first1 != last1 && first2 != last2
{
if first1.data.value < first2.data.value
return true
else
{
if first2.data.value < first1.data.value
return false
else
{
first1 = first1.next
first2 = first2.next
}
}
}
return false
}
}
operator==(compare) // equals and not equals derive from operator<
{
if this < compare return false
if compare < this return false
return true
}
operator!=(compare)
{
if this < compare return true
if compare < this return true
return false
}
operator<<(e) // this operator adds an element to the end of the array.
{
try
{
this[s.last.key + +b] = e
}
catch
{
this[+a] = e
}
return this
}
operator[key] // this is the array indexer.
{
set
{
try { s >> key_value(key) } catch {}
s << key_value(integer(key) value)
}
get
{
result = s.get(key_value(key))
return result.value
}
}
operator>>(key) // this operator removes an element from the array.
{
s >> key_value(key)
return this
}
iterate() // and this is how to iterate on the array.
{
if iterator.null()
{
iterator = s.left_most
if iterator == s.header
return iterator(false none())
else
return iterator(true iterator.data.value)
}
else
{
iterator = iterator.next
if iterator == s.header
{
iterator = null
return iterator(false none())
}
else
return iterator(true iterator.data.value)
}
}
count // this property returns a count of elements in the array.
{
get
{
return s.count
}
}
empty // is the array empty? (Property of course).
{
get
{
return s.empty
}
}
last // returns the value of the last element in the array.
{
get
{
if empty
throw "empty array"
else
return s.last.value
}
}
📟 string() // converts the array to a string
{
out = "{"
iterator = s.left_most
while iterator != s.header
{
_value = iterator.data.value
out = out + (string)_value
if iterator != s.right_most
out = out + ","
iterator = iterator.next
}
out = out + "}"
return out
}
keys // return the set of keys of the array (a set of integers).
{
get
{
k = set()
for e s k << e.key
return k
}
}
sort // unloads the set into a value and reloads in sorted order.
{
get
{
sort_bag = bag()
for e s sort_bag << e.value
a = new array()
for g sort_bag a << g
return a
}
}
}
// and here is a test program
using system
space sampleB
{
sampleB()
{
try
{
🌳 = { "A" "B" "C" } // create a tree
🌳 << "D" << "E"
🎛️ << "Found: " << 🌳["B"] << "\n"
for inst 🌳 🎛️ << inst << "\n"
🎛️ << 🌳 << "\n"
💰 = bag() { 1 1 2 3 } // create a bag
🎛️ << 💰 << "\n"
🪣 = ["D" "C" "B" "A"] // create an array
🎛️ << 🪣 << "\n"
🎛️ << 🪣.sort << "\n"
🪣[4] = "E"
🎛️ << 🪣 << "\n"
📘 = <[0 "hello"] [1 "world"]> // create a dictionary
🎛️ << 📘 << "\n"
📘[2] = "goodbye"
🎛️ << 📘 << "\n"
}
catch
{
🎛️ << exception << "\n"
}
}
}
// The output of the program is shown below.
Found: B
A
B
C
D
E
{A,B,C,D,E}
{1,1,2,3}
{D,C,B,A}
{A,B,C,D}
{D,C,B,A,E}
{(0 hello),(1 world)}
{(0 hello),(1 world),(2 goodbye)} |
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
| #Euler_Math_Toolbox | Euler Math Toolbox | >function meanangle (a) ...
$ z=sum(exp(rad(a)*I));
$ if z~=0 then error("Not meaningful");
$ else return deg(arg(z))
$ endfunction
>meanangle([350,10])
0
>meanangle([90,180,270,360])
Error : Not meaningful
Error generated by error() command
Error in function meanangle in line
if z~=0 then error("Not meaningful");
>meanangle([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
| #Euphoria | Euphoria |
include std/console.e
include std/mathcons.e
sequence AngleList = {{350,10},{90,180,270,360},{10,20,30}}
function atan2(atom y, atom x)
return 2*arctan((sqrt(power(x,2)+power(y,2)) - x)/y)
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
for i = 1 to length(AngleList) do
printf(1,"Mean Angle for set %d: %3.5f\n",{i,MeanAngle(AngleList[i])})
end for
if getc(0) then end if
|
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
| #BQN | BQN | Median ← (+´÷≠)∧⊏˜2⌊∘÷˜¯1‿0+≠
Median 5.961475‿2.025856‿7.262835‿1.814272‿2.281911‿4.854716 |
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
| #Bracmat | Bracmat | (median=
begin decimals end int list med med1 med2 num number
. 0:?list
& whl
' ( @( !arg
: ?
((%@:~" ":~",") ?:?number)
((" "|",") ?arg|:?arg)
)
& @( !number
: ( #?int "." [?begin #?decimals [?end
& !int+!decimals*10^(!begin+-1*!end):?num
| ?num
)
)
& (!num.)+!list:?list
)
& !list:?+[?end
& ( !end*1/2:~/
& !list:?+[!(=1/2*!end+-1)+(?med1.)+(?med2.)+?
& !med1*1/2+!med2*1/2:?med
| !list:?+[(div$(1/2*!end,1))+(?med.)+?
)
& !med
); |
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
| #Forth | Forth | : famean ( faddr n -- f )
0e
tuck floats bounds do
i f@ f+
float +loop
0 d>f f/ ;
: fgmean ( faddr n -- f )
1e
tuck floats bounds do
i f@ f*
float +loop
0 d>f 1/f f** ;
: fhmean ( faddr n -- f )
dup 0 d>f 0e
floats bounds do
i f@ 1/f f+
float +loop
f/ ;
create test 1e f, 2e f, 3e f, 4e f, 5e f, 6e f, 7e f, 8e f, 9e f, 10e f,
test 10 famean fdup f.
test 10 fgmean fdup fdup f.
test 10 fhmean fdup f.
( A G G H )
f>= . f>= . \ -1 -1 |
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.
| #Icon_and_Unicon | Icon and Unicon | procedure main()
a := "+-0++0+"
write("a = +-0++0+"," = ",cvtFromBT("+-0++0+"))
write("b = -436 = ",b := cvtToBT(-436))
c := "+-++-"
write("c = +-++- = ",cvtFromBT("+-++-"))
d := mul(a,sub(b,c))
write("a(b-c) = ",d," = ",cvtFromBT(d))
end
procedure bTrim(s)
return s[upto('+-',s):0] | "0"
end
procedure cvtToBT(n)
if n=0 then return "0"
if n<0 then return map(cvtToBT(-n),"+-","-+")
return bTrim(case n%3 of {
0: cvtToBT(n/3)||"0"
1: cvtToBT(n/3)||"+"
2: cvtToBT((n+1)/3)||"-"
})
end
procedure cvtFromBT(n)
sum := 0
i := -1
every c := !reverse(n) do {
sum +:= case c of {
"+" : 1
"-" : -1
"0" : 0
}*(3^(i+:=1))
}
return sum
end
procedure neg(n)
return map(n,"+-","-+")
end
procedure add(a,b)
if *b > *a then a :=: b
b := repl("0",*a-*b)||b
c := "0"
sum := ""
every place := 1 to *a do {
ds := addDigits(a[-place],b[-place],c)
c := if *ds > 1 then c := ds[1] else "0"
sum := ds[-1]||sum
}
return bTrim(c||sum)
end
procedure addDigits(a,b,c)
sum1 := addDigit(a,b)
sum2 := addDigit(sum1[-1],c)
if *sum1 = 1 then return sum2
if *sum2 = 1 then return sum1[1]||sum2
return sum1[1]
end
procedure addDigit(a,b)
return case(a||b) of {
"00"|"0+"|"0-": b
"+0"|"-0" : a
"++" : "+-"
"+-"|"-+" : "0"
"--" : "-+"
}
end
procedure sub(a,b)
return add(a,neg(b))
end
procedure mul(a,b)
if b[1] == "-" then {
b := neg(b)
negate := "yes"
}
b := cvtFromBT(b)
i := "+"
mul := "0"
while cvtFromBT(i) <= b do {
mul := add(mul,a)
i := add(i,"+")
}
return (\negate,map(mul,"+-","-+")) | mul
end |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #PARI.2FGP | PARI/GP | m=269696;
k=1000000;
{for(n=1,99736,
\\ Try each number in this range, from 1 to 99736
if(denominator((n^2-m)/k)==1, \\ Check if n squared, minus m, is divisible by k
return(n) \\ If so, return this number and STOP.
)
)} |
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
| #Befunge | Befunge | v > "KO TON" ,,,,,, v
> ~ : 25*- #v_ $ | > 25*, @
> "KO" ,, ^
> : 1991+*+- #v_ v
> \ : 1991+*+- #v_v
\ $
^ < <$< |
http://rosettacode.org/wiki/Atomic_updates | Atomic updates |
Task
Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to:
get the current value of any bucket
remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the transferred amount to ensure the values remain non-negative
In order to exercise this data type, create one set of buckets, and start three concurrent tasks:
As often as possible, pick two buckets and make their values closer to equal.
As often as possible, pick two buckets and arbitrarily redistribute their values.
At whatever rate is convenient, display (by any means) the total value and, optionally, the individual values of each bucket.
The display task need not be explicit; use of e.g. a debugger or trace tool is acceptable provided it is simple to set up to provide the display.
This task is intended as an exercise in atomic operations. The sum of the bucket values must be preserved even if the two tasks attempt to perform transfers simultaneously, and a straightforward solution is to ensure that at any time, only one transfer is actually occurring — that the transfer operation is atomic.
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
procedure Test_Updates is
type Bucket_Index is range 1..13;
package Random_Index is new Ada.Numerics.Discrete_Random (Bucket_Index);
use Random_Index;
type Buckets is array (Bucket_Index) of Natural;
protected type Safe_Buckets is
procedure Initialize (Value : Buckets);
function Get (I : Bucket_Index) return Natural;
procedure Transfer (I, J : Bucket_Index; Amount : Integer);
function Snapshot return Buckets;
private
Data : Buckets := (others => 0);
end Safe_Buckets;
protected body Safe_Buckets is
procedure Initialize (Value : Buckets) is
begin
Data := Value;
end Initialize;
function Get (I : Bucket_Index) return Natural is
begin
return Data (I);
end Get;
procedure Transfer (I, J : Bucket_Index; Amount : Integer) is
Increment : constant Integer :=
Integer'Max (-Data (J), Integer'Min (Data (I), Amount));
begin
Data (I) := Data (I) - Increment;
Data (J) := Data (J) + Increment;
end Transfer;
function Snapshot return Buckets is
begin
return Data;
end Snapshot;
end Safe_Buckets;
Data : Safe_Buckets;
task Equalize;
task Mess_Up;
task body Equalize is
Dice : Generator;
I, J : Bucket_Index;
begin
loop
I := Random (Dice);
J := Random (Dice);
Data.Transfer (I, J, (Data.Get (I) - Data.Get (J)) / 2);
end loop;
end Equalize;
task body Mess_Up is
Dice : Generator;
begin
loop
Data.Transfer (Random (Dice), Random (Dice), 100);
end loop;
end Mess_Up;
begin
Data.Initialize ((1,2,3,4,5,6,7,8,9,10,11,12,13));
loop
delay 1.0;
declare
State : Buckets := Data.Snapshot;
Sum : Natural := 0;
begin
for Index in State'Range loop
Sum := Sum + State (Index);
Put (Integer'Image (State (Index)));
end loop;
Put (" =" & Integer'Image (Sum));
New_Line;
end;
end loop;
end Test_Updates; |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #68000_Assembly | 68000 Assembly | CMP.L #42,D0
BEQ continue
ILLEGAL ;jumps to Trap 4. Alternatively, other trap numbers could have been chosen with the "TRAP #" command.
continue:
; rest of program |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Ada | Ada | pragma Assert (A = 42, "Oops!"); |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Aime | Aime | integer x;
x = 41;
if (x != 42) {
error("x is not 42");
} |
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
| #Groovy | Groovy | def mode(Iterable col) {
assert col
def m = [:]
col.each {
m[it] = m[it] == null ? 1 : m[it] + 1
}
def keys = m.keySet().sort { -m[it] }
keys.findAll { m[it] == m[keys[0]] }
} |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #ALGOL_W | ALGOL W | begin
% procedure to find the mean of the elements of a vector. %
% As the procedure can't find the bounds of the array for itself, %
% we pass them in lb and ub %
real procedure mean ( real array vector ( * )
; integer value lb
; integer value ub
) ;
begin
real sum;
assert( ub > lb ); % terminate the program if there are no elements %
sum := 0;
for i := lb until ub do sum := sum + vector( i );
sum / ( ( ub + 1 ) - lb )
end mean ;
% test the mean procedure by finding the mean of 1.1, 2.2, 3.3, 4.4, 5.5 %
real array numbers ( 1 :: 5 );
for i := 1 until 5 do numbers( i ) := i + ( i / 10 );
r_format := "A"; r_w := 10; r_d := 2; % set fixed point output %
write( mean( numbers, 1, 5 ) );
end. |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for 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
| #AmigaE | AmigaE | PROC mean(l:PTR TO LONG)
DEF m, i, ll
ll := ListLen(l)
IF ll = 0 THEN RETURN 0.0
m := 0.0
FOR i := 0 TO ll-1 DO m := !m + l[i]
m := !m / (ll!)
ENDPROC m
PROC main()
DEF s[20] : STRING
WriteF('mean \s\n',
RealF(s,mean([1.0, 2.0, 3.0, 4.0, 5.0]), 2))
ENDPROC |
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
| #BaCon | BaCon | DECLARE base$, update$, merge$ ASSOC STRING
base$("name") = "Rocket Skates"
base$("price") = "12.75"
base$("color") = "yellow"
PRINT "Base array"
FOR x$ IN OBTAIN$(base$)
PRINT x$, " : ", base$(x$)
NEXT
update$("price") = "15.25"
update$("color") = "red"
update$("year") = "1974"
PRINT NL$, "Update array"
FOR x$ IN OBTAIN$(update$)
PRINT x$, " : ", update$(x$)
NEXT
merge$() = base$()
merge$() = update$()
PRINT NL$, "Merged array"
FOR x$ IN OBTAIN$(merge$)
PRINT x$, " : ", merge$(x$)
NEXT |
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
| #C.2B.2B | C++ | #include <iostream>
#include <string>
#include <map>
template<typename map_type>
map_type merge(const map_type& original, const map_type& update) {
map_type result(update);
result.insert(original.begin(), original.end());
return result;
}
int main() {
typedef std::map<std::string, std::string> map;
map original{
{"name", "Rocket Skates"},
{"price", "12.75"},
{"color", "yellow"}
};
map update{
{"price", "15.25"},
{"color", "red"},
{"year", "1974"}
};
map merged(merge(original, update));
for (auto&& i : merged)
std::cout << "key: " << i.first << ", value: " << i.second << '\n';
return 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%)
| #Delphi | Delphi |
program Average_loop_length;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Math;
const
MAX_N = 20;
TIMES = 1000000;
function Factorial(const n: Double): Double;
begin
Result := 1;
if n > 1 then
Result := n * Factorial(n - 1);
end;
function Expected(const n: Integer): Double;
var
i: Integer;
begin
Result := 0;
for i := 1 to n do
Result := Result + (factorial(n) / Power(n, i) / factorial(n - i));
end;
function Test(const n, times: Integer): integer;
var
i, x, bits: Integer;
begin
Result := 0;
for i := 0 to times - 1 do
begin
x := 1;
bits := 0;
while ((bits and x) = 0) do
begin
inc(Result);
bits := bits or x;
x := 1 shl random(n);
end;
end;
end;
var
n, cnt: Integer;
avg, theory, diff: Double;
begin
Randomize;
Writeln(#10' tavg'^I'exp.'^I'diff'#10'-------------------------------');
for n := 1 to MAX_N do
begin
cnt := test(n, times);
avg := cnt / times;
theory := expected(n);
diff := (avg / theory - 1) * 100;
writeln(format('%2d %8.4f %8.4f %6.3f%%', [n, avg, theory, diff]));
end;
readln;
end.
|
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period.
It can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA().
The word stateful in the task description refers to the need for SMA() to remember certain information between calls to it:
The period, P
An ordered container of at least the last P numbers from each of its individual calls.
Stateful also means that successive calls to I(), the initializer, should return separate routines that do not share saved state so they could be used on two independent streams of data.
Pseudo-code for an implementation of SMA is:
function SMA(number: N):
stateful integer: P
stateful list: stream
number: average
stream.append_last(N)
if stream.length() > P:
# Only average the last P elements of the stream
stream.delete_first()
if stream.length() == 0:
average = 0
else:
average = sum( stream.values() ) / stream.length()
return average
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #PL.2FI | PL/I | SMA: procedure (N) returns (float byaddr);
declare N fixed;
declare A(*) fixed controlled,
(p, q) fixed binary static initial (0);
if allocation(A) = 0 then signal error;
p = p + 1; if q < 20 then q = q + 1;
if p > hbound(A, 1) then p = 1;
A(p) = N;
return (sum(float(A))/q);
I: ENTRY (Period);
declare Period fixed binary;
if allocation(A) > 0 then FREE A;
allocate A(Period);
A = 0;
p = 0;
end 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.
| #C.23 | C# | using System;
namespace AttractiveNumbers {
class Program {
const int MAX = 120;
static bool IsPrime(int n) {
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
if (n % 3 == 0) return n == 3;
int d = 5;
while (d * d <= n) {
if (n % d == 0) return false;
d += 2;
if (n % d == 0) return false;
d += 4;
}
return true;
}
static int PrimeFactorCount(int n) {
if (n == 1) return 0;
if (IsPrime(n)) return 1;
int count = 0;
int f = 2;
while (true) {
if (n % f == 0) {
count++;
n /= f;
if (n == 1) return count;
if (IsPrime(n)) f = n;
} else if (f >= 3) {
f += 2;
} else {
f = 3;
}
}
}
static void Main(string[] args) {
Console.WriteLine("The attractive numbers up to and including {0} are:", MAX);
int i = 1;
int count = 0;
while (i <= MAX) {
int n = PrimeFactorCount(i);
if (IsPrime(n)) {
Console.Write("{0,4}", i);
if (++count % 20 == 0) Console.WriteLine();
}
++i;
}
Console.WriteLine();
}
}
} |
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
| #Go | Go | package main
import (
"errors"
"fmt"
"log"
"math"
"time"
)
var inputs = []string{"23:00:17", "23:40:20", "00:12:45", "00:17:19"}
func main() {
tList := make([]time.Time, len(inputs))
const clockFmt = "15:04:05"
var err error
for i, s := range inputs {
tList[i], err = time.Parse(clockFmt, s)
if err != nil {
log.Fatal(err)
}
}
mean, err := meanTime(tList)
if err != nil {
log.Fatal(err)
}
fmt.Println(mean.Format(clockFmt))
}
func meanTime(times []time.Time) (mean time.Time, err error) {
if len(times) == 0 {
err = errors.New("meanTime: no times specified")
return
}
var ssum, csum float64
for _, t := range times {
h, m, s := t.Clock()
n := t.Nanosecond()
fSec := (float64((h*60+m)*60+s) + float64(n)*1e-9)
sin, cos := math.Sincos(fSec * math.Pi / (12 * 60 * 60))
ssum += sin
csum += cos
}
if ssum == 0 && csum == 0 {
err = errors.New("meanTime: mean undefined")
return
}
_, dayFrac := math.Modf(1 + math.Atan2(ssum, csum)/(2*math.Pi))
return mean.Add(time.Duration(dayFrac * 24 * float64(time.Hour))), nil
} |
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.
| #Go | Go | package avl
// AVL tree adapted from Julienne Walker's presentation at
// http://eternallyconfuzzled.com/tuts/datastructures/jsw_tut_avl.aspx.
// This port uses similar indentifier names.
// The Key interface must be supported by data stored in the AVL tree.
type Key interface {
Less(Key) bool
Eq(Key) bool
}
// Node is a node in an AVL tree.
type Node struct {
Data Key // anything comparable with Less and Eq.
Balance int // balance factor
Link [2]*Node // children, indexed by "direction", 0 or 1.
}
// A little readability function for returning the opposite of a direction,
// where a direction is 0 or 1. Go inlines this.
// Where JW writes !dir, this code has opp(dir).
func opp(dir int) int {
return 1 - dir
}
// single rotation
func single(root *Node, dir int) *Node {
save := root.Link[opp(dir)]
root.Link[opp(dir)] = save.Link[dir]
save.Link[dir] = root
return save
}
// double rotation
func double(root *Node, dir int) *Node {
save := root.Link[opp(dir)].Link[dir]
root.Link[opp(dir)].Link[dir] = save.Link[opp(dir)]
save.Link[opp(dir)] = root.Link[opp(dir)]
root.Link[opp(dir)] = save
save = root.Link[opp(dir)]
root.Link[opp(dir)] = save.Link[dir]
save.Link[dir] = root
return save
}
// adjust valance factors after double rotation
func adjustBalance(root *Node, dir, bal int) {
n := root.Link[dir]
nn := n.Link[opp(dir)]
switch nn.Balance {
case 0:
root.Balance = 0
n.Balance = 0
case bal:
root.Balance = -bal
n.Balance = 0
default:
root.Balance = 0
n.Balance = bal
}
nn.Balance = 0
}
func insertBalance(root *Node, dir int) *Node {
n := root.Link[dir]
bal := 2*dir - 1
if n.Balance == bal {
root.Balance = 0
n.Balance = 0
return single(root, opp(dir))
}
adjustBalance(root, dir, bal)
return double(root, opp(dir))
}
func insertR(root *Node, data Key) (*Node, bool) {
if root == nil {
return &Node{Data: data}, false
}
dir := 0
if root.Data.Less(data) {
dir = 1
}
var done bool
root.Link[dir], done = insertR(root.Link[dir], data)
if done {
return root, true
}
root.Balance += 2*dir - 1
switch root.Balance {
case 0:
return root, true
case 1, -1:
return root, false
}
return insertBalance(root, dir), true
}
// Insert a node into the AVL tree.
// Data is inserted even if other data with the same key already exists.
func Insert(tree **Node, data Key) {
*tree, _ = insertR(*tree, data)
}
func removeBalance(root *Node, dir int) (*Node, bool) {
n := root.Link[opp(dir)]
bal := 2*dir - 1
switch n.Balance {
case -bal:
root.Balance = 0
n.Balance = 0
return single(root, dir), false
case bal:
adjustBalance(root, opp(dir), -bal)
return double(root, dir), false
}
root.Balance = -bal
n.Balance = bal
return single(root, dir), true
}
func removeR(root *Node, data Key) (*Node, bool) {
if root == nil {
return nil, false
}
if root.Data.Eq(data) {
switch {
case root.Link[0] == nil:
return root.Link[1], false
case root.Link[1] == nil:
return root.Link[0], false
}
heir := root.Link[0]
for heir.Link[1] != nil {
heir = heir.Link[1]
}
root.Data = heir.Data
data = heir.Data
}
dir := 0
if root.Data.Less(data) {
dir = 1
}
var done bool
root.Link[dir], done = removeR(root.Link[dir], data)
if done {
return root, true
}
root.Balance += 1 - 2*dir
switch root.Balance {
case 1, -1:
return root, true
case 0:
return root, false
}
return removeBalance(root, dir)
}
// Remove a single item from an AVL tree.
// If key does not exist, function has no effect.
func Remove(tree **Node, data Key) {
*tree, _ = removeR(*tree, data)
} |
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
| #F.23 | F# | open System
open System.Numerics
let deg2rad d = d * Math.PI / 180.
let rad2deg r = r * 180. / Math.PI
[<EntryPoint>]
let main argv =
let makeComplex = fun r -> Complex.FromPolarCoordinates(1., r)
argv
|> Seq.map (Double.Parse >> deg2rad >> makeComplex)
|> Seq.fold (fun x y -> Complex.Add(x,y)) Complex.Zero
|> fun c -> c.Phase |> rad2deg
|> printfn "Mean angle for [%s]: %g°" (String.Join("; ",argv))
0 |
http://rosettacode.org/wiki/Averages/Mean_angle | Averages/Mean angle | When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle.
If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the second was of 10 degrees then the average of the numbers is 180 degrees, whereas if you can note that 350 degrees is equivalent to -10 degrees and so you have two readings at 10 degrees either side of zero degrees leading to a more fitting mean angle of zero degrees.
To calculate the mean angle of several angles:
Assume all angles are on the unit circle and convert them to complex numbers expressed in real and imaginary form.
Compute the mean of the complex numbers.
Convert the complex mean to polar coordinates whereupon the phase of the complex mean is the required angular mean.
(Note that, since the mean is the sum divided by the number of numbers, and division by a positive real number does not affect the angle, you can also simply compute the sum for step 2.)
You can alternatively use this formula:
Given the angles
α
1
,
…
,
α
n
{\displaystyle \alpha _{1},\dots ,\alpha _{n}}
the mean is computed by
α
¯
=
atan2
(
1
n
⋅
∑
j
=
1
n
sin
α
j
,
1
n
⋅
∑
j
=
1
n
cos
α
j
)
{\displaystyle {\bar {\alpha }}=\operatorname {atan2} \left({\frac {1}{n}}\cdot \sum _{j=1}^{n}\sin \alpha _{j},{\frac {1}{n}}\cdot \sum _{j=1}^{n}\cos \alpha _{j}\right)}
Task[edit]
write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle.
(You should use a built-in function if you have one that does this for degrees or radians).
Use the function to compute the means of these lists of angles (in degrees):
[350, 10]
[90, 180, 270, 360]
[10, 20, 30]
Show your output here.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Factor | Factor | USING: formatting kernel math math.functions math.libm math.trig
sequences ;
: mean-angle ( seq -- x )
[ deg>rad ] map [ [ sin ] map-sum ] [ [ cos ] map-sum ]
[ length ] tri recip [ * ] curry bi@ fatan2 rad>deg ;
: show ( seq -- )
dup mean-angle "The mean angle of %u is: %f°\n" printf ;
{ { 350 10 } { 90 180 270 360 } { 10 20 30 } } [ show ] each |
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
| #C | C | #include <stdio.h>
#include <stdlib.h>
typedef struct floatList {
float *list;
int size;
} *FloatList;
int floatcmp( const void *a, const void *b) {
if (*(const float *)a < *(const float *)b) return -1;
else return *(const float *)a > *(const float *)b;
}
float median( FloatList fl )
{
qsort( fl->list, fl->size, sizeof(float), floatcmp);
return 0.5 * ( fl->list[fl->size/2] + fl->list[(fl->size-1)/2]);
}
int main()
{
static float floats1[] = { 5.1, 2.6, 6.2, 8.8, 4.6, 4.1 };
static struct floatList flist1 = { floats1, sizeof(floats1)/sizeof(float) };
static float floats2[] = { 5.1, 2.6, 8.8, 4.6, 4.1 };
static struct floatList flist2 = { floats2, sizeof(floats2)/sizeof(float) };
printf("flist1 median is %7.2f\n", median(&flist1)); /* 4.85 */
printf("flist2 median is %7.2f\n", median(&flist2)); /* 4.60 */
return 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
| #Fortran | Fortran | program Mean
real :: a(10) = (/ (i, i=1,10) /)
real :: amean, gmean, hmean
amean = sum(a) / size(a)
gmean = product(a)**(1.0/size(a))
hmean = size(a) / sum(1.0/a)
if ((amean < gmean) .or. (gmean < hmean)) then
print*, "Error!"
else
print*, amean, gmean, hmean
end if
end program Mean |
http://rosettacode.org/wiki/Balanced_ternary | Balanced ternary | Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1.
Examples
Decimal 11 = 32 + 31 − 30, thus it can be written as "++−"
Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0"
Task
Implement balanced ternary representation of integers with the following:
Support arbitrarily large integers, both positive and negative;
Provide ways to convert to and from text strings, using digits '+', '-' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5).
Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type is balanced ternary). If your native integers can't support arbitrary length, overflows during conversion must be indicated.
Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do not convert to native integers first.
Make your implementation efficient, with a reasonable definition of "efficient" (and with a reasonable definition of "reasonable").
Test case With balanced ternaries a from string "+-0++0+", b from native integer -436, c "+-++-":
write out a, b and c in decimal notation;
calculate a × (b − c), write out the result in both ternary and decimal notations.
Note: The pages generalised floating point addition and generalised floating point multiplication have code implementing arbitrary precision floating point balanced ternary.
| #J | J | trigits=: 1+3 <.@^. 2 * 1&>.@|
trinOfN=: |.@((_1 + ] #: #.&1@] + [) #&3@trigits) :. nOfTrin
nOfTrin=: p.&3 :. trinOfN
trinOfStr=: 0 1 _1 {~ '0+-'&i.@|. :. strOfTrin
strOfTrin=: {&'0+-'@|. :. trinOfStr
carry=: +//.@:(trinOfN"0)^:_
trimLead0=: (}.~ i.&1@:~:&0)&.|.
add=: carry@(+/@,:)
neg=: -
mul=: trimLead0@carry@(+//.@(*/)) |
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.
| #Pascal | Pascal | program BabbageProblem;
(* Anything bracketed off like this is an explanatory comment. *)
var n : longint; (* The VARiable n can hold a 'long', ie large, INTeger. *)
begin
n := 2; (* Start with n equal to 2. *)
repeat
n := n + 2 (* Increase n by 2. *)
until (n * n) mod 1000000 = 269696;
(* 'n * n' means 'n times n'; 'mod' means 'modulo'. *)
write(n)
end. |
http://rosettacode.org/wiki/Approximate_equality | Approximate equality | Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the
difference in floating point calculations between different language implementations becomes significant.
For example, a difference between 32 bit and 64 bit floating point calculations may appear by
about the 8th significant digit in base 10 arithmetic.
Task
Create a function which returns true if two floating point numbers are approximately equal.
The function should allow for differences in the magnitude of numbers, so that, for example,
100000000000000.01 may be approximately equal to 100000000000000.011,
even though 100.01 is not approximately equal to 100.011.
If the language has such a feature in its standard library, this may be used instead of a custom function.
Show the function results with comparisons on the following pairs of values:
100000000000000.01, 100000000000000.011 (note: should return true)
100.01, 100.011 (note: should return false)
10000000000000.001 / 10000.0, 1000000000.0000001000
0.001, 0.0010000001
0.000000000000000000000101, 0.0
sqrt(2) * sqrt(2), 2.0
-sqrt(2) * sqrt(2), -2.0
3.14159265358979323846, 3.14159265358979324
Answers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.
| #Ada | Ada |
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Generic_Elementary_Functions;
procedure Main is
type Real is digits 18;
package Real_Funcs is new Ada.Numerics.Generic_Elementary_Functions(Real);
use Real_Funcs;
package Real_IO is new Ada.Text_IO.Float_IO(Real);
use Real_IO;
function Approx_Equal (Left : Real; Right : Real) return Boolean is
-- Calculate an epsilon value based upon the magnitude of the
-- maximum value of the two parameters
eps : Real := Real'Max(Left, Right) * 1.0e-9;
begin
if left > Right then
return Left - Right < eps;
else
return Right - Left < eps;
end if;
end Approx_Equal;
Type Index is (Left, Right);
type Pairs_List is array (Index) of Real;
type Pairs_Table is array(1..8) of Pairs_List;
Table : Pairs_Table;
begin
Table := ((100000000000000.01, 100000000000000.011),
(100.01, 100.011),
(10000000000000.001 / 10000.0, 1000000000.0000001000),
(0.001, 0.0010000001),
(0.000000000000000000000101, 0.0),
(sqrt(2.0) * sqrt(2.0), 2.0),
(-sqrt(2.0) * sqrt(2.0), -2.0),
(3.14159265358979323846, 3.14159265358979324));
for Pair of Table loop
Put(Item => Pair(Left), Exp => 0, Aft => 16, Fore => 6);
Put(" ");
Put(Item => Pair(Right), Exp => 0, Aft => 16, Fore => 6);
Put_Line(" " & Boolean'Image(Approx_Equal(Pair(Left), Pair(Right))));
end loop;
end Main;
|
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
| #BQN | BQN | ⟨l, r | l·r = e⟩ |
http://rosettacode.org/wiki/Atomic_updates | Atomic updates |
Task
Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to:
get the current value of any bucket
remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the transferred amount to ensure the values remain non-negative
In order to exercise this data type, create one set of buckets, and start three concurrent tasks:
As often as possible, pick two buckets and make their values closer to equal.
As often as possible, pick two buckets and arbitrarily redistribute their values.
At whatever rate is convenient, display (by any means) the total value and, optionally, the individual values of each bucket.
The display task need not be explicit; use of e.g. a debugger or trace tool is acceptable provided it is simple to set up to provide the display.
This task is intended as an exercise in atomic operations. The sum of the bucket values must be preserved even if the two tasks attempt to perform transfers simultaneously, and a straightforward solution is to ensure that at any time, only one transfer is actually occurring — that the transfer operation is atomic.
| #AutoHotkey | AutoHotkey | Bucket := [], Buckets := 10, Originaltotal = 0
loop, %Buckets% {
Random, rnd, 0,50
Bucket[A_Index] := rnd, Originaltotal += rnd
}
loop 100
{
total := 0
Randomize(B1, B2, Buckets)
temp := (Bucket[B1] + Bucket[B2]) /2
Bucket[B1] := floor(temp), Bucket[B2] := Ceil(temp) ; values closer to equal
Randomize(B1, B2, Buckets)
temp := Bucket[B1] + Bucket[B2]
Random, value, 0, %temp%
Bucket[B1] := value, Bucket[B2] := temp-value ; redistribute values arbitrarily
VisualTip := "Original Total = " Originaltotal "`n"
loop, %Buckets%
VisualTip .= SubStr("0" Bucket[A_Index], -1) " : " x(Bucket[A_Index]) "`n" , total += Bucket[A_Index]
ToolTip % VisualTip "Current Total = " total
if (total <> Originaltotal)
MsgBox "Error"
Sleep, 100
}
return
Randomize(ByRef B1, ByRef B2, Buckets){
Random, B1, 1, %Buckets%
Loop
Random, B2, 1, %Buckets%
until (B1<>B2)
}
x(n){
loop, % n
Res.= ">"
return Res
} |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #ALGOL_68 | ALGOL 68 | INT a, b; read((a, b)) PR ASSERT a >= 0 & b > 0 PR;
|
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #ALGOL_W | ALGOL W | begin
integer a;
a := 43;
assert a = 42;
write( "this won't appear" )
end. |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Apex | Apex |
String myStr = 'test;
System.assert(myStr == 'something else', 'Assertion Failed Message');
|
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
| #Haskell | Haskell | import Prelude (foldr, maximum, (==), (+))
import Data.Map (insertWith', empty, filter, elems, keys)
mode :: (Ord a) => [a] -> [a]
mode xs = keys (filter (== maximum (elems counts)) counts)
where counts = foldr (\x -> insertWith' (+) x 1) empty xs |
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
| #AntLang | AntLang | avg[list] |
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
| #APL | APL | X←3 1 4 1 5 9
(+/X)÷⍴X
3.833333333 |
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
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main() {
var baseData = new Dictionary<string, object> {
["name"] = "Rocket Skates",
["price"] = 12.75,
["color"] = "yellow"
};
var updateData = new Dictionary<string, object> {
["price"] = 15.25,
["color"] = "red",
["year"] = 1974
};
var mergedData = new Dictionary<string, object>();
foreach (var entry in baseData.Concat(updateData)) {
mergedData[entry.Key] = entry.Value;
}
foreach (var entry in mergedData) {
Console.WriteLine(entry);
}
}
} |
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%)
| #EchoLisp | EchoLisp |
(lib 'math) ;; Σ aka (sigma f(n) nfrom nto)
(define (f-count N (times 100000))
(define count 0)
(for ((i times))
;; new random f mapping from 0..N-1 to 0..N-1
;; (f n) is NOT (random N)
;; because each call (f n) must return the same value
(define f (build-vector N (lambda(i) (random N))))
(define hits (make-vector N))
(define n 0)
(while (zero? [hits n])
(++ count)
(vector+= hits n 1)
(set! n [f n])))
(// count times))
(define (f-anal N)
(Σ (lambda(i) (// (! N) (! (- N i)) (^ N i))) 1 N))
(decimals 5)
(define (f-print (maxN 21))
(for ((N (in-range 1 maxN)))
(define fc (f-count N))
(define fa (f-anal N))
(printf "%3d %10d %10d %10.2d %%" N fc fa (// (abs (- fa fc)) fc 0.01))))
|
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
| #Pony | Pony |
class MovingAverage
let period: USize
let _arr: Array[I32] // circular buffer
var _curr: USize // index of pointer position
var _total: I32 // cache the total so far
new create(period': USize) =>
period = period'
_arr = Array[I32](period) // preallocate space
_curr = 0
_total = 0
fun ref apply(n: I32): F32 =>
_total = _total + n
if _arr.size() < period then
_arr.push(n)
else
try
let prev = _arr.update(_curr, n)?
_total = _total - prev
_curr = (_curr + 1) % period
end
end
_total.f32() / _arr.size().f32()
// ---- TESTING -----
actor Main
new create(env: Env) =>
let foo = MovingAverage(3)
let bar = MovingAverage(5)
let data: Array[I32] = [1; 2; 3; 4; 5; 5; 4; 3; 2; 1]
for v in data.values() do
env.out.print("Foo: " + foo(v).string())
end
for v in data.values() do
env.out.print("Bar: " + bar(v).string())
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.
| #C.2B.2B | C++ | #include <iostream>
#include <iomanip>
#define MAX 120
using namespace std;
bool is_prime(int n) {
if (n < 2) return false;
if (!(n % 2)) return n == 2;
if (!(n % 3)) return n == 3;
int d = 5;
while (d *d <= n) {
if (!(n % d)) return false;
d += 2;
if (!(n % d)) return false;
d += 4;
}
return true;
}
int count_prime_factors(int n) {
if (n == 1) return 0;
if (is_prime(n)) return 1;
int count = 0, f = 2;
while (true) {
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;
}
}
int main() {
cout << "The attractive numbers up to and including " << MAX << " are:" << endl;
for (int i = 1, count = 0; i <= MAX; ++i) {
int n = count_prime_factors(i);
if (is_prime(n)) {
cout << setw(4) << i;
if (!(++count % 20)) cout << endl;
}
}
cout << endl;
return 0;
} |
http://rosettacode.org/wiki/Averages/Mean_time_of_day | Averages/Mean time of day | Task[edit]
A particular activity of bats occurs at these times of the day:
23:00:17, 23:40:20, 00:12:45, 00:17:19
Using the idea that there are twenty-four hours in a day,
which is analogous to there being 360 degrees in a circle,
map times of day to and from angles;
and using the ideas of Averages/Mean angle
compute and show the average time of the nocturnal activity
to an accuracy of one second of time.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Groovy | Groovy | import static java.lang.Math.*
final format = 'HH:mm:ss', clock = PI / 12, millisPerHr = 3600*1000
final tzOffset = new Date(0).timezoneOffset / 60
def parseTime = { time -> (Date.parse(format, time).time / millisPerHr) - tzOffset }
def formatTime = { time -> new Date((time + tzOffset) * millisPerHr as int).format(format) }
def mean = { list, closure -> list.sum(closure)/list.size() }
def meanTime = { ... timeStrings ->
def times = timeStrings.collect(parseTime)
formatTime(atan2( mean(times) { sin(it * clock) }, mean(times) { cos(it * clock) }) / clock)
} |
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.
| #Haskell | Haskell | data Tree a
= Leaf
| Node
Int
(Tree a)
a
(Tree a)
deriving (Show, Eq)
foldTree :: Ord a => [a] -> Tree a
foldTree = foldr insert Leaf
height :: Tree a -> Int
height Leaf = -1
height (Node h _ _ _) = h
depth :: Tree a -> Tree a -> Int
depth a b = succ (max (height a) (height b))
insert :: Ord a => a -> Tree a -> Tree a
insert v Leaf = Node 1 Leaf v Leaf
insert v t@(Node n left v_ right)
| v_ < v = rotate $ Node n left v_ (insert v right)
| v_ > v = rotate $ Node n (insert v left) v_ right
| otherwise = t
max_ :: Ord a => Tree a -> Maybe a
max_ Leaf = Nothing
max_ (Node _ _ v right) =
case right of
Leaf -> Just v
_ -> max_ right
delete :: Ord a => a -> Tree a -> Tree a
delete _ Leaf = Leaf
delete x (Node h left v right)
| x == v =
maybe left (rotate . (Node h left <*> (`delete` right))) (max_ right)
| x > v = rotate $ Node h left v (delete x right)
| x < v = rotate $ Node h (delete x left) v right
rotate :: Tree a -> Tree a
rotate Leaf = Leaf
rotate (Node h (Node lh ll lv lr) v r)
-- Left Left.
| lh - height r > 1 && height ll - height lr > 0 =
Node lh ll lv (Node (depth r lr) lr v r)
rotate (Node h l v (Node rh rl rv rr))
-- Right Right.
| rh - height l > 1 && height rr - height rl > 0 =
Node rh (Node (depth l rl) l v rl) rv rr
rotate (Node h (Node lh ll lv (Node rh rl rv rr)) v r)
-- Left Right.
| lh - height r > 1 =
Node h (Node (rh + 1) (Node (lh - 1) ll lv rl) rv rr) v r
rotate (Node h l v (Node rh (Node lh ll lv lr) rv rr))
-- Right Left.
| rh - height l > 1 =
Node h l v (Node (lh + 1) ll lv (Node (rh - 1) lr rv rr))
rotate (Node h l v r) =
-- Re-weighting.
let (l_, r_) = (rotate l, rotate r)
in Node (depth l_ r_) l_ v r_
draw :: Show a => Tree a -> String
draw t = '\n' : draw_ t 0 <> "\n"
where
draw_ Leaf _ = []
draw_ (Node h l v r) d = draw_ r (d + 1) <> node <> draw_ l (d + 1)
where
node = padding d <> show (v, h) <> "\n"
padding n = replicate (n * 4) ' '
main :: IO ()
main = putStr $ draw $ foldTree [1 .. 31] |
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
| #Fortran | Fortran |
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Mon Jun 3 18:07:59
!
!a=./f && make $a && OMP_NUM_THREADS=2 $a
!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f
! -7.80250048E-06 350 10
! 90.0000000 90 180 270 360
! 19.9999962 10 20 30
!
!Compilation finished at Mon Jun 3 18:07:59
program average_angles
!real(kind=8), parameter :: TAU = 6.283185307179586232 ! http://tauday.com/
!integer, dimension(13), parameter :: test_data = (/2,350,10, 4,90,180,270,360, 3,10,20,30, 0/)
!integer :: i, j, n
!complex(kind=16) :: some
!real(kind=8) :: angle
real, parameter :: TAU = 6.283185307179586232 ! http://tauday.com/
integer, dimension(13), parameter :: test_data = (/2,350,10, 4,90,180,270,360, 3,10,20,30, 0/)
integer :: i, j, n
complex :: some
real :: angle
i = 1
n = int(test_data(i))
do while (0 .lt. n)
some = 0
do j = 1, n
angle = (TAU/360)*test_data(i+j)
some = some + cmplx(cos(angle), sin(angle))
end do
some = some / n
write(6,*)(360/TAU)*atan2(aimag(some), real(some)),test_data(i+1:i+n)
i = i + n + 1
n = int(test_data(i))
end do
end program average_angles
|
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches to this. One is to sort the elements, and then pick the element(s) in the middle.
Sorting would take at least O(n logn). Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s). This would also take O(n logn). The best solution is to use the selection algorithm to find the median in O(n) time.
See also
Quickselect_algorithm
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #C.23 | C# | using System;
using System.Linq;
namespace Test
{
class Program
{
static void Main()
{
double[] myArr = new double[] { 1, 5, 3, 6, 4, 2 };
myArr = myArr.OrderBy(i => i).ToArray();
// or Array.Sort(myArr) for in-place sort
int mid = myArr.Length / 2;
double median;
if (myArr.Length % 2 == 0)
{
//we know its even
median = (myArr[mid] + myArr[mid - 1]) / 2.0;
}
else
{
//we know its odd
median = myArr[mid];
}
Console.WriteLine(median);
Console.ReadLine();
}
}
}
|
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
| #FreeBASIC | FreeBASIC |
' FB 1.05.0 Win64
Function ArithmeticMean(array() As Double) As Double
Dim length As Integer = Ubound(array) - Lbound(array) + 1
Dim As Double sum = 0.0
For i As Integer = LBound(array) To UBound(array)
sum += array(i)
Next
Return sum/length
End Function
Function GeometricMean(array() As Double) As Double
Dim length As Integer = Ubound(array) - Lbound(array) + 1
Dim As Double product = 1.0
For i As Integer = LBound(array) To UBound(array)
product *= array(i)
Next
Return product ^ (1.0 / length)
End Function
Function HarmonicMean(array() As Double) As Double
Dim length As Integer = Ubound(array) - Lbound(array) + 1
Dim As Double sum = 0.0
For i As Integer = LBound(array) To UBound(array)
sum += 1.0 / array(i)
Next
Return length / sum
End Function
Dim vector(1 To 10) As Double
For i As Integer = 1 To 10
vector(i) = i
Next
Print "Arithmetic mean is :"; ArithmeticMean(vector())
Print "Geometric mean is :"; GeometricMean(vector())
Print "Harmonic mean is :"; HarmonicMean(vector())
Print
Print "Press any key to quit the program"
Sleep
|
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.
| #Java | Java |
/*
* 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.
*/
public class BalancedTernary
{
public static void main(String[] args)
{
BTernary a=new BTernary("+-0++0+");
BTernary b=new BTernary(-436);
BTernary c=new BTernary("+-++-");
System.out.println("a="+a.intValue());
System.out.println("b="+b.intValue());
System.out.println("c="+c.intValue());
System.out.println();
//result=a*(b-c)
BTernary result=a.mul(b.sub(c));
System.out.println("result= "+result+" "+result.intValue());
}
public static class BTernary
{
String value;
public BTernary(String s)
{
int i=0;
while(s.charAt(i)=='0')
i++;
this.value=s.substring(i);
}
public BTernary(int v)
{
this.value="";
this.value=convertToBT(v);
}
private String convertToBT(int v)
{
if(v<0)
return flip(convertToBT(-v));
if(v==0)
return "";
int rem=mod3(v);
if(rem==0)
return convertToBT(v/3)+"0";
if(rem==1)
return convertToBT(v/3)+"+";
if(rem==2)
return convertToBT((v+1)/3)+"-";
return "You can't see me";
}
private String flip(String s)
{
String flip="";
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)=='+')
flip+='-';
else if(s.charAt(i)=='-')
flip+='+';
else
flip+='0';
}
return flip;
}
private int mod3(int v)
{
if(v>0)
return v%3;
v=v%3;
return (v+3)%3;
}
public int intValue()
{
int sum=0;
String s=this.value;
for(int i=0;i<s.length();i++)
{
char c=s.charAt(s.length()-i-1);
int dig=0;
if(c=='+')
dig=1;
else if(c=='-')
dig=-1;
sum+=dig*Math.pow(3, i);
}
return sum;
}
public BTernary add(BTernary that)
{
String a=this.value;
String b=that.value;
String longer=a.length()>b.length()?a:b;
String shorter=a.length()>b.length()?b:a;
while(shorter.length()<longer.length())
shorter=0+shorter;
a=longer;
b=shorter;
char carry='0';
String sum="";
for(int i=0;i<a.length();i++)
{
int place=a.length()-i-1;
String digisum=addDigits(a.charAt(place),b.charAt(place),carry);
if(digisum.length()!=1)
carry=digisum.charAt(0);
else
carry='0';
sum=digisum.charAt(digisum.length()-1)+sum;
}
sum=carry+sum;
return new BTernary(sum);
}
private String addDigits(char a,char b,char carry)
{
String sum1=addDigits(a,b);
String sum2=addDigits(sum1.charAt(sum1.length()-1),carry);
//System.out.println(carry+" "+sum1+" "+sum2);
if(sum1.length()==1)
return sum2;
if(sum2.length()==1)
return sum1.charAt(0)+sum2;
return sum1.charAt(0)+"";
}
private String addDigits(char a,char b)
{
String sum="";
if(a=='0')
sum=b+"";
else if (b=='0')
sum=a+"";
else if(a=='+')
{
if(b=='+')
sum="+-";
else
sum="0";
}
else
{
if(b=='+')
sum="0";
else
sum="-+";
}
return sum;
}
public BTernary neg()
{
return new BTernary(flip(this.value));
}
public BTernary sub(BTernary that)
{
return this.add(that.neg());
}
public BTernary mul(BTernary that)
{
BTernary one=new BTernary(1);
BTernary zero=new BTernary(0);
BTernary mul=new BTernary(0);
int flipflag=0;
if(that.compareTo(zero)==-1)
{
that=that.neg();
flipflag=1;
}
for(BTernary i=new BTernary(1);i.compareTo(that)<1;i=i.add(one))
mul=mul.add(this);
if(flipflag==1)
mul=mul.neg();
return mul;
}
public boolean equals(BTernary that)
{
return this.value.equals(that.value);
}
public int compareTo(BTernary that)
{
if(this.intValue()>that.intValue())
return 1;
else if(this.equals(that))
return 0;
return -1;
}
public String toString()
{
return value;
}
}
}
|
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.
| #Perl | Perl | #!/usr/bin/perl
use strict ;
use warnings ;
my $current = 0 ;
while ( ($current ** 2 ) % 1000000 != 269696 ) {
$current++ ;
}
print "The square of $current is " . ($current * $current) . " !\n" ; |
http://rosettacode.org/wiki/Approximate_equality | Approximate equality | Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the
difference in floating point calculations between different language implementations becomes significant.
For example, a difference between 32 bit and 64 bit floating point calculations may appear by
about the 8th significant digit in base 10 arithmetic.
Task
Create a function which returns true if two floating point numbers are approximately equal.
The function should allow for differences in the magnitude of numbers, so that, for example,
100000000000000.01 may be approximately equal to 100000000000000.011,
even though 100.01 is not approximately equal to 100.011.
If the language has such a feature in its standard library, this may be used instead of a custom function.
Show the function results with comparisons on the following pairs of values:
100000000000000.01, 100000000000000.011 (note: should return true)
100.01, 100.011 (note: should return false)
10000000000000.001 / 10000.0, 1000000000.0000001000
0.001, 0.0010000001
0.000000000000000000000101, 0.0
sqrt(2) * sqrt(2), 2.0
-sqrt(2) * sqrt(2), -2.0
3.14159265358979323846, 3.14159265358979324
Answers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.
| #ALGOL_68 | ALGOL 68 | BEGIN # test REAL values for approximate equality #
# returns TRUE if value is approximately equal to other, FALSE otherwide #
PROC approx equals = ( REAL value, REAL other, REAL epsilon )BOOL: ABS ( value - other ) < epsilon;
# shows the result of testing a for approximate equality with b #
PROC test = ( REAL a, b )VOID:
BEGIN
REAL epsilon = 1e-18;
print( ( a, ", ", b, " => ", IF approx equals( a, b, epsilon ) THEN "true" ELSE "false" FI, newline ) )
END # test # ;
# task test cases #
test( 100000000000000.01, 100000000000000.011 );
test( 100.01, 100.011 );
test( 10000000000000.001 / 10000.0, 1000000000.0000001000);
test( 0.001, 0.0010000001 );
test( 0.000000000000000000000101, 0.0 );
test( sqrt( 2 ) * sqrt( 2 ), 2.0 );
test( - sqrt( 2 ) * sqrt( 2 ), -2.0 );
test( 3.14159265358979323846, 3.14159265358979324 )
END |
http://rosettacode.org/wiki/Approximate_equality | Approximate equality | Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the
difference in floating point calculations between different language implementations becomes significant.
For example, a difference between 32 bit and 64 bit floating point calculations may appear by
about the 8th significant digit in base 10 arithmetic.
Task
Create a function which returns true if two floating point numbers are approximately equal.
The function should allow for differences in the magnitude of numbers, so that, for example,
100000000000000.01 may be approximately equal to 100000000000000.011,
even though 100.01 is not approximately equal to 100.011.
If the language has such a feature in its standard library, this may be used instead of a custom function.
Show the function results with comparisons on the following pairs of values:
100000000000000.01, 100000000000000.011 (note: should return true)
100.01, 100.011 (note: should return false)
10000000000000.001 / 10000.0, 1000000000.0000001000
0.001, 0.0010000001
0.000000000000000000000101, 0.0
sqrt(2) * sqrt(2), 2.0
-sqrt(2) * sqrt(2), -2.0
3.14159265358979323846, 3.14159265358979324
Answers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.
| #AWK | AWK |
# syntax: GAWK -f APPROXIMATE_EQUALITY.AWK
# converted from C#
BEGIN {
epsilon = 1
while (1 + epsilon != 1) {
epsilon /= 2
}
printf("epsilon = %18.16g\n\n",epsilon)
main("100000000000000.01","100000000000000.011")
main("100.01","100.011")
main("10000000000000.001"/"10000.0","1000000000.0000001000")
main("0.001","0.0010000001")
main("0.000000000000000000000101","0.0")
main(sqrt(2.0)*sqrt(2.0),"2.0")
main(-sqrt(2.0)*sqrt(2.0),"-2.0")
main("3.14159265358979323846","3.14159265358979324")
exit(0)
}
function main(a,b, tmp) {
tmp = abs(a - b) < epsilon
printf("%d %27s %s\n",tmp,a,b)
}
function abs(x) { if (x >= 0) { return x } else { return -x } }
|
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
| #Bracmat | Bracmat | ( (bal=|"[" !bal "]" !bal)
& ( generate
= a j m n z N S someNumber
. !arg:<1&
| 11^123+13^666+17^321:?someNumber
& (!arg:?n)+1:?N
& :?S
& whl
' (!n+-1:~<0:?n&"[" "]" !S:?S)
& whl
' ( !someNumber:>0
& mod$(!someNumber.!N):?j
& div$(!someNumber.!N):?someNumber
& !S:?a [!j ?m [!N ?z
& !z !m !a:?S
)
& !S
)
& 0:?L
& whl
' ( generate$!L:?S
& put$(str$(!S ":"))
& out
$ (!S:!bal&Balanced|"Not balanced")
& !L+1:<11:?L
)
); |
http://rosettacode.org/wiki/Atomic_updates | Atomic updates |
Task
Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to:
get the current value of any bucket
remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the transferred amount to ensure the values remain non-negative
In order to exercise this data type, create one set of buckets, and start three concurrent tasks:
As often as possible, pick two buckets and make their values closer to equal.
As often as possible, pick two buckets and arbitrarily redistribute their values.
At whatever rate is convenient, display (by any means) the total value and, optionally, the individual values of each bucket.
The display task need not be explicit; use of e.g. a debugger or trace tool is acceptable provided it is simple to set up to provide the display.
This task is intended as an exercise in atomic operations. The sum of the bucket values must be preserved even if the two tasks attempt to perform transfers simultaneously, and a straightforward solution is to ensure that at any time, only one transfer is actually occurring — that the transfer operation is atomic.
| #BBC_BASIC | BBC BASIC | INSTALL @lib$+"TIMERLIB"
DIM Buckets%(100)
FOR i% = 1 TO 100 : Buckets%(i%) = RND(10) : NEXT
tid0% = FN_ontimer(10, PROCdisplay, 1)
tid1% = FN_ontimer(11, PROCflatten, 1)
tid2% = FN_ontimer(12, PROCroughen, 1)
ON ERROR PROCcleanup : REPORT : PRINT : END
ON CLOSE PROCcleanup : QUIT
REPEAT
WAIT 0
UNTIL FALSE
END
DEF PROCdisplay
PRINT SUM(Buckets%()) " ", MOD(Buckets%())
ENDPROC
DEF PROCflatten
LOCAL d%, i%, j%
REPEAT
i% = RND(100)
j% = RND(100)
UNTIL i%<>j%
d% = Buckets%(i%) - Buckets%(j%)
PROCatomicupdate(Buckets%(i%), Buckets%(j%), d% DIV 4)
ENDPROC
DEF PROCroughen
LOCAL i%, j%
REPEAT
i% = RND(100)
j% = RND(100)
UNTIL i%<>j%
PROCatomicupdate(Buckets%(i%), Buckets%(j%), RND(10))
ENDPROC
DEF PROCatomicupdate(RETURN src%, RETURN dst%, amt%)
IF amt% > src% amt% = src%
IF amt% < -dst% amt% = -dst%
src% -= amt%
dst% += amt%
ENDPROC
DEF PROCcleanup
PROC_killtimer(tid0%)
PROC_killtimer(tid1%)
PROC_killtimer(tid2%)
ENDPROC |
http://rosettacode.org/wiki/Atomic_updates | Atomic updates |
Task
Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to:
get the current value of any bucket
remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the transferred amount to ensure the values remain non-negative
In order to exercise this data type, create one set of buckets, and start three concurrent tasks:
As often as possible, pick two buckets and make their values closer to equal.
As often as possible, pick two buckets and arbitrarily redistribute their values.
At whatever rate is convenient, display (by any means) the total value and, optionally, the individual values of each bucket.
The display task need not be explicit; use of e.g. a debugger or trace tool is acceptable provided it is simple to set up to provide the display.
This task is intended as an exercise in atomic operations. The sum of the bucket values must be preserved even if the two tasks attempt to perform transfers simultaneously, and a straightforward solution is to ensure that at any time, only one transfer is actually occurring — that the transfer operation is atomic.
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#include <time.h>
#include <pthread.h>
#define N_BUCKETS 15
pthread_mutex_t bucket_mutex[N_BUCKETS];
int buckets[N_BUCKETS];
pthread_t equalizer;
pthread_t randomizer;
void transfer_value(int from, int to, int howmuch)
{
bool swapped = false;
if ( (from == to) || ( howmuch < 0 ) ||
(from < 0 ) || (to < 0) || (from >= N_BUCKETS) || (to >= N_BUCKETS) ) return;
if ( from > to ) {
int temp1 = from;
from = to;
to = temp1;
swapped = true;
howmuch = -howmuch;
}
pthread_mutex_lock(&bucket_mutex[from]);
pthread_mutex_lock(&bucket_mutex[to]);
if ( howmuch > buckets[from] && !swapped )
howmuch = buckets[from];
if ( -howmuch > buckets[to] && swapped )
howmuch = -buckets[to];
buckets[from] -= howmuch;
buckets[to] += howmuch;
pthread_mutex_unlock(&bucket_mutex[from]);
pthread_mutex_unlock(&bucket_mutex[to]);
}
void print_buckets()
{
int i;
int sum=0;
for(i=0; i < N_BUCKETS; i++) pthread_mutex_lock(&bucket_mutex[i]);
for(i=0; i < N_BUCKETS; i++) {
printf("%3d ", buckets[i]);
sum += buckets[i];
}
printf("= %d\n", sum);
for(i=0; i < N_BUCKETS; i++) pthread_mutex_unlock(&bucket_mutex[i]);
}
void *equalizer_start(void *t)
{
for(;;) {
int b1 = rand()%N_BUCKETS;
int b2 = rand()%N_BUCKETS;
int diff = buckets[b1] - buckets[b2];
if ( diff < 0 )
transfer_value(b2, b1, -diff/2);
else
transfer_value(b1, b2, diff/2);
}
return NULL;
}
void *randomizer_start(void *t)
{
for(;;) {
int b1 = rand()%N_BUCKETS;
int b2 = rand()%N_BUCKETS;
int diff = rand()%(buckets[b1]+1);
transfer_value(b1, b2, diff);
}
return NULL;
}
int main()
{
int i, total=0;
for(i=0; i < N_BUCKETS; i++) pthread_mutex_init(&bucket_mutex[i], NULL);
for(i=0; i < N_BUCKETS; i++) {
buckets[i] = rand() % 100;
total += buckets[i];
printf("%3d ", buckets[i]);
}
printf("= %d\n", total);
// we should check if these succeeded
pthread_create(&equalizer, NULL, equalizer_start, NULL);
pthread_create(&randomizer, NULL, randomizer_start, NULL);
for(;;) {
sleep(1);
print_buckets();
}
// we do not provide a "good" way to stop this run, so the following
// is never reached indeed...
for(i=0; i < N_BUCKETS; i++) pthread_mutex_destroy(bucket_mutex+i);
return EXIT_SUCCESS;
} |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Arturo | Arturo | a: 42
ensure [a = 42] |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #AutoHotkey | AutoHotkey | a := 42
Assert(a > 10)
Assert(a < 42) ; throws exception
Assert(bool){
If !bool
throw Exception("Expression false", -1)
} |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #AWK | AWK |
BEGIN {
meaning = 6 * 7
assert(meaning == 42, "Integer mathematics failed")
assert(meaning == 42)
meaning = strtonum("42 also known as forty-two")
assert(meaning == 42, "Built-in function failed")
meaning = "42"
assert(meaning == 42, "Dynamic type conversion failed")
meaning = 6 * 9
assert(meaning == 42, "Ford Prefect's experiment failed")
print "That's all folks"
exit
}
# Errormsg is optional, displayed if assertion fails
function assert(cond, errormsg){
if (!cond) {
if (errormsg != "") print errormsg
exit 1
}
}
|
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Icon_and_Unicon | Icon and Unicon | procedure main(args)
every write(!mode(args))
end
procedure mode(A)
hist := table(0)
every hist[!A] +:= 1
hist := sort(hist, 2)
modeCnt := hist[*hist][2]
every modeP := hist[*hist to 1 by -1] do {
if modeCnt = modeP[2] then suspend modeP[1]
else fail
}
end |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #11l | 11l | V d = [‘key1’ = ‘value1’, ‘key2’ = ‘value2’]
L(key, value) d
print(key‘ = ’value)
L(key) d.keys()
print(key)
L(value) d.values()
print(value) |
http://rosettacode.org/wiki/Apply_a_digital_filter_(direct_form_II_transposed) | Apply a digital filter (direct form II transposed) | Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [1]
Task
Filter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667]
The signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]
| #11l | 11l | F apply_filter(a, b, signal)
V result = [0.0] * signal.len
L(i) 0 .< signal.len
V tmp = 0.0
L(j) 0 .< min(i + 1, b.len)
tmp += b[j] * signal[i - j]
L(j) 1 .< min(i + 1, a.len)
tmp -= a[j] * result[i - j]
tmp /= a[0]
result[i] = tmp
R result
V a = [1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17]
V b = [0.16666667, 0.5, 0.5, 0.16666667]
V signal = [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412,
-0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044,
0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195,
0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293,
0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]
V result = apply_filter(a, b, signal)
L(r) result
print(‘#2.8’.format(r), end' ‘’)
print(I (L.index + 1) % 5 != 0 {‘, ’} E "\n", end' ‘’) |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for 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
| #AppleScript | AppleScript | on average(listOfNumbers)
set len to (count listOfNumbers)
if (len is 0) then return missing value
set sum to 0
repeat with thisNumber in listOfNumbers
set sum to sum + thisNumber
end repeat
return sum / len
end average
average({2500, 2700, 2400, 2300, 2550, 2650, 2750, 2450, 2600, 2400}) |
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
| #Applesoft_BASIC | Applesoft BASIC | REM COLLECTION IN DATA STATEMENTS, EMPTY DATA IS THE END OF THE COLLECTION
0 READ V$
1 IF LEN(V$) = 0 THEN END
2 N = 0
3 S = 0
4 FOR I = 0 TO 1 STEP 0
5 S = S + VAL(V$)
6 N = N + 1
7 READ V$
8 IF LEN(V$) THEN NEXT
9 PRINT S / N
10000 DATA1,2,2.718,3,3.142
63999 DATA
REM COLLECTION IN AN ARRAY, ITEM 0 IS THE SIZE OF THE COLLECTION
A(0) = 5 : A(1) = 1 : A(2) = 2 : A(3) = 2.718 : A(4) = 3 : A(5) = 3.142
N = A(0) : IF N THEN S = 0 : FOR I = 1 TO N : S = S + A(I) : NEXT : ? S / N
|
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
| #Clojure | Clojure |
(defn update-map [base update]
(merge base update))
(update-map {"name" "Rocket Skates"
"price" "12.75"
"color" "yellow"}
{"price" "15.25"
"color" "red"
"year" "1974"})
|
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
| #Crystal | Crystal | base = {"name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"}
update = { "price" => 15.25, "color" => "red", "year" => 1974 }
puts base.merge(update) |
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
| #Common_Lisp | Common Lisp |
(append list2 list1)
|
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%)
| #Elixir | Elixir | defmodule RC do
def factorial(0), do: 1
def factorial(n), do: Enum.reduce(1..n, 1, &(&1 * &2))
def loop_length(n), do: loop_length(n, MapSet.new)
defp loop_length(n, set) do
r = :rand.uniform(n)
if r in set, do: MapSet.size(set), else: loop_length(n, MapSet.put(set, r))
end
def task(runs) do
IO.puts " N average analytical (error) "
IO.puts "=== ========= ========== ========="
Enum.each(1..20, fn n ->
avg = Enum.reduce(1..runs, 0, fn _,sum -> sum + loop_length(n) end) / runs
analytical = Enum.reduce(1..n, 0, fn i,sum ->
sum + (factorial(n) / :math.pow(n, i) / factorial(n-i))
end)
:io.format "~3w ~9.4f ~9.4f (~6.2f%)~n", [n, avg, analytical, abs(avg/analytical - 1)*100]
end)
end
end
runs = 1_000_000
RC.task(runs) |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.