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/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
| #Oberon-2 | Oberon-2 |
MODULE AvgTimeOfDay;
IMPORT
M := LRealMath,
T := NPCT:Tools,
Out := NPCT:Console;
CONST
secsDay = 86400;
secsHour = 3600;
secsMin = 60;
toRads = M.pi / 180;
VAR
h,m,s: LONGINT;
data: ARRAY 4 OF LONGREAL;
PROCEDURE TimeToDeg(time: STRING): LONGREAL;
VAR
parts: ARRAY 3 OF STRING;
h,m,s: LONGREAL;
BEGIN
T.Split(time,':',parts);
h := T.StrToInt(parts[0]);
m := T.StrToInt(parts[1]);
s := T.StrToInt(parts[2]);
RETURN (h * secsHour + m * secsMin + s) * 360 / secsDay;
END TimeToDeg;
PROCEDURE DegToTime(d: LONGREAL; VAR h,m,s: LONGINT);
VAR
ds: LONGREAL;
PROCEDURE Mod(x,y: LONGREAL): LONGREAL;
VAR
c: LONGREAL;
BEGIN
c := ENTIER(x / y);
RETURN x - c * y
END Mod;
BEGIN
ds := Mod(d,360.0) * secsDay / 360.0;
h := ENTIER(ds / secsHour);
m := ENTIER(Mod(ds,secsHour) / secsMin);
s := ENTIER(Mod(ds,secsMin));
END DegToTime;
PROCEDURE Mean(g: ARRAY OF LONGREAL): LONGREAL;
VAR
i,l: LONGINT;
sumSin, sumCos: LONGREAL;
BEGIN
i := 0;l := LEN(g);sumSin := 0.0;sumCos := 0.0;
WHILE i < l DO
sumSin := sumSin + M.sin(g[i] * toRads);
sumCos := sumCos + M.cos(g[i] * toRads);
INC(i)
END;
RETURN M.arctan2(sumSin / l,sumCos / l) * 180 / M.pi;
END Mean;
BEGIN
data[0] := TimeToDeg("23:00:17");
data[1] := TimeToDeg("23:40:20");
data[2] := TimeToDeg("00:12:45");
data[3] := TimeToDeg("00:17:19");
DegToTime(Mean(data),h,m,s);
Out.String(":> ");Out.Int(h,0);Out.Char(':');Out.Int(m,0);Out.Char(':');Out.Int(s,0);Out.Ln
END AvgTimeOfDay.
|
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.
| #Phix | Phix | with javascript_semantics
enum KEY = 0,
LEFT,
HEIGHT, -- (NB +/-1 gives LEFT or RIGHT)
RIGHT
sequence tree = {}
integer freelist = 0
function newNode(object key)
integer node
if freelist=0 then
node = length(tree)+1
tree &= {key,NULL,1,NULL}
else
node = freelist
freelist = tree[freelist]
tree[node+KEY..node+RIGHT] = {key,NULL,1,NULL}
end if
return node
end function
function height(integer node)
return iff(node=NULL?0:tree[node+HEIGHT])
end function
procedure setHeight(integer node)
tree[node+HEIGHT] = max(height(tree[node+LEFT]), height(tree[node+RIGHT]))+1
end procedure
function rotate(integer node, integer direction)
integer idirection = LEFT+RIGHT-direction
integer pivot = tree[node+idirection]
{tree[pivot+direction],tree[node+idirection]} = {node,tree[pivot+direction]}
setHeight(node)
setHeight(pivot)
return pivot
end function
function getBalance(integer N)
return iff(N==NULL ? 0 : height(tree[N+LEFT])-height(tree[N+RIGHT]))
end function
function insertNode(integer node, object key)
if node==NULL then
return newNode(key)
end if
integer c = compare(key,tree[node+KEY])
if c!=0 then
integer direction = HEIGHT+c -- LEFT or RIGHT
-- note this crashes under p2js... (easy to fix, not so easy to find)
-- tree[node+direction] = insertNode(tree[node+direction], key)
atom tnd = insertNode(tree[node+direction], key)
tree[node+direction] = tnd
setHeight(node)
integer balance = trunc(getBalance(node)/2) -- +/-1 (or 0)
if balance then
direction = HEIGHT-balance -- LEFT or RIGHT
c = compare(key,tree[tree[node+direction]+KEY])
if c=balance then
tree[node+direction] = rotate(tree[node+direction],direction)
end if
if c!=0 then
node = rotate(node,LEFT+RIGHT-direction)
end if
end if
end if
return node
end function
function minValueNode(integer node)
while 1 do
integer next = tree[node+LEFT]
if next=NULL then exit end if
node = next
end while
return node
end function
function deleteNode(integer root, object key)
integer c
if root=NULL then return root end if
c = compare(key,tree[root+KEY])
if c=-1 then
tree[root+LEFT] = deleteNode(tree[root+LEFT], key)
elsif c=+1 then
tree[root+RIGHT] = deleteNode(tree[root+RIGHT], key)
elsif tree[root+LEFT]==NULL
or tree[root+RIGHT]==NULL then
integer temp = iff(tree[root+LEFT] ? tree[root+LEFT] : tree[root+RIGHT])
if temp==NULL then -- No child case
{temp,root} = {root,NULL}
else -- One child case
tree[root+KEY..root+RIGHT] = tree[temp+KEY..temp+RIGHT]
end if
tree[temp+KEY] = freelist
freelist = temp
else -- Two child case
integer temp = minValueNode(tree[root+RIGHT])
tree[root+KEY] = tree[temp+KEY]
tree[root+RIGHT] = deleteNode(tree[root+RIGHT], tree[temp+KEY])
end if
if root=NULL then return root end if
setHeight(root)
integer balance = trunc(getBalance(root)/2)
if balance then
integer direction = HEIGHT-balance
c = compare(getBalance(tree[root+direction]),0)
if c=-balance then
tree[root+direction] = rotate(tree[root+direction],direction)
end if
root = rotate(root,LEFT+RIGHT-direction)
end if
return root
end function
procedure inOrder(integer node)
if node!=NULL then
inOrder(tree[node+LEFT])
printf(1, "%d ", tree[node+KEY])
inOrder(tree[node+RIGHT])
end if
end procedure
integer root = NULL
sequence test = shuffle(tagset(50003))
for i=1 to length(test) do
root = insertNode(root,test[i])
end for
test = shuffle(tagset(50000))
for i=1 to length(test) do
root = deleteNode(root,test[i])
end for
inOrder(root)
|
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
| #Maple | Maple | > [ 350, 10 ] *~ Unit(arcdeg);
[350 [arcdeg], 10 [arcdeg]] |
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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | meanAngle[data_List] := N@Arg[Mean[Exp[I data Degree]]]/Degree |
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
| #Erlang | Erlang | -module(median).
-import(lists, [nth/2, sort/1]).
-compile(export_all).
test(MaxInt,ListSize,TimesToRun) ->
test(MaxInt,ListSize,TimesToRun,[[],[]]).
test(_,_,0,[GMAcc, OMAcc]) ->
Len = length(GMAcc),
{GMT,GMV} = lists:foldl(fun({T, V}, {AT,AV}) -> {AT + T, AV + V} end, {0,0}, GMAcc),
{OMT,OMV} = lists:foldl(fun({T, V}, {AT,AV}) -> {AT + T, AV + V} end, {0,0}, OMAcc),
io:format("QuickSelect Time: ~p, Val: ~p~nOriginal Time: ~p, Val: ~p~n", [GMT/Len, GMV/Len, OMT/Len, OMV/Len]);
test(M,N,T,[GMAcc, OMAcc]) ->
L = [rand:uniform(M) || _ <- lists:seq(1,N)],
GM = timer:tc(fun() -> qs_median(L) end),
OM = timer:tc(fun() -> median(L) end),
test(M,N,T-1,[[GM|GMAcc], [OM|OMAcc]]).
median(Unsorted) ->
Sorted = sort(Unsorted),
Length = length(Sorted),
Mid = Length div 2,
Rem = Length rem 2,
(nth(Mid+Rem, Sorted) + nth(Mid+1, Sorted)) / 2.
% ***********************************************************
% median based on quick select with optimizations for repeating numbers
% if it really matters it's a little faster
% by Roman Rabinovich
% ***********************************************************
qs_median([]) -> error;
qs_median([X]) -> X;
qs_median([P|_Tail] = List) ->
TargetPos = length(List)/2 + 0.5,
qs_median(List, TargetPos, P, 0).
qs_median([X], 1, _, 0) -> X;
qs_median([X], 1, _, Acc) -> (X + Acc)/2;
qs_median([P|Tail], TargetPos, LastP, Acc) ->
Smaller = [X || X <- Tail, X < P],
LS = length(Smaller),
qs_continue(P, LS, TargetPos, LastP, Smaller, Tail, Acc).
qs_continue(P, LS, TargetPos, _, _, _, 0) when LS + 1 == TargetPos -> P;
qs_continue(P, LS, TargetPos, _, _, _, Acc) when LS + 1 == TargetPos -> (P + Acc)/2;
qs_continue(P, 0, TargetPos, LastP, _SM, _TL, _Acc) when TargetPos == 0.5 ->
(P+LastP)/2;
qs_continue(P, LS, TargetPos, _LastP, SM, _TL, _Acc) when TargetPos == LS + 0.5 ->
qs_median(SM, TargetPos - 0.5, P, P);
qs_continue(P, LS, TargetPos, _LastP, SM, _TL, Acc) when LS + 1 > TargetPos ->
qs_median(SM, TargetPos, P, Acc);
qs_continue(P, LS, TargetPos, _LastP, _SM, TL, Acc) ->
Larger = [X || X <- TL, X >= P],
NewPos= TargetPos - LS -1,
case NewPos == 0.5 of
true ->
qs_median(Larger, 1, P, P);
false ->
qs_median(Larger, NewPos, P, Acc)
end.
|
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of positive integers.
The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
A
(
x
1
,
…
,
x
n
)
=
x
1
+
⋯
+
x
n
n
{\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}}
The geometric mean is the
n
{\displaystyle n}
th root of the product of the list:
G
(
x
1
,
…
,
x
n
)
=
x
1
⋯
x
n
n
{\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}}
The harmonic mean is
n
{\displaystyle n}
divided by the sum of the reciprocal of each item in the list:
H
(
x
1
,
…
,
x
n
)
=
n
1
x
1
+
⋯
+
1
x
n
{\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #J | J | amean=: +/ % #
gmean=: # %: */
hmean=: amean&.:% |
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.
| #Phix | Phix | with javascript_semantics
function bt2dec(string bt)
integer res = 0
for i=1 to length(bt) do
res = 3*res+(bt[i]='+')-(bt[i]='-')
end for
return res
end function
function negate(string bt)
for i=1 to length(bt) do
if bt[i]!='0' then
bt[i] = '+'+'-'-bt[i]
end if
end for
return bt
end function
function dec2bt(integer n)
string res = "0"
if n!=0 then
integer neg = n<0
if neg then n = -n end if
res = ""
while n!=0 do
integer r = mod(n,3)
res = "0+-"[r+1]&res
n = floor((n+(r=2))/3)
end while
if neg then res = negate(res) end if
end if
return res
end function
-- res,carry for a+b+carry lookup tables (not the fastest way to do it, I'm sure):
constant {tadd,addres} = columnize({{"---","0-"},{"--0","+-"},{"--+","-0"},
{"-0-","+-"},{"-00","-0"},{"-0+","00"},
{"-+-","-0"},{"-+0","00"},{"-++","+0"},
{"0--","+-"},{"0-0","-0"},{"0-+","00"},
{"00-","-0"},{"000","00"},{"00+","+0"},
{"0+-","00"},{"0+0","+0"},{"0++","-+"},
{"+--","-0"},{"+-0","00"},{"+-+","+0"},
{"+0-","00"},{"+00","+0"},{"+0+","-+"},
{"++-","+0"},{"++0","-+"},{"+++","0+"}})
function bt_add(string a, b)
integer padding = length(a)-length(b),
carry = '0', ch
if padding!=0 then
if padding<0 then
a = repeat('0',-padding)&a
else
b = repeat('0',padding)&b
end if
end if
for i=length(a) to 1 by -1 do
string cc = addres[find(a[i]&b[i]&carry,tadd)]
a[i] = cc[1]
carry = cc[2]
end for
if carry!='0' then
a = carry&a
else
while length(a)>1 and a[1]='0' do
a = a[2..$]
end while
end if
return a
end function
function bt_mul(string a, string b)
string pos = a, neg = negate(a), res = "0"
for i=length(b) to 1 by -1 do
integer ch = b[i]
if ch='+' then
res = bt_add(res,pos)
elsif ch='-' then
res = bt_add(res,neg)
end if
pos = pos&'0'
neg = neg&'0'
end for
return res
end function
string a = "+-0++0+", b = dec2bt(-436), c = "+-++-",
res = bt_mul(a,bt_add(b,negate(c)))
printf(1,"%7s: %12s %9d\n",{"a",a,bt2dec(a)})
printf(1,"%7s: %12s %9d\n",{"b",b,bt2dec(b)})
printf(1,"%7s: %12s %9d\n",{"c",c,bt2dec(c)})
printf(1,"%7s: %12s %9d\n",{"a*(b-c)",res,bt2dec(res)})
|
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.
| #Python | Python |
# Lines that start by # are a comments:
# they will be ignored by the machine
n=0 # n is a variable and its value is 0
# we will increase its value by one until
# its square ends in 269,696
while n**2 % 1000000 != 269696:
# n**2 -> n squared
# % -> 'modulo' or remainer after division
# != -> not equal to
n += 1 # += -> increase by a certain number
print(n) # prints n
# short version
>>> [x for x in range(30000) if (x*x) % 1000000 == 269696] [0]
25264
|
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.
| #Lobster | Lobster |
// Return whether the two numbers `a` and `b` are close.
// Closeness is determined by the `epsilon` parameter -
// the numbers are considered close if the difference between them
// is no more than epsilon * max(abs(a), abs(b)).
//
def isclose(a, b, epsilon):
return abs(a - b) <= max(abs(a), abs(b)) * epsilon
let tv = [
xy { 100000000000000.01, 100000000000000.011 },
xy { 100.01, 100.011 },
xy { 10000000000000.001 / 10000.0, 1000000000.0000001000 },
xy { 0.001, 0.0010000001 },
xy { 0.000000000000000000000101, 0.0 },
xy { sqrt(2.0) * sqrt(2.0), 2.0 },
xy { -sqrt(2.0) * sqrt(2.0), -2.0 },
xy { 3.14159265358979323846, 3.14159265358979324 }
]
for(tv) t:
print concat_string([string(t.x), if isclose(t.x, t.y, 1.0e-9): """ ≈ """ else: """ ≉ """, string(t.y)], "")
|
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.
| #Lua | Lua | function approxEquals(value, other, epsilon)
return math.abs(value - other) < epsilon
end
function test(a, b)
local epsilon = 1e-18
print(string.format("%f, %f => %s", a, b, tostring(approxEquals(a, b, epsilon))))
end
function main()
test(100000000000000.01, 100000000000000.011);
test(100.01, 100.011)
test(10000000000000.001 / 10000.0, 1000000000.0000001000)
test(0.001, 0.0010000001)
test(0.000000000000000000000101, 0.0)
test(math.sqrt(2.0) * math.sqrt(2.0), 2.0)
test(-math.sqrt(2.0) * math.sqrt(2.0), -2.0)
test(3.14159265358979323846, 3.14159265358979324)
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
| #Common_Lisp | Common Lisp |
(defun string-of-brackets (n)
(let* ((len (* 2 n))
(res (make-string len))
(opening (/ len 2))
(closing (/ len 2)))
(dotimes (i len res)
(setf (aref res i)
(cond ((zerop opening) #\])
((zerop closing) #\[)
(t (if (= (random 2) 0)
(progn (decf opening) #\[)
(progn (decf closing) #\]))))))))
(defun balancedp (string)
(zerop (reduce (lambda (nesting bracket)
(ecase bracket
(#\] (if (= nesting 0)
(return-from balancedp nil)
(1- nesting)))
(#\[ (1+ nesting))))
string
:initial-value 0)))
(defun show-balanced-brackets ()
(dotimes (i 10)
(let ((s (string-of-brackets i)))
(format t "~3A: ~A~%" (balancedp s) s))))
|
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file | Append a record to the end of a text file | Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment.
This feature is most useful in the case of log files, where many jobs may be appending to the log file at the same time, or where care must be taken to avoid concurrently overwriting the same record from another job.
Task
Given a two record sample for a mythical "passwd" file:
Write these records out in the typical system format.
Ideally these records will have named fields of various types.
Close the file, then reopen the file for append.
Append a new record to the file and close the file again.
Take appropriate care to avoid concurrently overwrites from another job.
Open the file and demonstrate the new record has indeed written to the end.
Source record field types and contents.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
jsmith
x
1001
1000
Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]
/home/jsmith
/bin/bash
jdoe
x
1002
1000
Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]
/home/jdoe
/bin/bash
Record to be appended.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
xyz
x
1003
1000
X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]
/home/xyz
/bin/bash
Resulting file format: should mimic Linux's /etc/passwd file format with particular attention to the "," separator used in the GECOS field. But if the specific language has a particular or unique format of storing records in text file, then this format should be named and demonstrated with an additional example.
Expected output:
Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash
Finally: Provide a summary of the language's "append record" capabilities in a table. eg.
Append Capabilities.
Data Representation
IO
Library
Append
Possible
Automatic
Append
Multi-tasking
Safe
In core
On disk
C struct
CSV text file
glibc/stdio
☑
☑
☑ (Not all, eg NFS)
Alternatively: If the language's appends can not guarantee its writes will always append, then note this restriction in the table. If possible, provide an actual code example (possibly using file/record locking) to guarantee correct concurrent appends.
| #COBOL | COBOL |
*> Tectonics:
*> cobc -xj append.cob
*> cobc -xjd -DDEBUG append.cob
*> ***************************************************************
identification division.
program-id. append.
environment division.
configuration section.
repository.
function all intrinsic.
input-output section.
file-control.
select pass-file
assign to pass-filename
organization is line sequential
status is pass-status.
REPLACE ==:LRECL:== BY ==2048==.
data division.
file section.
fd pass-file record varying depending on pass-length.
01 fd-pass-record.
05 filler pic x occurs 0 to :LRECL: times
depending on pass-length.
working-storage section.
01 pass-filename.
05 filler value "passfile".
01 pass-status pic xx.
88 ok-status values '00' thru '09'.
88 eof-pass value '10'.
01 pass-length usage index.
01 total-length usage index.
77 file-action pic x(11).
01 pass-record.
05 account pic x(64).
88 key-account value "xyz".
05 password pic x(64).
05 uid pic z(4)9.
05 gid pic z(4)9.
05 details.
10 fullname pic x(128).
10 office pic x(128).
10 extension pic x(32).
10 homephone pic x(32).
10 email pic x(256).
05 homedir pic x(256).
05 shell pic x(256).
77 colon pic x value ":".
77 comma-mark pic x value ",".
77 newline pic x value x"0a".
*> ***************************************************************
procedure division.
main-routine.
perform initial-fill
>>IF DEBUG IS DEFINED
display "Initial data:"
perform show-records
>>END-IF
perform append-record
>>IF DEBUG IS DEFINED
display newline "After append:"
perform show-records
>>END-IF
perform verify-append
goback
.
*> ***************************************************************
initial-fill.
perform open-output-pass-file
move "jsmith" to account
move "x" to password
move 1001 to uid
move 1000 to gid
move "Joe Smith" to fullname
move "Room 1007" to office
move "(234)555-8917" to extension
move "(234)555-0077" to homephone
move "[email protected]" to email
move "/home/jsmith" to homedir
move "/bin/bash" to shell
perform write-pass-record
move "jdoe" to account
move "x" to password
move 1002 to uid
move 1000 to gid
move "Jane Doe" to fullname
move "Room 1004" to office
move "(234)555-8914" to extension
move "(234)555-0044" to homephone
move "[email protected]" to email
move "/home/jdoe" to homedir
move "/bin/bash" to shell
perform write-pass-record
perform close-pass-file
.
*> **********************
check-pass-file.
if not ok-status then
perform file-error
end-if
.
*> **********************
check-pass-with-eof.
if not ok-status and not eof-pass then
perform file-error
end-if
.
*> **********************
file-error.
display "error " file-action space pass-filename
space pass-status upon syserr
move 1 to return-code
goback
.
*> **********************
append-record.
move "xyz" to account
move "x" to password
move 1003 to uid
move 1000 to gid
move "X Yz" to fullname
move "Room 1003" to office
move "(234)555-8913" to extension
move "(234)555-0033" to homephone
move "[email protected]" to email
move "/home/xyz" to homedir
move "/bin/bash" to shell
perform open-extend-pass-file
perform write-pass-record
perform close-pass-file
.
*> **********************
open-output-pass-file.
open output pass-file with lock
move "open output" to file-action
perform check-pass-file
.
*> **********************
open-extend-pass-file.
open extend pass-file with lock
move "open extend" to file-action
perform check-pass-file
.
*> **********************
open-input-pass-file.
open input pass-file
move "open input" to file-action
perform check-pass-file
.
*> **********************
close-pass-file.
close pass-file
move "closing" to file-action
perform check-pass-file
.
*> **********************
write-pass-record.
set total-length to 1
set pass-length to :LRECL:
string
account delimited by space
colon
password delimited by space
colon
trim(uid leading) delimited by size
colon
trim(gid leading) delimited by size
colon
trim(fullname trailing) delimited by size
comma-mark
trim(office trailing) delimited by size
comma-mark
trim(extension trailing) delimited by size
comma-mark
trim(homephone trailing) delimited by size
comma-mark
email delimited by space
colon
trim(homedir trailing) delimited by size
colon
trim(shell trailing) delimited by size
into fd-pass-record with pointer total-length
on overflow
display "error: fd-pass-record truncated at "
total-length upon syserr
end-string
set pass-length to total-length
set pass-length down by 1
write fd-pass-record
move "writing" to file-action
perform check-pass-file
.
*> **********************
read-pass-file.
read pass-file
move "reading" to file-action
perform check-pass-with-eof
.
*> **********************
show-records.
perform open-input-pass-file
perform read-pass-file
perform until eof-pass
perform show-pass-record
perform read-pass-file
end-perform
perform close-pass-file
.
*> **********************
show-pass-record.
display fd-pass-record
.
*> **********************
verify-append.
perform open-input-pass-file
move 0 to tally
perform read-pass-file
perform until eof-pass
add 1 to tally
unstring fd-pass-record delimited by colon
into account
if key-account then exit perform end-if
perform read-pass-file
end-perform
if (key-account and tally not > 2) or (not key-account) then
display
"error: appended record not found in correct position"
upon syserr
else
display "Appended record: " with no advancing
perform show-pass-record
end-if
perform close-pass-file
.
end program append. |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Apex | Apex | // Cannot / Do not need to instantiate the algorithm implementation (e.g, HashMap).
Map<String, String> strMap = new Map<String, String>();
strMap.put('a', 'aval');
strMap.put('b', 'bval');
System.assert( strMap.containsKey('a') );
System.assertEquals( 'bval', strMap.get('b') );
// String keys are case-sensitive
System.assert( !strMap.containsKey('A') ); |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #APL | APL | f←{⍸≠⌈\(⍴∘∪⊢∨⍳)¨⍳⍵} |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI or android with termux */
/* program antiprime.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
.equ NMAXI, 20
.equ MAXLINE, 5
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .asciz " @ "
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r3,iNMaxi @ load limit
mov r5,#0 @ maxi
mov r6,#0 @ result counter
mov r7,#0 @ display counter
mov r4,#1 @ number begin
1:
mov r0,r4 @ number
bl decFactor @ compute number factors
cmp r0,r5 @ maxi ?
addle r4,r4,#1 @ no -> increment indice
ble 1b @ and loop
mov r5,r0
mov r0,r4
bl displayResult
add r7,r7,#1 @ increment display counter
cmp r7,#MAXLINE @ line maxi ?
blt 2f
mov r7,#0
ldr r0,iAdrszCarriageReturn
bl affichageMess @ display message
2:
add r6,r6,#1 @ increment result counter
add r4,r4,#1 @ increment number
cmp r6,r3 @ end ?
blt 1b
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iNMaxi: .int NMAXI
/***************************************************/
/* display message number */
/***************************************************/
/* r0 contains number 1 */
/* r1 contains number 2 */
displayResult:
push {r1,lr} @ save registers
ldr r1,iAdrsZoneConv
bl conversion10 @ call décimal conversion
ldr r0,iAdrsMessResult
ldr r1,iAdrsZoneConv @ insert conversion in message
bl strInsertAtCharInc
bl affichageMess @ display message
pop {r1,pc} @ restaur des registres
iAdrsMessResult: .int sMessResult
iAdrsZoneConv: .int sZoneConv
/***************************************************/
/* compute factors sum */
/***************************************************/
/* r0 contains the number */
decFactor:
push {r1-r5,lr} @ save registers
mov r5,#0 @ init number factors
mov r4,r0 @ save number
mov r1,#1 @ start factor -> divisor
1:
mov r0,r4 @ dividende
bl division
cmp r1,r2 @ divisor > quotient ?
bgt 3f
cmp r3,#0 @ remainder = 0 ?
bne 2f
add r5,r5,#1 @ increment counter factors
cmp r1,r2 @ divisor = quotient ?
beq 3f @ yes -> end
add r5,r5,#1 @ no -> increment counter factors
2:
add r1,r1,#1 @ increment factor
b 1b @ and loop
3:
mov r0,r5 @ return counter
pop {r1-r5,pc} @ restaur registers
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
|
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.
| #Haskell | Haskell | module AtomicUpdates (main) where
import Control.Concurrent (forkIO, threadDelay)
import Control.Concurrent.MVar (MVar, newMVar, readMVar, modifyMVar_)
import Control.Monad (forever, forM_)
import Data.IntMap (IntMap, (!), toAscList, fromList, adjust)
import System.Random (randomRIO)
import Text.Printf (printf)
-------------------------------------------------------------------------------
type Index = Int
type Value = Integer
data Buckets = Buckets Index (MVar (IntMap Value))
makeBuckets :: Int -> IO Buckets
size :: Buckets -> Index
currentValue :: Buckets -> Index -> IO Value
currentValues :: Buckets -> IO (IntMap Value)
transfer :: Buckets -> Index -> Index -> Value -> IO ()
-------------------------------------------------------------------------------
makeBuckets n = do v <- newMVar (fromList [(i, 100) | i <- [1..n]])
return (Buckets n v)
size (Buckets n _) = n
currentValue (Buckets _ v) i = fmap (! i) (readMVar v)
currentValues (Buckets _ v) = readMVar v
transfer b@(Buckets n v) i j amt | amt < 0 = transfer b j i (-amt)
| otherwise = do
modifyMVar_ v $ \map -> let amt' = min amt (map ! i)
in return $ adjust (subtract amt') i
$ adjust (+ amt') j
$ map
-------------------------------------------------------------------------------
roughen, smooth, display :: Buckets -> IO ()
pick buckets = randomRIO (1, size buckets)
roughen buckets = forever loop where
loop = do i <- pick buckets
j <- pick buckets
iv <- currentValue buckets i
transfer buckets i j (iv `div` 3)
smooth buckets = forever loop where
loop = do i <- pick buckets
j <- pick buckets
iv <- currentValue buckets i
jv <- currentValue buckets j
transfer buckets i j ((iv - jv) `div` 4)
display buckets = forever loop where
loop = do threadDelay 1000000
bmap <- currentValues buckets
putStrLn (report $ map snd $ toAscList bmap)
report list = "\nTotal: " ++ show (sum list) ++ "\n" ++ bars
where bars = concatMap row $ map (*40) $ reverse [1..5]
row lim = printf "%3d " lim ++ [if x >= lim then '*' else ' ' | x <- list] ++ "\n"
main = do buckets <- makeBuckets 100
forkIO (roughen buckets)
forkIO (smooth buckets)
display buckets |
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.
| #Euphoria | Euphoria | type fourty_two(integer i)
return i = 42
end type
fourty_two i
i = 41 -- type-check failure |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #F.23 | F# | let test x =
assert (x = 42)
test 43 |
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.
| #Factor | Factor | USING: kernel ;
42 assert= |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #AppleScript | AppleScript | on callback for arg
-- Returns a string like "arc has 3 letters"
arg & " has " & (count arg) & " letters"
end callback
set alist to {"arc", "be", "circle"}
repeat with aref in alist
-- Passes a reference to some item in alist
-- to callback, then speaks the return value.
say (callback for aref)
end repeat |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Arturo | Arturo | arr: [1 2 3 4 5]
print map arr => [2*] |
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
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
run_samples()
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method mode(lvector = java.util.List) public static returns java.util.List
seen = 0
modes = ''
modeMax = 0
loop v_ = 0 to lvector.size() - 1
mv = Rexx lvector.get(v_)
seen[mv] = seen[mv] + 1
select
when seen[mv] > modeMax then do
modeMax = seen[mv]
modes = ''
nx = 1
modes[0] = nx
modes[nx] = mv
end
when seen[mv] = modeMax then do
nx = modes[0] + 1
modes[0] = nx
modes[nx] = mv
end
otherwise do
nop
end
end
end v_
modeList = ArrayList(modes[0])
loop v_ = 1 to modes[0]
val = modes[v_]
modeList.add(val)
end v_
return modeList
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method mode(rvector = Rexx[]) public static returns java.util.List
return mode(ArrayList(Arrays.asList(rvector)))
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method show_mode(lvector = java.util.List) public static returns java.util.List
modes = mode(lvector)
say 'Vector:' (Rexx lvector).space(0)', Mode(s):' (Rexx modes).space(0)
return modes
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method show_mode(rvector = Rexx[]) public static returns java.util.List
return show_mode(ArrayList(Arrays.asList(rvector)))
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method run_samples() public static
show_mode([Rexx 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) -- 10 9 8 7 6 5 4 3 2 1
show_mode([Rexx 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0.11]) -- 0
show_mode([Rexx 30, 10, 20, 30, 40, 50, -100, 4.7, -11e+2]) -- 30
show_mode([Rexx 30, 10, 20, 30, 40, 50, -100, 4.7, -11e+2, -11e+2]) -- 30 -11e2
show_mode([Rexx 1, 8, 6, 0, 1, 9, 4, 6, 1, 9, 9, 9]) -- 9
show_mode([Rexx 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) -- 1 2 3 4 5 6 7 8 9 10 11
show_mode([Rexx 8, 8, 8, 2, 2, 2]) -- 8 2
show_mode([Rexx 'cat', 'kat', 'Cat', 'emu', 'emu', 'Kat']) -- emu
show_mode([Rexx 0, 1, 2, 3, 3, 3, 4, 4, 4, 4, 1, 0]) -- 4
show_mode([Rexx 2, 7, 1, 8, 2]) -- 2
show_mode([Rexx 2, 7, 1, 8, 2, 8]) -- 8 2
show_mode([Rexx 'E', 'n', 'z', 'y', 'k', 'l', 'o', 'p', 'ä', 'd', 'i', 'e']) -- E n z y k l o p ä d i e
show_mode([Rexx 'E', 'n', 'z', 'y', 'k', 'l', 'o', 'p', 'ä', 'd', 'i', 'e', 'ä']) -- ä
show_mode([Rexx 3, 1, 4, 1, 5, 9, 7, 6]) -- 1
show_mode([Rexx 3, 1, 4, 1, 5, 9, 7, 6, 3]) -- 3, 1
show_mode([Rexx 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]) -- 6
show_mode([Rexx 1, 1, 2, 4, 4]) -- 4 1
return
|
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #C.23 | C# | using System;
using System.Collections.Generic;
namespace AssocArrays
{
class Program
{
static void Main(string[] args)
{
Dictionary<string,int> assocArray = new Dictionary<string,int>();
assocArray["Hello"] = 1;
assocArray.Add("World", 2);
assocArray["!"] = 3;
foreach (KeyValuePair<string, int> kvp in assocArray)
{
Console.WriteLine(kvp.Key + " : " + kvp.Value);
}
foreach (string key in assocArray.Keys)
{
Console.WriteLine(key);
}
foreach (int val in assocArray.Values)
{
Console.WriteLine(val.ToString());
}
}
}
}
|
http://rosettacode.org/wiki/Apply_a_digital_filter_(direct_form_II_transposed) | Apply a digital filter (direct form II transposed) | Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [1]
Task
Filter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667]
The signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]
| #Groovy | Groovy | class DigitalFilter {
private static double[] filter(double[] a, double[] b, double[] signal) {
double[] result = new double[signal.length]
for (int i = 0; i < signal.length; ++i) {
double tmp = 0.0
for (int j = 0; j < b.length; ++j) {
if (i - j < 0) continue
tmp += b[j] * signal[i - j]
}
for (int j = 1; j < a.length; ++j) {
if (i - j < 0) continue
tmp -= a[j] * result[i - j]
}
tmp /= a[0]
result[i] = tmp
}
return result
}
static void main(String[] args) {
double[] a = [1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] as double[]
double[] b = [0.16666667, 0.5, 0.5, 0.16666667] as double[]
double[] 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
] as double[]
double[] result = filter(a, b, signal)
for (int i = 0; i < result.length; ++i) {
printf("% .8f", result[i])
print((i + 1) % 5 != 0 ? ", " : "\n")
}
}
} |
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
| #COBOL | COBOL | FUNCTION MEAN(some-table (ALL)) |
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
| #Cobra | Cobra |
class Rosetta
def mean(ns as List<of number>) as number
if ns.count == 0
return 0
else
sum = 0.0
for n in ns
sum += n
return sum / ns.count
def main
print "mean of [[]] is [.mean(List<of number>())]"
print "mean of [[1,2,3,4]] is [.mean([1.0,2.0,3.0,4.0])]"
|
http://rosettacode.org/wiki/Associative_array/Merging | Associative array/Merging | Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:
Key
Value
"name"
"Rocket Skates"
"price"
15.25
"color"
"red"
"year"
1974
| #Phix | Phix | with javascript_semantics
integer d1 = new_dict({{"name","Rocket Skates"},{"price",12.75},{"color","yellow"}}),
d2 = new_dict({{"price",15.25},{"color","red"},{"year",1974}}),
d3 = new_dict(d1)
function merger(object key, data, /*user_data*/) setd(key,data,d3) return 1 end function
traverse_dict(merger,NULL,d2)
include builtins/map.e
?pairs(d3)
|
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
| #Phixmonti | Phixmonti | include ..\Utilitys.pmt
def scand /# dict key -- dict n #/
0 var flag
var ikey
len for
var i
i 1 2 tolist sget
ikey == if i var flag exitfor endif
endfor
flag
enddef
def getd /# dict key -- dict data #/
scand
dup if get 2 get nip else drop "Unfound" endif
enddef
def setd /# dict ( key data ) -- dict #/
1 get rot swap
scand
rot swap
dup if set else put endif
enddef
/# ---------- MAIN ---------- #/
( ( "name" "Rocket Skates" )
( "price" 12.75 )
( "color" "yellow" ) )
dup
( ( "price" 15.25 )
( "color" "red" )
( "year" 1974 ) )
len for
get rot swap setd swap
endfor
swap
pstack
|
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
| #PHP | PHP | <?
$base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
$update = array("price" => 15.25, "color" => "red", "year" => 1974);
$result = $update + $base; // Notice that the order is reversed
print_r($result);
?> |
http://rosettacode.org/wiki/Average_loop_length | Average loop length | Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence.
Task
Write a program or a script that estimates, for each N, the average length until the first such repetition.
Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.
This problem comes from the end of Donald Knuth's Christmas tree lecture 2011.
Example of expected output:
N average analytical (error)
=== ========= ============ =========
1 1.0000 1.0000 ( 0.00%)
2 1.4992 1.5000 ( 0.05%)
3 1.8784 1.8889 ( 0.56%)
4 2.2316 2.2188 ( 0.58%)
5 2.4982 2.5104 ( 0.49%)
6 2.7897 2.7747 ( 0.54%)
7 3.0153 3.0181 ( 0.09%)
8 3.2429 3.2450 ( 0.07%)
9 3.4536 3.4583 ( 0.14%)
10 3.6649 3.6602 ( 0.13%)
11 3.8091 3.8524 ( 1.12%)
12 3.9986 4.0361 ( 0.93%)
13 4.2074 4.2123 ( 0.12%)
14 4.3711 4.3820 ( 0.25%)
15 4.5275 4.5458 ( 0.40%)
16 4.6755 4.7043 ( 0.61%)
17 4.8877 4.8579 ( 0.61%)
18 4.9951 5.0071 ( 0.24%)
19 5.1312 5.1522 ( 0.41%)
20 5.2699 5.2936 ( 0.45%)
| #Phixmonti | Phixmonti | include ..\Utilitys.pmt
20 var MAX
100000 var ITER
def factorial 1 swap for * endfor enddef
def expected /# n -- n #/
>ps
0
tps for var i
tps factorial tps i power / tps i - factorial / +
endfor
ps> drop
enddef
def condition over over bitand not enddef
def test /# n -- n #/
0 >ps
ITER for var i
0 1
condition while
ps> 1 + >ps
bitor
over rand * 1 + int 1 - 2 swap power
condition endwhile
drop drop
endfor
drop ps> ITER /
enddef
def printAll len for get print 9 tochar print endfor enddef
( "n" "avg." "exp." "(error%)" ) printAll drop nl
( "==" "======" "======" "========" ) printAll drop nl
MAX for var n
n test
n expected
n rot rot over over / 1 swap - abs 100 * 4 tolist printAll drop nl
endfor |
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%)
| #PicoLisp | PicoLisp | (scl 4)
(seed (in "/dev/urandom" (rd 8)))
(de fact (N)
(if (=0 N) 1 (apply * (range 1 N))) )
(de analytical (N)
(sum
'((I)
(/
(* (fact N) 1.0)
(** N I)
(fact (- N I)) ) )
(range 1 N) ) )
(de testing (N)
(let (C 0 N (dec N) X 0 B 0 I 1000000)
(do I
(zero B)
(one X)
(while (=0 (& B X))
(inc 'C)
(setq
B (| B X)
X (** 2 (rand 0 N)) ) ) )
(*/ C 1.0 I) ) )
(let F (2 8 8 6)
(tab F "N" "Avg" "Exp" "Diff")
(for I 20
(let (A (testing I) B (analytical I))
(tab F
I
(round A 4)
(round B 4)
(round
(*
(abs (- (*/ A 1.0 B) 1.0))
100 )
2 ) ) ) ) )
(bye) |
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
| #Run_Basic | Run Basic | data 1,2,3,4,5,5,4,3,2,1
dim sd(10) ' series data
global sd ' make it global so we all see it
for i = 1 to 10:read sd(i): next i
x = sma(3) ' simple moving average for 3 periods
x = sma(5) ' simple moving average for 5 periods
function sma(p) ' the simple moving average function
print "----- SMA:";p;" -----"
for i = 1 to 10
sumSd = 0
for j = max((i - p) + 1,1) to i
sumSd = sumSd + sd(j) ' sum series data for the period
next j
if p > i then p1 = i else p1 = p
print sd(i);" sma:";p;" ";sumSd / p1
next i
end function |
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.
| #J | J |
echo (#~ (1 p: ])@#@q:) >:i.120
|
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.
| #JavaScript | JavaScript | (() => {
'use strict';
// attractiveNumbers :: () -> Gen [Int]
const attractiveNumbers = () =>
// An infinite series of attractive numbers.
filter(
compose(isPrime, length, primeFactors)
)(enumFrom(1));
// ----------------------- TEST -----------------------
// main :: IO ()
const main = () =>
showCols(10)(
takeWhile(ge(120))(
attractiveNumbers()
)
);
// ---------------------- PRIMES ----------------------
// isPrime :: Int -> Bool
const isPrime = n => {
// True if n is prime.
if (2 === n || 3 === n) {
return true
}
if (2 > n || 0 === n % 2) {
return false
}
if (9 > n) {
return true
}
if (0 === n % 3) {
return false
}
return !enumFromThenTo(5)(11)(
1 + Math.floor(Math.pow(n, 0.5))
).some(x => 0 === n % x || 0 === n % (2 + x));
};
// primeFactors :: Int -> [Int]
const primeFactors = n => {
// A list of the prime factors of n.
const
go = x => {
const
root = Math.floor(Math.sqrt(x)),
m = until(
([q, _]) => (root < q) || (0 === (x % q))
)(
([_, r]) => [step(r), 1 + r]
)([
0 === x % 2 ? (
2
) : 3,
1
])[0];
return m > root ? (
[x]
) : ([m].concat(go(Math.floor(x / m))));
},
step = x => 1 + (x << 2) - ((x >> 1) << 1);
return go(n);
};
// ---------------- GENERIC FUNCTIONS -----------------
// chunksOf :: Int -> [a] -> [[a]]
const chunksOf = n =>
xs => enumFromThenTo(0)(n)(
xs.length - 1
).reduce(
(a, i) => a.concat([xs.slice(i, (n + i))]),
[]
);
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
const compose = (...fs) =>
fs.reduce(
(f, g) => x => f(g(x)),
x => x
);
// enumFrom :: Enum a => a -> [a]
function* enumFrom(x) {
// A non-finite succession of enumerable
// values, starting with the value x.
let v = x;
while (true) {
yield v;
v = 1 + v;
}
}
// enumFromThenTo :: Int -> Int -> Int -> [Int]
const enumFromThenTo = x1 =>
x2 => y => {
const d = x2 - x1;
return Array.from({
length: Math.floor(y - x2) / d + 2
}, (_, i) => x1 + (d * i));
};
// filter :: (a -> Bool) -> Gen [a] -> [a]
const filter = p => xs => {
function* go() {
let x = xs.next();
while (!x.done) {
let v = x.value;
if (p(v)) {
yield v
}
x = xs.next();
}
}
return go(xs);
};
// ge :: Ord a => a -> a -> Bool
const ge = x =>
// True if x >= y
y => x >= y;
// justifyRight :: Int -> Char -> String -> String
const justifyRight = n =>
// The string s, preceded by enough padding (with
// the character c) to reach the string length n.
c => s => n > s.length ? (
s.padStart(n, c)
) : s;
// last :: [a] -> a
const last = xs =>
// The last item of a list.
0 < xs.length ? xs.slice(-1)[0] : undefined;
// length :: [a] -> Int
const length = xs =>
// Returns Infinity over objects without finite
// length. This enables zip and zipWith to choose
// the shorter argument when one is non-finite,
// like cycle, repeat etc
(Array.isArray(xs) || 'string' === typeof xs) ? (
xs.length
) : Infinity;
// map :: (a -> b) -> [a] -> [b]
const map = f =>
// The list obtained by applying f
// to each element of xs.
// (The image of xs under f).
xs => (
Array.isArray(xs) ? (
xs
) : xs.split('')
).map(f);
// showCols :: Int -> [a] -> String
const showCols = w => xs => {
const
ys = xs.map(str),
mx = last(ys).length;
return unlines(chunksOf(w)(ys).map(
row => row.map(justifyRight(mx)(' ')).join(' ')
))
};
// str :: a -> String
const str = x =>
x.toString();
// takeWhile :: (a -> Bool) -> Gen [a] -> [a]
const takeWhile = p => xs => {
const ys = [];
let
nxt = xs.next(),
v = nxt.value;
while (!nxt.done && p(v)) {
ys.push(v);
nxt = xs.next();
v = nxt.value
}
return ys;
};
// unlines :: [String] -> String
const unlines = xs =>
// A single string formed by the intercalation
// of a list of strings with the newline character.
xs.join('\n');
// until :: (a -> Bool) -> (a -> a) -> a -> a
const until = p => f => x => {
let v = x;
while (!p(v)) v = f(v);
return v;
};
// MAIN ---
return main();
})(); |
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
| #OCaml | OCaml | let pi_twice = 2.0 *. 3.14159_26535_89793_23846_2643
let day = float (24 * 60 * 60)
let rad_of_time t =
t *. pi_twice /. day
let time_of_rad r =
r *. day /. pi_twice
let mean_angle angles =
let sum_sin = List.fold_left (fun sum a -> sum +. sin a) 0.0 angles
and sum_cos = List.fold_left (fun sum a -> sum +. cos a) 0.0 angles in
atan2 sum_sin sum_cos
let mean_time times =
let angles = List.map rad_of_time times in
let t = time_of_rad (mean_angle angles) in
if t < 0.0 then t +. day else t
let parse_time t =
Scanf.sscanf t "%d:%d:%d" (fun h m s -> float (s + m * 60 + h * 3600))
let round x = int_of_float (floor (x +. 0.5))
let string_of_time t =
let t = round t in
let h = t / 3600 in
let rem = t mod 3600 in
let m = rem / 60 in
let s = rem mod 60 in
Printf.sprintf "%d:%d:%d" h m s
let () =
let times = ["23:00:17"; "23:40:20"; "00:12:45"; "00:17:19"] in
Printf.printf "The mean time of [%s] is: %s\n"
(String.concat "; " times)
(string_of_time (mean_time (List.map parse_time times))) |
http://rosettacode.org/wiki/AVL_tree | AVL tree |
This page uses content from Wikipedia. The original article was at AVL tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In computer science, an AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; at no time do they differ by more than one because rebalancing is done ensure this is the case. Lookup, insertion, and deletion all take O(log n) time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations. Note the tree of nodes comprise a set, so duplicate node keys are not allowed.
AVL trees are often compared with red-black trees because they support the same set of operations and because red-black trees also take O(log n) time for the basic operations. Because AVL trees are more rigidly balanced, they are faster than red-black trees for lookup-intensive applications. Similar to red-black trees, AVL trees are height-balanced, but in general not weight-balanced nor μ-balanced; that is, sibling nodes can have hugely differing numbers of descendants.
Task
Implement an AVL tree in the language of choice, and provide at least basic operations.
| #Picat | Picat | main =>
T = nil,
foreach (X in 1..10)
T := insert(X,T)
end,
output(T,0).
insert(X, nil) = {1,nil,X,nil}.
insert(X, T@{H,L,V,R}) = Res =>
if X < V then
Res = rotate({H, insert(X,L) ,V,R})
elseif X > V then
Res = rotate({H,L,V, insert(X,R)})
else
Res = T
end.
rotate(nil) = nil.
rotate({H, {LH,LL,LV,LR}, V, R}) = Res,
LH - height(R) > 1,
height(LL) - height(LR) > 0
=> % Left Left.
Res = {LH,LL,LV, {depth(R,LR), LR,V,R}}.
rotate({H,L,V, {RH,RL,RV,RR}}) = Res,
RH - height(L) > 1,
height(RR) - height(RL) > 0
=> % Right Right.
Res = {RH, {depth(L,RL),L,V,RL}, RV,RR}.
rotate({H, {LH,LL,LV, {RH,RL,RV,RR}, V,R}}) = Res,
LH - height(R) > 1
=> % Left Right.
Res = {H, {RH + 1, {LH - 1, LL, LV, RL}, RV, RR}, V, R}.
rotate({H,L,V, {RH, {LH,LL,LV,LR},RV,RR}}) = Res,
RH - height(L) > 1
=> % Right Left.
Res = {H,L,V, {LH+1, LL, LV, {RH-1, LR, RV, RR}}}.
rotate({H,L,V,R}) = Res => % Re-weighting.
L1 = rotate(L),
R1 = rotate(R),
Res = {depth(L1,R1), L1,V,R1}.
height(nil) = -1.
height({H,_,_,_}) = H.
depth(A,B) = max(height(A), height(B)) + 1.
output(nil,Indent) => printf("%*w\n",Indent,nil).
output({_,L,V,R},Indent) =>
output(L,Indent+6),
printf("%*w\n",Indent,V),
output(R,Indent+6).
|
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
| #MATLAB_.2F_Octave | MATLAB / Octave | function u = mean_angle(phi)
u = angle(mean(exp(i*pi*phi/180)))*180/pi;
end |
http://rosettacode.org/wiki/Averages/Mean_angle | Averages/Mean angle | When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle.
If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the second was of 10 degrees then the average of the numbers is 180 degrees, whereas if you can note that 350 degrees is equivalent to -10 degrees and so you have two readings at 10 degrees either side of zero degrees leading to a more fitting mean angle of zero degrees.
To calculate the mean angle of several angles:
Assume all angles are on the unit circle and convert them to complex numbers expressed in real and imaginary form.
Compute the mean of the complex numbers.
Convert the complex mean to polar coordinates whereupon the phase of the complex mean is the required angular mean.
(Note that, since the mean is the sum divided by the number of numbers, and division by a positive real number does not affect the angle, you can also simply compute the sum for step 2.)
You can alternatively use this formula:
Given the angles
α
1
,
…
,
α
n
{\displaystyle \alpha _{1},\dots ,\alpha _{n}}
the mean is computed by
α
¯
=
atan2
(
1
n
⋅
∑
j
=
1
n
sin
α
j
,
1
n
⋅
∑
j
=
1
n
cos
α
j
)
{\displaystyle {\bar {\alpha }}=\operatorname {atan2} \left({\frac {1}{n}}\cdot \sum _{j=1}^{n}\sin \alpha _{j},{\frac {1}{n}}\cdot \sum _{j=1}^{n}\cos \alpha _{j}\right)}
Task[edit]
write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle.
(You should use a built-in function if you have one that does this for degrees or radians).
Use the function to compute the means of these lists of angles (in degrees):
[350, 10]
[90, 180, 270, 360]
[10, 20, 30]
Show your output here.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
numeric digits 80
runSample(arg)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method getMeanAngle(angles) private static binary
x_component = double 0.0
y_component = double 0.0
aK = int angles.words()
loop a_ = 1 to aK
angle_d = double angles.word(a_)
angle_r = double Math.toRadians(angle_d)
x_component = x_component + Math.cos(angle_r)
y_component = y_component + Math.sin(angle_r)
end a_
x_component = x_component / aK
y_component = y_component / aK
avg_r = Math.atan2(y_component, x_component)
avg_d = Math.toDegrees(avg_r)
return avg_d
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
angleSet = [ '350 10', '90 180 270 360', '10 20 30', '370', '180' ]
loop angles over angleSet
say 'The mean angle of' angles.space(1, ',') 'is:'
say ' 'getMeanAngle(angles).format(6, 6)
say
end angles
return
|
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches to this. One is to sort the elements, and then pick the element(s) in the middle.
Sorting would take at least O(n logn). Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s). This would also take O(n logn). The best solution is to use the selection algorithm to find the median in O(n) time.
See also
Quickselect_algorithm
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #ERRE | ERRE |
PROGRAM MEDIAN
DIM X[10]
PROCEDURE QUICK_SELECT
LT=0 RT=L-1
J=LT
REPEAT
PT=X[K]
SWAP(X[K],X[RT])
P=LT
FOR I=P TO RT-1 DO
IF X[I]<PT THEN SWAP(X[I],X[P]) P=P+1 END IF
END FOR
SWAP(X[RT],X[P])
IF P=K THEN EXIT PROCEDURE END IF
IF P<K THEN LT=P+1 END IF
IF P>=K THEN RT=P-1 END IF
UNTIL J>RT
END PROCEDURE
PROCEDURE MEDIAN
K=INT(L/2)
QUICK_SELECT
R=X[K]
IF L-2*INT(L/2)<>0 THEN R=(R+X[K+1])/2 END IF
END PROCEDURE
BEGIN
PRINT(CHR$(12);) !CLS
X[0]=4.4 X[1]=2.3 X[2]=-1.7 X[3]=7.5 X[4]=6.6 X[5]=0
X[6]=1.9 X[7]=8.2 X[8]=9.3 X[9]=4.5 X[10]=-11.7
L=11
MEDIAN
PRINT(R)
END PROGRAM
|
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
| #Euler_Math_Toolbox | Euler Math Toolbox |
>type median
function median (x, v: none, p)
## Default for v : none
## Default for p : 0.5
m=rows(x);
if m>1 then
y=zeros(m,1);
loop 1 to m;
y[#]=median(x[#],v,p);
end;
return y;
else
if v<>none then
{xs,i}=sort(x); vsh=v[i];
n=cols(xs);
ns=sum(vsh);
i=1+p*(ns-1); i0=floor(i);
vs=cumsum(vsh);
loop 1 to n
if vs[#]>i0 then
return xs[#];
elseif vs[#]+1>i0 then
k=#+1;
repeat;
if vsh[k]>0 or k>n then break; endif;
k=k+1;
end;
return (1-(i-i0))*xs[#]+(i-i0)*xs[k]+0;
endif;
end;
return xs[n];
else
xs=sort(x);
n=cols(x);
i=1+p*(n-1); i0=floor(i);
if i0==n then return xs[n]; endif;
return (i-i0)*xs[i+1]+(1-(i-i0))*xs[i];
endif;
endif;
endfunction
>median(1:10)
5.5
>median(1:9)
5
>median(1:10,p=0.2)
2.8
>0.2*10+0.8*1
2.8
|
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
| #Java | Java | import java.util.Arrays;
import java.util.List;
public class PythagoreanMeans {
public static double arithmeticMean(List<Double> numbers) {
if (numbers.isEmpty()) return Double.NaN;
double mean = 0.0;
for (Double number : numbers) {
mean += number;
}
return mean / numbers.size();
}
public static double geometricMean(List<Double> numbers) {
if (numbers.isEmpty()) return Double.NaN;
double mean = 1.0;
for (Double number : numbers) {
mean *= number;
}
return Math.pow(mean, 1.0 / numbers.size());
}
public static double harmonicMean(List<Double> numbers) {
if (numbers.isEmpty() || numbers.contains(0.0)) return Double.NaN;
double mean = 0.0;
for (Double number : numbers) {
mean += (1.0 / number);
}
return numbers.size() / mean;
}
public static void main(String[] args) {
Double[] array = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0};
List<Double> list = Arrays.asList(array);
double arithmetic = arithmeticMean(list);
double geometric = geometricMean(list);
double harmonic = harmonicMean(list);
System.out.format("A = %f G = %f H = %f%n", arithmetic, geometric, harmonic);
System.out.format("A >= G is %b, G >= H is %b%n", (arithmetic >= geometric), (geometric >= harmonic));
}
} |
http://rosettacode.org/wiki/Balanced_ternary | Balanced ternary | Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1.
Examples
Decimal 11 = 32 + 31 − 30, thus it can be written as "++−"
Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0"
Task
Implement balanced ternary representation of integers with the following:
Support arbitrarily large integers, both positive and negative;
Provide ways to convert to and from text strings, using digits '+', '-' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5).
Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type is balanced ternary). If your native integers can't support arbitrary length, overflows during conversion must be indicated.
Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do not convert to native integers first.
Make your implementation efficient, with a reasonable definition of "efficient" (and with a reasonable definition of "reasonable").
Test case With balanced ternaries a from string "+-0++0+", b from native integer -436, c "+-++-":
write out a, b and c in decimal notation;
calculate a × (b − c), write out the result in both ternary and decimal notations.
Note: The pages generalised floating point addition and generalised floating point multiplication have code implementing arbitrary precision floating point balanced ternary.
| #PicoLisp | PicoLisp | (seed (in "/dev/urandom" (rd 8)))
(setq *G '((0 -1) (1 -1) (-1 0) (0 0) (1 0) (-1 1) (0 1)))
# For humans
(de negh (L)
(mapcar
'((I)
(case I
(- '+)
(+ '-)
(T 0) ) )
L ) )
(de trih (X)
(if (num? X)
(let (S (lt0 X) X (abs X) R NIL)
(if (=0 X)
(push 'R 0)
(until (=0 X)
(push 'R
(case (% X 3)
(0 0)
(1 '+)
(2 (inc 'X) '-) ) )
(setq X (/ X 3)) ) )
(if S (pack (negh R)) (pack R)) )
(let M 1
(sum
'((C)
(prog1
(unless (= C "0") ((intern C) M))
(setq M (* 3 M)) ) )
(flip (chop X)) ) ) ) )
# For robots
(de neg (L)
(mapcar
'((I)
(case I (-1 1) (1 -1) (T 0)) )
L ) )
(de tri (X)
(if (num? X)
(let (S (lt0 X) X (abs X) R NIL)
(if (=0 X)
(push 'R 0)
(until (=0 X)
(push 'R
(case (% X 3)
(0 0)
(1 1)
(2 (inc 'X) (- 1)) ) )
(setq X (/ X 3)) ) )
(flip (if S (neg R) R)) )
(let M 1
(sum
'((C)
(prog1 (* C M) (setq M (* 3 M))) )
X ) ) ) )
(de add (D1 D2)
(let
(L (max (length D1) (length D2))
D1 (need (- L) D1 0)
D2 (need (- L) D2 0)
C 0 )
(mapcon
'((L1 L2)
(let R
(get
*G
(+ 4 (+ (car L1) (car L2) C)) )
(ifn (cdr L1)
R
(setq C (cadr R))
(cons (car R)) ) ) )
D1
D2 ) ) )
(de mul (D1 D2)
(ifn (and D1 D2)
0
(add
(case (car D1)
(0 0)
(1 D2)
(-1 (neg D2)) )
(cons 0 (mul (cdr D1) D2) ) ) ) )
(de sub (D1 D2)
(add D1 (neg D2)) )
# Random testing
(let (X 0 Y 0 C 2048)
(do C
(setq
X (rand (- C) C)
Y (rand (- C) C) )
(test X (trih (trih X)))
(test X (tri (tri X)))
(test
(+ X Y)
(tri (add (tri X) (tri Y))) )
(test
(- X Y)
(tri (sub (tri X) (tri Y))) )
(test
(* X Y)
(tri (mul (tri X) (tri Y))) ) ) )
(println 'A (trih 523) (trih "+-0++0+"))
(println 'B (trih -436) (trih "-++-0--"))
(println 'C (trih 65) (trih "+-++-"))
(let R
(tri
(mul
(tri (trih "+-0++0+"))
(sub (tri -436) (tri (trih "+-++-"))) ) )
(println 'R (trih R) R) )
(bye) |
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.
| #Quackery | Quackery | ( . . . . . . . . . . . . . . . . . . )
( The computer will ignore anything between parentheses, providing there is
a space or carriage return on either side of each parenthesis. )
( . . . . . . . . . . . . . . . . . . )
( A number squared is that number, multiplied by itself.
Here, "dup" means "make a duplicate" and "*" means "multiply two numbers",
So "dup *" means "make a duplicate of a number and multiply it by itself".
We will tell the computer that this action is called "squared". )
[ dup * ] is squared
( "squared" takes a number and returns that number, squared. )
( . . . . . . . . . . . . . . . . . . )
( A number n ends with the digits 269696 if n mod 1000000 = 269696,
When expressed in postfix notation this is: 1000000 mod 269696 =
We will tell the computer that this test is called "ends.with.269696". )
[ 1000000 mod 269696 = ] is ends.with.269696
( "ends.with.269696" takes a number and returns true if it ends with 269696,
and false if it does not. )
( . . . . . . . . . . . . . . . . . . )
( The square root of 269696 is approximately equal to 518.35, so we need not
consider numbers less than 519.
Starting withe 518, we will intruct the computer to repeatedly add 2 to
the number using the command "2 +" (because the number we are looking for
must be an even number as the square root of any even perfect square
must be an even number), then square a duplicate of the number until a
value is found of which its square ends with 269696.
"until" will take the truth value returned by "ends.with.269696" and, if
that value is "false", will cause the previous commands from the nearest
"[" preceding "until" to be repeated.
When the value is "true" the computer will proceed to the word "echo",
which will take the calculated solution and display it on the screen. )
518 [ 2 + dup squared ends.with.269696 until ] echo
( . . . . . . . . . . . . . . . . . . ) |
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.
| #R | R |
babbage_function=function(){
n=0
while (n**2%%1000000!=269696) {
n=n+1
}
return(n)
}
babbage_function()[length(babbage_function())]
|
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[CloseEnough]
CloseEnough[a_, b_, tol_] := Chop[a - b, tol] == 0
numbers = {
{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}
};
(*And@@Flatten[Map[MachineNumberQ,numbers,{2}]]*)
{#1, #2, CloseEnough[#1, #2, 10^-9]} & @@@ numbers // Grid |
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.
| #Nim | Nim | from math import sqrt
import strformat
import strutils
const Tolerance = 1e-10
proc `~=`(a, b: float): bool =
## Check if "a" and "b" are close.
## We use a relative tolerance to compare the values.
result = abs(a - b) < max(abs(a), abs(b)) * Tolerance
proc compare(a, b: string) =
## Compare "a" and "b" transmitted as strings.
## Values are computed using "parseFloat".
let r = a.parseFloat() ~= b.parseFloat()
echo fmt"{a} ~= {b} is {r}"
proc compare(a: string; avalue: float; b: string) =
## Compare "a" and "b" transmitted as strings.
## The value of "a" is transmitted and not computed.
let r = avalue ~= b.parseFloat()
echo fmt"{a} ~= {b} is {r}"
compare("100000000000000.01", "100000000000000.011")
compare("100.01", "100.011")
compare("10000000000000.001 / 10000.0", 10000000000000.001 / 10000.0, "1000000000.0000001000")
compare("0.001", "0.0010000001")
compare("0.000000000000000000000101", "0.0")
compare("sqrt(2) * sqrt(2)", sqrt(2.0) * sqrt(2.0), "2.0")
compare("-sqrt(2) * sqrt(2)", -sqrt(2.0) * sqrt(2.0), "-2.0")
compare("3.14159265358979323846", "3.14159265358979324") |
http://rosettacode.org/wiki/Approximate_equality | Approximate equality | Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the
difference in floating point calculations between different language implementations becomes significant.
For example, a difference between 32 bit and 64 bit floating point calculations may appear by
about the 8th significant digit in base 10 arithmetic.
Task
Create a function which returns true if two floating point numbers are approximately equal.
The function should allow for differences in the magnitude of numbers, so that, for example,
100000000000000.01 may be approximately equal to 100000000000000.011,
even though 100.01 is not approximately equal to 100.011.
If the language has such a feature in its standard library, this may be used instead of a custom function.
Show the function results with comparisons on the following pairs of values:
100000000000000.01, 100000000000000.011 (note: should return true)
100.01, 100.011 (note: should return false)
10000000000000.001 / 10000.0, 1000000000.0000001000
0.001, 0.0010000001
0.000000000000000000000101, 0.0
sqrt(2) * sqrt(2), 2.0
-sqrt(2) * sqrt(2), -2.0
3.14159265358979323846, 3.14159265358979324
Answers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.
| #OCaml | OCaml | let approx_eq v1 v2 epsilon =
Float.abs (v1 -. v2) < epsilon
let test a b =
let epsilon = 1e-18 in
Printf.printf "%g, %g => %b\n" a b (approx_eq a b epsilon)
let () =
test 100000000000000.01 100000000000000.011;
test 100.01 100.011;
test (10000000000000.001 /. 10000.0) 1000000000.0000001000;
test 0.001 0.0010000001;
test 0.000000000000000000000101 0.0;
test ((sqrt 2.0) *. (sqrt 2.0)) 2.0;
test (-. (sqrt 2.0) *. (sqrt 2.0)) (-2.0);
test 3.14159265358979323846 3.14159265358979324;
;;
|
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #Component_Pascal | Component Pascal |
MODULE Brackets;
IMPORT StdLog, Args, Stacks (* See Task Stacks *);
TYPE
Character = POINTER TO RECORD (Stacks.Object)
c: CHAR
END;
PROCEDURE NewCharacter(c: CHAR): Character;
VAR
n: Character;
BEGIN
NEW(n);n.c:= c;RETURN n
END NewCharacter;
PROCEDURE (c: Character) Show*;
BEGIN
StdLog.String("Character(");StdLog.Char(c.c);StdLog.String(");");StdLog.Ln
END Show;
PROCEDURE CheckBalance(str: ARRAY OF CHAR): BOOLEAN;
VAR
s: Stacks.Stack;
n,x: ANYPTR;
i: INTEGER;
c : CHAR;
BEGIN
i := 0; s := Stacks.NewStack();
WHILE (i < LEN(str$)) & (~Args.IsBlank(str[i])) & (str[i] # 0X) DO
IF s.Empty() THEN
s.Push(NewCharacter(str[i]));
ELSE
n := s.top.data;
WITH
n : Character DO
IF (str[i] = ']')& (n.c = '[') THEN
x := s.Pop();
ELSE
s.Push(NewCharacter(str[i]))
END;
ELSE RETURN FALSE;
END;
END;
INC(i)
END;
RETURN s.Empty();
END CheckBalance;
PROCEDURE Do*;
VAR
p : Args.Params;
i: INTEGER;
BEGIN
Args.Get(p); (* Get Params *)
FOR i := 0 TO p.argc - 1 DO
StdLog.String(p.args[i] + ":>");StdLog.Bool(CheckBalance(p.args[i]));StdLog.Ln
END
END Do;
END Brackets.
|
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file | Append a record to the end of a text file | Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment.
This feature is most useful in the case of log files, where many jobs may be appending to the log file at the same time, or where care must be taken to avoid concurrently overwriting the same record from another job.
Task
Given a two record sample for a mythical "passwd" file:
Write these records out in the typical system format.
Ideally these records will have named fields of various types.
Close the file, then reopen the file for append.
Append a new record to the file and close the file again.
Take appropriate care to avoid concurrently overwrites from another job.
Open the file and demonstrate the new record has indeed written to the end.
Source record field types and contents.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
jsmith
x
1001
1000
Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]
/home/jsmith
/bin/bash
jdoe
x
1002
1000
Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]
/home/jdoe
/bin/bash
Record to be appended.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
xyz
x
1003
1000
X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]
/home/xyz
/bin/bash
Resulting file format: should mimic Linux's /etc/passwd file format with particular attention to the "," separator used in the GECOS field. But if the specific language has a particular or unique format of storing records in text file, then this format should be named and demonstrated with an additional example.
Expected output:
Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash
Finally: Provide a summary of the language's "append record" capabilities in a table. eg.
Append Capabilities.
Data Representation
IO
Library
Append
Possible
Automatic
Append
Multi-tasking
Safe
In core
On disk
C struct
CSV text file
glibc/stdio
☑
☑
☑ (Not all, eg NFS)
Alternatively: If the language's appends can not guarantee its writes will always append, then note this restriction in the table. If possible, provide an actual code example (possibly using file/record locking) to guarantee correct concurrent appends.
| #Common_Lisp | Common Lisp | (defvar *initial_data*
(list
(list "jsmith" "x" 1001 1000
(list "Joe Smith" "Room 1007" "(234)555-8917" "(234)555-0077" "[email protected]")
"/home/jsmith" "/bin/bash")
(list "jdoe" "x" 1002 1000
(list "Jane Doe" "Room 1004" "(234)555-8914" "(234)555-0044" "[email protected]")
"/home/jdoe" "/bin/bash")))
(defvar *insert*
(list "xyz" "x" 1003 1000
(list "X Yz" "Room 1003" "(234)555-8913" "(234)555-0033" "[email protected]")
"/home/xyz" "/bin/bash"))
(defun serialize (record delim)
(string-right-trim delim ;; Remove trailing delimiter
(reduce (lambda (a b)
(typecase b
(list (concatenate 'string a (serialize b ",") delim))
(t (concatenate 'string a
(typecase b
(integer (write-to-string b))
(t b))
delim))))
record :initial-value "")))
(defun main ()
;; Write initial values to file
(with-open-file (stream "./passwd"
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(loop for x in *initial_data* do
(format stream (concatenate 'string (serialize x ":") "~%"))))
;; Reopen file, append insert value
(with-open-file (stream "./passwd"
:direction :output
:if-exists :append)
(format stream (concatenate 'string (serialize *insert* ":") "~%")))
;; Reopen file, search for new record
(with-open-file (stream "./passwd")
(when stream
(loop for line = (read-line stream nil)
while line do
(if (search "xyz" line)
(format t "Appended record: ~a~%" line))))))
(main)
|
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #APL | APL | ⍝ Create a namespace ("hash")
X←⎕NS ⍬
⍝ Assign some names
X.this←'that'
X.foo←88
⍝ Access the names
X.this
that
⍝ Or do it the array way
X.(foo this)
88 that
⍝ Namespaces are first class objects
sales ← ⎕NS ⍬
sales.(prices quantities) ← (100 98.4 103.4 110.16) (10 12 8 10)
sales.(revenue ← prices +.× quantities)
sales.revenue
4109.6
|
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #Arturo | Arturo | found: 0
i: 1
maxDiv: 0
while [found<20][
fac: size factors i
if fac > maxDiv [
print i
maxDiv: fac
found: found + 1
]
i: i + 1
] |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #AWK | AWK | # syntax: GAWK -f ANTI-PRIMES.AWK
BEGIN {
print("The first 20 anti-primes are:")
while (count < 20) {
d = count_divisors(++n)
if (d > max_divisors) {
printf("%d ",n)
max_divisors = d
count++
}
}
printf("\n")
exit(0)
}
function count_divisors(n, count,i) {
if (n < 2) {
return(1)
}
count = 2
for (i=2; i<=n/2; i++) {
if (n % i == 0) {
count++
}
}
return(count)
} |
http://rosettacode.org/wiki/Atomic_updates | Atomic updates |
Task
Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to:
get the current value of any bucket
remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the 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.
| #Icon_and_Unicon | Icon and Unicon | global mtx
procedure main(A)
nBuckets := integer(A[1]) | 10
nShows := integer(A[2]) | 4
showBuckets := A[3]
mtx := mutex()
every !(buckets := list(nBuckets)) := ?100
thread repeat {
every (b1|b2) := ?nBuckets # OK if same!
critical mtx: xfer((buckets[b1] - buckets[b2])/2, b1, b2)
}
thread repeat {
every (b1|b2) := ?nBuckets # OK if same!
critical mtx: xfer(integer(?buckets[b1]), b1, b2)
}
wait(thread repeat {
delay(500)
critical mtx: {
every (sum := 0) +:= !buckets
writes("Sum: ",sum)
if \showBuckets then every writes(" -> "|right(!buckets, 4))
}
write()
if (nShows -:= 1) <= 0 then break
})
end
procedure xfer(x,b1,b2)
buckets[b1] -:= x
buckets[b2] +:= x
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.
| #FBSL | FBSL | #APPTYPE CONSOLE
DECLARE asserter
FUNCTION Assert(expression)
DIM cmd AS STRING = "DIM asserter AS INTEGER = (" & expression & ")"
EXECLINE(cmd, 1)
IF asserter = 0 THEN PRINT "Assertion: ", expression, " failed"
END FUNCTION
Assert("1<2")
Assert("1>2")
PAUSE |
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.
| #Forth | Forth | variable a
: assert a @ 42 <> throw ;
41 a ! assert |
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.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
' requires compilation with -g switch
Dim a As Integer = 5
Assert(a = 6)
'The rest of the code will not be executed
Print a
Sleep |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #AutoHotkey | AutoHotkey | map("callback", "3,4,5")
callback(array){
Loop, Parse, array, `,
MsgBox % (2 * A_LoopField)
}
map(callback, array){
%callback%(array)
} |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #AWK | AWK | $ awk 'func psqr(x){print x,x*x}BEGIN{split("1 2 3 4 5",a);for(i in a)psqr(a[i])}'
4 16
5 25
1 1
2 4
3 9 |
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
| #Nim | Nim | import tables
proc modes[T](xs: openArray[T]): T =
var count = initCountTable[T]()
for x in xs:
count.inc(x)
largest(count).key
echo modes(@[1,3,6,6,6,6,7,7,12,12,17])
echo modes(@[1,1,2,4,4]) |
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
| #Oberon-2 | Oberon-2 |
MODULE Mode;
IMPORT
Object:Boxed,
ADT:Dictionary,
ADT:LinkedList,
Out := NPCT:Console;
TYPE
Key = Boxed.LongInt;
Val = Boxed.LongInt;
VAR
x: ARRAY 11 OF LONGINT;
y: ARRAY 5 OF LONGINT;
z: ARRAY 8 OF LONGINT;
PROCEDURE Show(ll: LinkedList.LinkedList(Key));
VAR
iter: LinkedList.Iterator(Key);
i: LONGINT;
k: Key;
BEGIN
iter := ll.GetIterator(NIL);
FOR i := 0 TO ll.Size() - 1 DO;
k := iter.Next();
Out.Int(k.value,0);Out.Ln;
END;
END Show;
PROCEDURE Mode(x: ARRAY OF LONGINT): LinkedList.LinkedList(Key);
VAR
d: Dictionary.Dictionary(Key,Val);
i: LONGINT;
k: Key; v: Val;
iter: Dictionary.IterKeys(Key,Val);
resp: LinkedList.LinkedList(Key);
max: Boxed.LongInt;
BEGIN
d := NEW(Dictionary.Dictionary(Key,Val));
FOR i := 0 TO LEN(x) - 1 DO
k := NEW(Key,x[i]);
IF d.Lookup(k,v) THEN
d.Set(k,NEW(Val,v.value + 1));
ELSE
d.Set(k,NEW(Val,1))
END
END;
max := NEW(Boxed.LongInt,0);
resp := NEW(LinkedList.LinkedList(Key));
iter := d.IterKeys();
WHILE (iter.Next(k)) DO
v := d.Get(k);
IF v.Cmp(max) > 0 THEN
resp.Clear();
resp.Append(k);max := v
ELSIF v.Cmp(max) = 0 THEN
resp.Append(k);max := v
END
END;
RETURN resp
END Mode;
BEGIN
x[0] := 1; x[1] := 3; x[2] := 6; x[3] := 6;
x[4] := 6; x[5] := 6; x[6] := 7; x[7] := 7;
x[8] := 12; x[9] := 12; x[10] := 17;
Show(Mode(x));Out.Ln;
y[0] := 1; y[1] := 2; y[2] := 4; y[3] := 4; y[4] := 1;
Show(Mode(y));Out.Ln;
z[0] := 1; z[1] := 2; z[2] := 4; z[3] := 4; z[4] := 1; z[5] := 5; z[6] := 5; z[7] := 5;
Show(Mode(z));Out.Ln;
END Mode.
|
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #C.2B.2B | C++ | #include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> dict {
{"One", 1},
{"Two", 2},
{"Three", 7}
};
dict["Three"] = 3;
std::cout << "One: " << dict["One"] << std::endl;
std::cout << "Key/Value pairs: " << std::endl;
for(auto& kv: dict) {
std::cout << " " << kv.first << ": " << kv.second << std::endl;
}
return 0;
} |
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]
| #Haskell | Haskell | import Data.List (tails)
-- lazy convolution of a list by given kernel
conv :: Num a => [a] -> [a] -> [a]
conv ker = map (dot (reverse ker)) . tails . pad
where
pad v = replicate (length ker - 1) 0 ++ v
dot v = sum . zipWith (*) v
-- The lazy digital filter
dFilter :: [Double] -> [Double] -> [Double] -> [Double]
dFilter (a0:a) b s = tail res
where
res = (/ a0) <$> 0 : zipWith (-) (conv b s) (conv a res) |
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]
| #J | J | Butter=: {{
t=. (#n) +/ .*&(|.n)\(}.n*0),y
A=.|.}.m
for_i.}.i.#y do.
t=. t i}~ (i{t) - (i{.t) +/ .* (-i){.A
end.
t%{.m
}}
sig=: ". rplc&('-_') {{)n
-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
}}-.LF
a=: 1.00000000 _2.77555756e_16 3.33333333e_01 _1.85037171e_17
b=: 0.16666667 0.5 0.5 0.16666667
4 5$ a Butter b sig
_0.152974 _0.435258 _0.136043 0.697503 0.656445
_0.435482 _1.08924 _0.537677 0.51705 1.05225
0.961854 0.69569 0.424356 0.196262 _0.0278351
_0.211722 _0.174746 0.0692584 0.385446 0.651771 |
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
| #CoffeeScript | CoffeeScript |
mean = (array) ->
return 0 if array.length is 0
sum = array.reduce (s,i,0) -> s += i
sum / array.length
alert mean [1]
|
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Common_Lisp | Common Lisp | (defun mean (&rest sequence)
(if (null sequence)
nil
(/ (reduce #'+ sequence) (length sequence)))) |
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
| #PureBasic | PureBasic | NewMap m1.s()
NewMap m2.s()
NewMap m3.s()
m1("name")="Rocket Skates"
m1("price")="12.75"
m1("color")="yellow"
m2("price")="15.25"
m2("color")="red"
m2("year")="1974"
CopyMap(m1(),m3())
ForEach m2()
m3(MapKey(m2()))=m2()
Next
ForEach m3()
Debug MapKey(m3())+" : "+m3()
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
| #Python | Python | base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
result = {**base, **update}
print(result) |
http://rosettacode.org/wiki/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
| #Racket | Racket | #lang racket/base
(require racket/hash)
(module+ test
(require rackunit)
(define base-data (hash "name" "Rocket Skates"
"price" 12.75
"color" "yellow"))
(define update-data (hash "price" 15.25
"color" "red"
"year" 1974))
(hash-union base-data update-data #:combine (λ (a b) b)))
|
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%)
| #PowerShell | PowerShell |
function Get-AnalyticalLoopAverage ( [int]$N )
{
# Expected loop average = sum from i = 1 to N of N! / (N-i)! / N^(N-i+1)
# Equivalently, Expected loop average = sum from i = 1 to N of F(i)
# where F(N) = 1, and F(i) = F(i+1)*i/N
$LoopAverage = $Fi = 1
If ( $N -eq 1 ) { return $LoopAverage }
ForEach ( $i in ($N-1)..1 )
{
$Fi *= $i / $N
$LoopAverage += $Fi
}
return $LoopAverage
}
function Get-ExperimentalLoopAverage ( [int]$N, [int]$Tests = 100000 )
{
If ( $N -eq 1 ) { return 1 }
# Using 0 through N-1 instead of 1 through N for speed and simplicity
$NMO = $N - 1
# Create array to hold mapping function
$F = New-Object int[] ( $N )
$Count = 0
$Random = New-Object System.Random
ForEach ( $Test in 1..$Tests )
{
# Map each number to a random number
ForEach ( $i in 0..$NMO )
{
$F[$i] = $Random.Next( $N )
}
# For each number...
ForEach ( $i in 0..$NMO )
{
# Add the number to the list
$List = @()
$Count++
$List += $X = $i
# If loop does not yet exist in list...
While ( $F[$X] -notin $List )
{
# Go to the next mapped number and add it to the list
$Count++
$List += $X = $F[$X]
}
}
}
$LoopAvereage = $Count / $N / $Tests
return $LoopAvereage
}
|
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
| #Rust | Rust | struct SimpleMovingAverage {
period: usize,
numbers: Vec<usize>
}
impl SimpleMovingAverage {
fn new(p: usize) -> SimpleMovingAverage {
SimpleMovingAverage {
period: p,
numbers: Vec::new()
}
}
fn add_number(&mut self, number: usize) -> f64 {
self.numbers.push(number);
if self.numbers.len() > self.period {
self.numbers.remove(0);
}
if self.numbers.is_empty() {
return 0f64;
}else {
let sum = self.numbers.iter().fold(0, |acc, x| acc+x);
return sum as f64 / self.numbers.len() as f64;
}
}
}
fn main() {
for period in [3, 5].iter() {
println!("Moving average with period {}", period);
let mut sma = SimpleMovingAverage::new(*period);
for i in [1, 2, 3, 4, 5, 5, 4, 3, 2, 1].iter() {
println!("Number: {} | Average: {}", i, sma.add_number(*i));
}
}
} |
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.
| #Java | Java | public class Attractive {
static boolean is_prime(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 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 == 0) {
count++;
n /= f;
if (n == 1) return count;
if (is_prime(n)) f = n;
}
else if (f >= 3) f += 2;
else f = 3;
}
}
public static void main(String[] args) {
final int max = 120;
System.out.printf("The attractive numbers up to and including %d are:\n", max);
for (int i = 1, count = 0; i <= max; ++i) {
int n = count_prime_factors(i);
if (is_prime(n)) {
System.out.printf("%4d", i);
if (++count % 20 == 0) System.out.println();
}
}
System.out.println();
}
} |
http://rosettacode.org/wiki/Averages/Mean_time_of_day | Averages/Mean time of day | Task[edit]
A particular activity of bats occurs at these times of the day:
23:00:17, 23:40:20, 00:12:45, 00:17:19
Using the idea that there are twenty-four hours in a day,
which is analogous to there being 360 degrees in a circle,
map times of day to and from angles;
and using the ideas of Averages/Mean angle
compute and show the average time of the nocturnal activity
to an accuracy of one second of time.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #ooRexx | ooRexx | /* REXX ---------------------------------------------------------------
* 25.06.2014 Walter Pachl
*--------------------------------------------------------------------*/
times='23:00:17 23:40:20 00:12:45 00:17:19'
sum=0
day=86400
x=0
y=0
Do i=1 To words(times) /* loop over times */
time.i=word(times,i) /* pick a time */
alpha.i=t2a(time.i) /* convert to angle (degrees) */
/* Say time.i format(alpha.i,6,9) */
x=x+rxcalcsin(alpha.i) /* accumulate sines */
y=y+rxcalccos(alpha.i) /* accumulate cosines */
End
ww=rxcalcarctan(x/y) /* compute average angle */
ss=ww*86400/360 /* convert to seconds */
If ss<0 Then ss=ss+day /* avoid negative value */
m=ss%60 /* split into hh mm ss */
s=ss-m*60
h=m%60
m=m-h*60
Say f2(h)':'f2(m)':'f2(s) /* show the mean time */
Exit
t2a: Procedure Expose day /* convert time to angle */
Parse Arg hh ':' mm ':' ss
sec=(hh*60+mm)*60+ss
If sec>(day/2) Then
sec=sec-day
a=360*sec/day
Return a
f2: return right(format(arg(1),2,0),2,0)
::requires rxmath library |
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.
| #Python | Python |
# Module: calculus.py
import enum
class entry_not_found(Exception):
"""Raised when an entry is not found in a collection"""
pass
class entry_already_exists(Exception):
"""Raised when an entry already exists in a collection"""
pass
class state(enum.Enum):
header = 0
left_high = 1
right_high = 2
balanced = 3
class direction(enum.Enum):
from_left = 0
from_right = 1
from abc import ABC, abstractmethod
class comparer(ABC):
@abstractmethod
def compare(self,t):
pass
class node(comparer):
def __init__(self):
self.parent = None
self.left = self
self.right = self
self.balance = state.header
def compare(self,t):
if self.key < t:
return -1
elif t < self.key:
return 1
else:
return 0
def is_header(self):
return self.balance == state.header
def length(self):
if self != None:
if self.left != None:
left = self.left.length()
else:
left = 0
if self.right != None:
right = self.right.length()
else:
right = 0
return left + right + 1
else:
return 0
def rotate_left(self):
_parent = self.parent
x = self.right
self.parent = x
x.parent = _parent
if x.left is not None:
x.left.parent = self
self.right = x.left
x.left = self
return x
def rotate_right(self):
_parent = self.parent
x = self.left
self.parent = x
x.parent = _parent;
if x.right is not None:
x.right.parent = self
self.left = x.right
x.right = self
return x
def balance_left(self):
_left = self.left
if _left is None:
return self;
if _left.balance == state.left_high:
self.balance = state.balanced
_left.balance = state.balanced
self = self.rotate_right()
elif _left.balance == state.right_high:
subright = _left.right
if subright.balance == state.balanced:
self.balance = state.balanced
_left.balance = state.balanced
elif subright.balance == state.right_high:
self.balance = state.balanced
_left.balance = state.left_high
elif subright.balance == left_high:
root.balance = state.right_high
_left.balance = state.balanced
subright.balance = state.balanced
_left = _left.rotate_left()
self.left = _left
self = self.rotate_right()
elif _left.balance == state.balanced:
self.balance = state.left_high
_left.balance = state.right_high
self = self.rotate_right()
return self;
def balance_right(self):
_right = self.right
if _right is None:
return self;
if _right.balance == state.right_high:
self.balance = state.balanced
_right.balance = state.balanced
self = self.rotate_left()
elif _right.balance == state.left_high:
subleft = _right.left;
if subleft.balance == state.balanced:
self.balance = state.balanced
_right.balance = state.balanced
elif subleft.balance == state.left_high:
self.balance = state.balanced
_right.balance = state.right_high
elif subleft.balance == state.right_high:
self.balance = state.left_high
_right.balance = state.balanced
subleft.balance = state.balanced
_right = _right.rotate_right()
self.right = _right
self = self.rotate_left()
elif _right.balance == state.balanced:
self.balance = state.right_high
_right.balance = state.left_high
self = self.rotate_left()
return self
def balance_tree(self, direct):
taller = True
while taller:
_parent = self.parent;
if _parent.left == self:
next_from = direction.from_left
else:
next_from = direction.from_right;
if direct == direction.from_left:
if self.balance == state.left_high:
if _parent.is_header():
_parent.parent = _parent.parent.balance_left()
elif _parent.left == self:
_parent.left = _parent.left.balance_left()
else:
_parent.right = _parent.right.balance_left()
taller = False
elif self.balance == state.balanced:
self.balance = state.left_high
taller = True
elif self.balance == state.right_high:
self.balance = state.balanced
taller = False
else:
if self.balance == state.left_high:
self.balance = state.balanced
taller = False
elif self.balance == state.balanced:
self.balance = state.right_high
taller = True
elif self.balance == state.right_high:
if _parent.is_header():
_parent.parent = _parent.parent.balance_right()
elif _parent.left == self:
_parent.left = _parent.left.balance_right()
else:
_parent.right = _parent.right.balance_right()
taller = False
if taller:
if _parent.is_header():
taller = False
else:
self = _parent
direct = next_from
def balance_tree_remove(self, _from):
if self.is_header():
return;
shorter = True;
while shorter:
_parent = self.parent;
if _parent.left == self:
next_from = direction.from_left
else:
next_from = direction.from_right
if _from == direction.from_left:
if self.balance == state.left_high:
shorter = True
elif self.balance == state.balanced:
self.balance = state.right_high;
shorter = False
elif self.balance == state.right_high:
if self.right is not None:
if self.right.balance == state.balanced:
shorter = False
else:
shorter = True
else:
shorter = False;
if _parent.is_header():
_parent.parent = _parent.parent.balance_right()
elif _parent.left == self:
_parent.left = _parent.left.balance_right();
else:
_parent.right = _parent.right.balance_right()
else:
if self.balance == state.right_high:
self.balance = state.balanced
shorter = True
elif self.balance == state.balanced:
self.balance = state.left_high
shorter = False
elif self.balance == state.left_high:
if self.left is not None:
if self.left.balance == state.balanced:
shorter = False
else:
shorter = True
else:
short = False;
if _parent.is_header():
_parent.parent = _parent.parent.balance_left();
elif _parent.left == self:
_parent.left = _parent.left.balance_left();
else:
_parent.right = _parent.right.balance_left();
if shorter:
if _parent.is_header():
shorter = False
else:
_from = next_from
self = _parent
def previous(self):
if self.is_header():
return self.right
if self.left is not None:
y = self.left
while y.right is not None:
y = y.right
return y
else:
y = self.parent;
if y.is_header():
return y
x = self
while x == y.left:
x = y
y = y.parent
return y
def next(self):
if self.is_header():
return self.left
if self.right is not None:
y = self.right
while y.left is not None:
y = y.left
return y;
else:
y = self.parent
if y.is_header():
return y
x = self;
while x == y.right:
x = y
y = y.parent;
return y
def swap_nodes(a, b):
if b == a.left:
if b.left is not None:
b.left.parent = a
if b.right is not None:
b.right.parent = a
if a.right is not None:
a.right.parent = b
if not a.parent.is_header():
if a.parent.left == a:
a.parent.left = b
else:
a.parent.right = b;
else:
a.parent.parent = b
b.parent = a.parent
a.parent = b
a.left = b.left
b.left = a
temp = a.right
a.right = b.right
b.right = temp
elif b == a.right:
if b.right is not None:
b.right.parent = a
if b.left is not None:
b.left.parent = a
if a.left is not None:
a.left.parent = b
if not a.parent.is_header():
if a.parent.left == a:
a.parent.left = b
else:
a.parent.right = b
else:
a.parent.parent = b
b.parent = a.parent
a.parent = b
a.right = b.right
b.right = a
temp = a.left
a.left = b.left
b.left = temp
elif a == b.left:
if a.left is not None:
a.left.parent = b
if a.right is not None:
a.right.parent = b
if b.right is not None:
b.right.parent = a
if not parent.is_header():
if b.parent.left == b:
b.parent.left = a
else:
b.parent.right = a
else:
b.parent.parent = a
a.parent = b.parent
b.parent = a
b.left = a.left
a.left = b
temp = a.right
a.right = b.right
b.right = temp
elif a == b.right:
if a.right is not None:
a.right.parent = b
if a.left is not None:
a.left.parent = b
if b.left is not None:
b.left.parent = a
if not b.parent.is_header():
if b.parent.left == b:
b.parent.left = a
else:
b.parent.right = a
else:
b.parent.parent = a
a.parent = b.parent
b.parent = a
b.right = a.right
a.right = b
temp = a.left
a.left = b.left
b.left = temp
else:
if a.parent == b.parent:
temp = a.parent.left
a.parent.left = a.parent.right
a.parent.right = temp
else:
if not a.parent.is_header():
if a.parent.left == a:
a.parent.left = b
else:
a.parent.right = b
else:
a.parent.parent = b
if not b.parent.is_header():
if b.parent.left == b:
b.parent.left = a
else:
b.parent.right = a
else:
b.parent.parent = a
if b.left is not None:
b.left.parent = a
if b.right is not None:
b.right.parent = a
if a.left is not None:
a.left.parent = b
if a.right is not None:
a.right.parent = b
temp1 = a.left
a.left = b.left
b.left = temp1
temp2 = a.right
a.right = b.right
b.right = temp2
temp3 = a.parent
a.parent = b.parent
b.parent = temp3
balance = a.balance
a.balance = b.balance
b.balance = balance
class parent_node(node):
def __init__(self, parent):
self.parent = parent
self.left = None
self.right = None
self.balance = state.balanced
class set_node(node):
def __init__(self, parent, key):
self.parent = parent
self.left = None
self.right = None
self.balance = state.balanced
self.key = key
class ordered_set:
def __init__(self):
self.header = node()
def __iter__(self):
self.node = self.header
return self
def __next__(self):
self.node = self.node.next()
if self.node.is_header():
raise StopIteration
return self.node.key
def __delitem__(self, key):
self.remove(key)
def __lt__(self, other):
first1 = self.header.left
last1 = self.header
first2 = other.header.left
last2 = other.header
while (first1 != last1) and (first2 != last2):
l = first1.key < first2.key
if not l:
first1 = first1.next();
first2 = first2.next();
else:
return True;
a = self.__len__()
b = other.__len__()
return a < b
def __hash__(self):
h = 0
for i in self:
h = h + i.__hash__()
return h
def __eq__(self, other):
if self < other:
return False
if other < self:
return False
return True
def __ne__(self, other):
if self < other:
return True
if other < self:
return True
return False
def __len__(self):
return self.header.parent.length()
def __getitem__(self, key):
return self.contains(key)
def __str__(self):
l = self.header.right
s = "{"
i = self.header.left
h = self.header
while i != h:
s = s + i.key.__str__()
if i != l:
s = s + ","
i = i.next()
s = s + "}"
return s
def __or__(self, other):
r = ordered_set()
first1 = self.header.left
last1 = self.header
first2 = other.header.left
last2 = other.header
while first1 != last1 and first2 != last2:
les = first1.key < first2.key
graater = first2.key < first1.key
if les:
r.add(first1.key)
first1 = first1.next()
elif graater:
r.add(first2.key)
first2 = first2.next()
else:
r.add(first1.key)
first1 = first1.next()
first2 = first2.next()
while first1 != last1:
r.add(first1.key)
first1 = first1.next()
while first2 != last2:
r.add(first2.key)
first2 = first2.next()
return r
def __and__(self, other):
r = ordered_set()
first1 = self.header.left
last1 = self.header
first2 = other.header.left
last2 = other.header
while first1 != last1 and first2 != last2:
les = first1.key < first2.key
graater = first2.key < first1.key
if les:
first1 = first1.next()
elif graater:
first2 = first2.next()
else:
r.add(first1.key)
first1 = first1.next()
first2 = first2.next()
return r
def __xor__(self, other):
r = ordered_set()
first1 = self.header.left
last1 = self.header
first2 = other.header.left
last2 = other.header
while first1 != last1 and first2 != last2:
les = first1.key < first2.key
graater = first2.key < first1.key
if les:
r.add(first1.key)
first1 = first1.next()
elif graater:
r.add(first2.key)
first2 = first2.next()
else:
first1 = first1.next()
first2 = first2.next()
while first1 != last1:
r.add(first1.key)
first1 = first1.next()
while first2 != last2:
r.add(first2.key)
first2 = first2.next()
return r
def __sub__(self, other):
r = ordered_set()
first1 = self.header.left
last1 = self.header
first2 = other.header.left
last2 = other.header
while first1 != last1 and first2 != last2:
les = first1.key < first2.key
graater = first2.key < first1.key
if les:
r.add(first1.key)
first1 = first1.next()
elif graater:
r.add(first2.key)
first2 = first2.next()
else:
first1 = first1.next()
first2 = first2.next()
while first1 != last1:
r.add(first1.key)
first1 = first1.next()
return r
def __lshift__(self, data):
self.add(data)
return self
def __rshift__(self, data):
self.remove(data)
return self
def is_subset(self, other):
first1 = self.header.left
last1 = self.header
first2 = other.header.left
last2 = other.header
is_subet = True
while first1 != last1 and first2 != last2:
if first1.key < first2.key:
is_subset = False
break
elif first2.key < first1.key:
first2 = first2.next()
else:
first1 = first1.next()
first2 = first2.next()
if is_subet:
if first1 != last1:
is_subet = False
return is_subet
def is_superset(self,other):
return other.is_subset(self)
def add(self, data):
if self.header.parent is None:
self.header.parent = set_node(self.header,data)
self.header.left = self.header.parent
self.header.right = self.header.parent
else:
root = self.header.parent
while True:
c = root.compare(data)
if c >= 0:
if root.left is not None:
root = root.left
else:
new_node = set_node(root,data)
root.left = new_node
if self.header.left == root:
self.header.left = new_node
root.balance_tree(direction.from_left)
return
else:
if root.right is not None:
root = root.right
else:
new_node = set_node(root, data)
root.right = new_node
if self.header.right == root:
self.header.right = new_node
root.balance_tree(direction.from_right)
return
def remove(self,data):
root = self.header.parent;
while True:
if root is None:
raise entry_not_found("Entry not found in collection")
c = root.compare(data)
if c < 0:
root = root.left;
elif c > 0:
root = root.right;
else:
if root.left is not None:
if root.right is not None:
replace = root.left
while replace.right is not None:
replace = replace.right
root.swap_nodes(replace)
_parent = root.parent
if _parent.left == root:
_from = direction.from_left
else:
_from = direction.from_right
if self.header.left == root:
n = root.next();
if n.is_header():
self.header.left = self.header
self.header.right = self.header
else:
self.header.left = n
elif self.header.right == root:
p = root.previous();
if p.is_header():
self.header.left = self.header
self.header.right = self.header
else:
self.header.right = p
if root.left is None:
if _parent == self.header:
self.header.parent = root.right
elif _parent.left == root:
_parent.left = root.right
else:
_parent.right = root.right
if root.right is not None:
root.right.parent = _parent
else:
if _parent == self.header:
self.header.parent = root.left
elif _parent.left == root:
_parent.left = root.left
else:
_parent.right = root.left
if root.left is not None:
root.left.parent = _parent;
_parent.balance_tree_remove(_from)
return
def contains(self,data):
root = self.header.parent;
while True:
if root == None:
return False
c = root.compare(data);
if c > 0:
root = root.left;
elif c < 0:
root = root.right;
else:
return True
def find(self,data):
root = self.header.parent;
while True:
if root == None:
raise entry_not_found("An entry is not found in a collection")
c = root.compare(data);
if c > 0:
root = root.left;
elif c < 0:
root = root.right;
else:
return root.key;
class key_value(comparer):
def __init__(self, key, value):
self.key = key
self.value = value
def compare(self,kv):
if self.key < kv.key:
return -1
elif kv.key < self.key:
return 1
else:
return 0
def __lt__(self, other):
return self.key < other.key
def __str__(self):
return '(' + self.key.__str__() + ',' + self.value.__str__() + ')'
def __eq__(self, other):
return self.key == other.key
def __hash__(self):
return hash(self.key)
class dictionary:
def __init__(self):
self.set = ordered_set()
return None
def __lt__(self, other):
if self.keys() < other.keys():
return true
if other.keys() < self.keys():
return false
first1 = self.set.header.left
last1 = self.set.header
first2 = other.set.header.left
last2 = other.set.header
while (first1 != last1) and (first2 != last2):
l = first1.key.value < first2.key.value
if not l:
first1 = first1.next();
first2 = first2.next();
else:
return True;
a = self.__len__()
b = other.__len__()
return a < b
def add(self, key, value):
try:
self.set.remove(key_value(key,None))
except entry_not_found:
pass
self.set.add(key_value(key,value))
return
def remove(self, key):
self.set.remove(key_value(key,None))
return
def clear(self):
self.set.header = node()
def sort(self):
sort_bag = bag()
for e in self:
sort_bag.add(e.value)
keys_set = self.keys()
self.clear()
i = sort_bag.__iter__()
i = sort_bag.__next__()
try:
for e in keys_set:
self.add(e,i)
i = sort_bag.__next__()
except:
return
def keys(self):
keys_set = ordered_set()
for e in self:
keys_set.add(e.key)
return keys_set
def __len__(self):
return self.set.header.parent.length()
def __str__(self):
l = self.set.header.right;
s = "{"
i = self.set.header.left;
h = self.set.header;
while i != h:
s = s + "("
s = s + i.key.key.__str__()
s = s + ","
s = s + i.key.value.__str__()
s = s + ")"
if i != l:
s = s + ","
i = i.next()
s = s + "}"
return s;
def __iter__(self):
self.set.node = self.set.header
return self
def __next__(self):
self.set.node = self.set.node.next()
if self.set.node.is_header():
raise StopIteration
return key_value(self.set.node.key.key,self.set.node.key.value)
def __getitem__(self, key):
kv = self.set.find(key_value(key,None))
return kv.value
def __setitem__(self, key, value):
self.add(key,value)
return
def __delitem__(self, key):
self.set.remove(key_value(key,None))
class array:
def __init__(self):
self.dictionary = dictionary()
return None
def __len__(self):
return self.dictionary.__len__()
def push(self, value):
k = self.dictionary.set.header.right
if k == self.dictionary.set.header:
self.dictionary.add(0,value)
else:
self.dictionary.add(k.key.key+1,value)
return
def pop(self):
if self.dictionary.set.header.parent != None:
data = self.dictionary.set.header.right.key.value
self.remove(self.dictionary.set.header.right.key.key)
return data
def add(self, key, value):
try:
self.dictionary.remove(key)
except entry_not_found:
pass
self.dictionary.add(key,value)
return
def remove(self, key):
self.dictionary.remove(key)
return
def sort(self):
self.dictionary.sort()
def clear(self):
self.dictionary.header = node();
def __iter__(self):
self.dictionary.node = self.dictionary.set.header
return self
def __next__(self):
self.dictionary.node = self.dictionary.node.next()
if self.dictionary.node.is_header():
raise StopIteration
return self.dictionary.node.key.value
def __getitem__(self, key):
kv = self.dictionary.set.find(key_value(key,None))
return kv.value
def __setitem__(self, key, value):
self.add(key,value)
return
def __delitem__(self, key):
self.dictionary.remove(key)
def __lshift__(self, data):
self.push(data)
return self
def __lt__(self, other):
return self.dictionary < other.dictionary
def __str__(self):
l = self.dictionary.set.header.right;
s = "{"
i = self.dictionary.set.header.left;
h = self.dictionary.set.header;
while i != h:
s = s + i.key.value.__str__()
if i != l:
s = s + ","
i = i.next()
s = s + "}"
return s;
class bag:
def __init__(self):
self.header = node()
def __iter__(self):
self.node = self.header
return self
def __delitem__(self, key):
self.remove(key)
def __next__(self):
self.node = self.node.next()
if self.node.is_header():
raise StopIteration
return self.node.key
def __str__(self):
l = self.header.right;
s = "("
i = self.header.left;
h = self.header;
while i != h:
s = s + i.key.__str__()
if i != l:
s = s + ","
i = i.next()
s = s + ")"
return s;
def __len__(self):
return self.header.parent.length()
def __lshift__(self, data):
self.add(data)
return self
def add(self, data):
if self.header.parent is None:
self.header.parent = set_node(self.header,data)
self.header.left = self.header.parent
self.header.right = self.header.parent
else:
root = self.header.parent
while True:
c = root.compare(data)
if c >= 0:
if root.left is not None:
root = root.left
else:
new_node = set_node(root,data)
root.left = new_node
if self.header.left == root:
self.header.left = new_node
root.balance_tree(direction.from_left)
return
else:
if root.right is not None:
root = root.right
else:
new_node = set_node(root, data)
root.right = new_node
if self.header.right == root:
self.header.right = new_node
root.balance_tree(direction.from_right)
return
def remove_first(self,data):
root = self.header.parent;
while True:
if root is None:
return False;
c = root.compare(data);
if c > 0:
root = root.left;
elif c < 0:
root = root.right;
else:
if root.left is not None:
if root.right is not None:
replace = root.left;
while replace.right is not None:
replace = replace.right;
root.swap_nodes(replace);
_parent = root.parent
if _parent.left == root:
_from = direction.from_left
else:
_from = direction.from_right
if self.header.left == root:
n = root.next();
if n.is_header():
self.header.left = self.header
self.header.right = self.header
else:
self.header.left = n;
elif self.header.right == root:
p = root.previous();
if p.is_header():
self.header.left = self.header
self.header.right = self.header
else:
self.header.right = p
if root.left is None:
if _parent == self.header:
self.header.parent = root.right
elif _parent.left == root:
_parent.left = root.right
else:
_parent.right = root.right
if root.right is not None:
root.right.parent = _parent
else:
if _parent == self.header:
self.header.parent = root.left
elif _parent.left == root:
_parent.left = root.left
else:
_parent.right = root.left
if root.left is not None:
root.left.parent = _parent;
_parent.balance_tree_remove(_from)
return True;
def remove(self,data):
success = self.remove_first(data)
while success:
success = self.remove_first(data)
def remove_node(self, root):
if root.left != None and root.right != None:
replace = root.left
while replace.right != None:
replace = replace.right
root.swap_nodes(replace)
parent = root.parent;
if parent.left == root:
next_from = direction.from_left
else:
next_from = direction.from_right
if self.header.left == root:
n = root.next()
if n.is_header():
self.header.left = self.header;
self.header.right = self.header
else:
self.header.left = n
elif self.header.right == root:
p = root.previous()
if p.is_header():
root.header.left = root.header
root.header.right = header
else:
self.header.right = p
if root.left == None:
if parent == self.header:
self.header.parent = root.right
elif parent.left == root:
parent.left = root.right
else:
parent.right = root.right
if root.right != None:
root.right.parent = parent
else:
if parent == self.header:
self.header.parent = root.left
elif parent.left == root:
parent.left = root.left
else:
parent.right = root.left
if root.left != None:
root.left.parent = parent;
parent.balance_tree_remove(next_from)
def remove_at(self, data, ophset):
p = self.search(data);
if p == None:
return
else:
lower = p
after = after(data)
s = 0
while True:
if ophset == s:
remove_node(lower);
return;
lower = lower.next_node()
if after == lower:
break
s = s+1
return
def search(self, key):
s = before(key)
s.next()
if s.is_header():
return None
c = s.compare(s.key)
if c != 0:
return None
return s
def before(self, data):
y = self.header;
x = self.header.parent;
while x != None:
if x.compare(data) >= 0:
x = x.left;
else:
y = x;
x = x.right;
return y
def after(self, data):
y = self.header;
x = self.header.parent;
while x != None:
if x.compare(data) > 0:
y = x
x = x.left
else:
x = x.right
return y;
def find(self,data):
root = self.header.parent;
results = array()
while True:
if root is None:
break;
p = self.before(data)
p = p.next()
if not p.is_header():
i = p
l = self.after(data)
while i != l:
results.push(i.key)
i = i.next()
return results
else:
break;
return results
class bag_dictionary:
def __init__(self):
self.bag = bag()
return None
def add(self, key, value):
self.bag.add(key_value(key,value))
return
def remove(self, key):
self.bag.remove(key_value(key,None))
return
def remove_at(self, key, index):
self.bag.remove_at(key_value(key,None), index)
return
def clear(self):
self.bag.header = node()
def __len__(self):
return self.bag.header.parent.length()
def __str__(self):
l = self.bag.header.right;
s = "{"
i = self.bag.header.left;
h = self.bag.header;
while i != h:
s = s + "("
s = s + i.key.key.__str__()
s = s + ","
s = s + i.key.value.__str__()
s = s + ")"
if i != l:
s = s + ","
i = i.next()
s = s + "}"
return s;
def __iter__(self):
self.bag.node = self.bag.header
return self
def __next__(self):
self.bag.node = self.bag.node.next()
if self.bag.node.is_header():
raise StopIteration
return key_value(self.bag.node.key.key,self.bag.node.key.value)
def __getitem__(self, key):
kv_array = self.bag.find(key_value(key,None))
return kv_array
def __setitem__(self, key, value):
self.add(key,value)
return
def __delitem__(self, key):
self.bag.remove(key_value(key,None))
class unordered_set:
def __init__(self):
self.bag_dictionary = bag_dictionary()
def __len__(self):
return self.bag_dictionary.__len__()
def __hash__(self):
h = 0
for i in self:
h = h + i.__hash__()
return h
def __eq__(self, other):
for t in self:
if not other.contains(t):
return False
for u in other:
if self.contains(u):
return False
return true;
def __ne__(self, other):
return not self == other
def __or__(self, other):
r = unordered_set()
for t in self:
r.add(t);
for u in other:
if not self.contains(u):
r.add(u);
return r
def __and__(self, other):
r = unordered_set()
for t in self:
if other.contains(t):
r.add(t)
for u in other:
if self.contains(u) and not r.contains(u):
r.add(u);
return r
def __xor__(self, other):
r = unordered_set()
for t in self:
if not other.contains(t):
r.add(t)
for u in other:
if not self.contains(u) and not r.contains(u):
r.add(u)
return r
def __sub__(self, other):
r = ordered_set()
for t in self:
if not other.contains(t):
r.add(t);
return r
def __lshift__(self, data):
self.add(data)
return self
def __rshift__(self, data):
self.remove(data)
return self
def __getitem__(self, key):
return self.contains(key)
def is_subset(self, other):
is_subet = True
for t in self:
if not other.contains(t):
subset = False
break
return is_subet
def is_superset(self,other):
return other.is_subset(self)
def add(self, value):
if not self.contains(value):
self.bag_dictionary.add(hash(value),value)
else:
raise entry_already_exists("Entry already exists in the unordered set")
def contains(self, data):
if self.bag_dictionary.bag.header.parent == None:
return False;
else:
index = hash(data);
_search = self.bag_dictionary.bag.header.parent;
search_index = _search.key.key;
if index < search_index:
_search = _search.left
elif index > search_index:
_search = _search.right
if _search == None:
return False
while _search != None:
search_index = _search.key.key;
if index < search_index:
_search = _search.left
elif index > search_index:
_search = _search.right
else:
break
if _search == None:
return False
return self.contains_node(data, _search)
def contains_node(self,data,_node):
previous = _node.previous()
save = _node
while not previous.is_header() and previous.key.key == _node.key.key:
save = previous;
previous = previous.previous()
c = _node.key.value
_node = save
if c == data:
return True
next = _node.next()
while not next.is_header() and next.key.key == _node.key.key:
_node = next
c = _node.key.value
if c == data:
return True;
next = _node.next()
return False;
def find(self,data,_node):
previous = _node.previous()
save = _node
while not previous.is_header() and previous.key.key == _node.key.key:
save = previous;
previous = previous.previous();
_node = save;
c = _node.key.value
if c == data:
return _node
next = _node.next()
while not next.is_header() and next.key.key == _node.key.key:
_node = next
c = _node.data.value
if c == data:
return _node
next = _node.next()
return None
def search(self, data):
if self.bag_dictionary.bag.header.parent == None:
return None
else:
index = hash(data)
_search = self.bag_dictionary.bag.header.parent
c = _search.key.key
if index < c:
_search = _search.left;
elif index > c:
_search = _search.right;
while _search != None:
if index != c:
break
c = _search.key.key
if index < c:
_search = _search.left;
elif index > c:
_search = _search.right;
else:
break
if _search == None:
return None
return self.find(data, _search)
def remove(self,data):
found = self.search(data);
if found != None:
self.bag_dictionary.bag.remove_node(found);
else:
raise entry_not_found("Entry not found in the unordered set")
def clear(self):
self.bag_dictionary.bag.header = node()
def __str__(self):
l = self.bag_dictionary.bag.header.right;
s = "{"
i = self.bag_dictionary.bag.header.left;
h = self.bag_dictionary.bag.header;
while i != h:
s = s + i.key.value.__str__()
if i != l:
s = s + ","
i = i.next()
s = s + "}"
return s;
def __iter__(self):
self.bag_dictionary.bag.node = self.bag_dictionary.bag.header
return self
def __next__(self):
self.bag_dictionary.bag.node = self.bag_dictionary.bag.node.next()
if self.bag_dictionary.bag.node.is_header():
raise StopIteration
return self.bag_dictionary.bag.node.key.value
class map:
def __init__(self):
self.set = unordered_set()
return None
def __len__(self):
return self.set.__len__()
def add(self, key, value):
try:
self.set.remove(key_value(key,None))
except entry_not_found:
pass
self.set.add(key_value(key,value))
return
def remove(self, key):
self.set.remove(key_value(key,None))
return
def clear(self):
self.set.clear()
def __str__(self):
l = self.set.bag_dictionary.bag.header.right;
s = "{"
i = self.set.bag_dictionary.bag.header.left;
h = self.set.bag_dictionary.bag.header;
while i != h:
s = s + "("
s = s + i.key.value.key.__str__()
s = s + ","
s = s + i.key.value.value.__str__()
s = s + ")"
if i != l:
s = s + ","
i = i.next()
s = s + "}"
return s;
def __iter__(self):
self.set.node = self.set.bag_dictionary.bag.header
return self
def __next__(self):
self.set.node = self.set.node.next()
if self.set.node.is_header():
raise StopIteration
return key_value(self.set.node.key.key,self.set.node.key.value)
def __getitem__(self, key):
kv = self.set.find(key_value(key,None))
return kv.value
def __setitem__(self, key, value):
self.add(key,value)
return
def __delitem__(self, key):
self.remove(key)
|
http://rosettacode.org/wiki/Averages/Mean_angle | Averages/Mean angle | When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle.
If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the second was of 10 degrees then the average of the numbers is 180 degrees, whereas if you can note that 350 degrees is equivalent to -10 degrees and so you have two readings at 10 degrees either side of zero degrees leading to a more fitting mean angle of zero degrees.
To calculate the mean angle of several angles:
Assume all angles are on the unit circle and convert them to complex numbers expressed in real and imaginary form.
Compute the mean of the complex numbers.
Convert the complex mean to polar coordinates whereupon the phase of the complex mean is the required angular mean.
(Note that, since the mean is the sum divided by the number of numbers, and division by a positive real number does not affect the angle, you can also simply compute the sum for step 2.)
You can alternatively use this formula:
Given the angles
α
1
,
…
,
α
n
{\displaystyle \alpha _{1},\dots ,\alpha _{n}}
the mean is computed by
α
¯
=
atan2
(
1
n
⋅
∑
j
=
1
n
sin
α
j
,
1
n
⋅
∑
j
=
1
n
cos
α
j
)
{\displaystyle {\bar {\alpha }}=\operatorname {atan2} \left({\frac {1}{n}}\cdot \sum _{j=1}^{n}\sin \alpha _{j},{\frac {1}{n}}\cdot \sum _{j=1}^{n}\cos \alpha _{j}\right)}
Task[edit]
write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle.
(You should use a built-in function if you have one that does this for degrees or radians).
Use the function to compute the means of these lists of angles (in degrees):
[350, 10]
[90, 180, 270, 360]
[10, 20, 30]
Show your output here.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Nim | Nim | import math, complex
proc meanAngle(deg: openArray[float]): float =
var c: Complex[float]
for d in deg:
c += rect(1.0, degToRad(d))
radToDeg(phase(c / float(deg.len)))
echo "The 1st mean angle is: ", meanAngle([350.0, 10.0]), " degrees"
echo "The 2nd mean angle is: ", meanAngle([90.0, 180.0, 270.0, 360.0]), " degrees"
echo "The 3rd mean angle is: ", meanAngle([10.0, 20.0, 30.0]), " degrees" |
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
| #Oberon-2 | Oberon-2 |
MODULE MeanAngle;
IMPORT
M := LRealMath,
Out;
CONST
toRads = M.pi / 180;
toDegs = 180 / M.pi;
VAR
grades: ARRAY 64 OF LONGREAL;
PROCEDURE Mean(g: ARRAY OF LONGREAL): LONGREAL;
VAR
i: INTEGER;
sumSin, sumCos: LONGREAL;
BEGIN
i := 0;sumSin := 0.0;sumCos := 0.0;
WHILE g[i] # 0.0 DO
sumSin := sumSin + M.sin(g[i] * toRads);
sumCos := sumCos + M.cos(g[i] * toRads);
INC(i)
END;
RETURN M.arctan2(sumSin / i,sumCos / i);
END Mean;
BEGIN
grades[0] := 350.0;grades[1] := 10.0;
Out.LongRealFix(Mean(grades) * toDegs,15,9);Out.Ln;
grades[0] := 90.0;grades[1] := 180.0;grades[2] := 270.0;grades[3] := 360.0;
Out.LongRealFix(Mean(grades) * toDegs,15,9);Out.Ln;
grades[0] := 10.0;grades[1] := 20.0;grades[2] := 30.0;grades[3] := 0.0;
Out.LongRealFix(Mean(grades) * toDegs,15,9);Out.Ln;
END MeanAngle.
|
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches to this. One is to sort the elements, and then pick the element(s) in the middle.
Sorting would take at least O(n logn). Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s). This would also take O(n logn). The best solution is to use the selection algorithm to find the median in O(n) time.
See also
Quickselect_algorithm
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Euphoria | Euphoria | function median(sequence s)
atom min,k
-- Selection sort of half+1
for i = 1 to length(s)/2+1 do
min = s[i]
k = 0
for j = i+1 to length(s) do
if s[j] < min then
min = s[j]
k = j
end if
end for
if k then
s[k] = s[i]
s[i] = min
end if
end for
if remainder(length(s),2) = 0 then
return (s[$/2]+s[$/2+1])/2
else
return s[$/2+1]
end if
end function
? median({ 4.4, 2.3, -1.7, 7.5, 6.6, 0.0, 1.9, 8.2, 9.3, 4.5 }) |
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
| #JavaScript | JavaScript | (function () {
'use strict';
// arithmetic_mean :: [Number] -> Number
function arithmetic_mean(ns) {
return (
ns.reduce( // sum
function (sum, n) {
return (sum + n);
},
0
) / ns.length
);
}
// geometric_mean :: [Number] -> Number
function geometric_mean(ns) {
return Math.pow(
ns.reduce( // product
function (product, n) {
return (product * n);
},
1
),
1 / ns.length
);
}
// harmonic_mean :: [Number] -> Number
function harmonic_mean(ns) {
return (
ns.length / ns.reduce( // sum of inverses
function (invSum, n) {
return (invSum + (1 / n));
},
0
)
);
}
var values = [arithmetic_mean, geometric_mean, harmonic_mean]
.map(function (f) {
return f([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
}),
mean = {
Arithmetic: values[0], // arithmetic
Geometric: values[1], // geometric
Harmonic: values[2] // harmonic
}
return JSON.stringify({
values: mean,
test: "is A >= G >= H ? " +
(
mean.Arithmetic >= mean.Geometric &&
mean.Geometric >= mean.Harmonic ? "yes" : "no"
)
}, null, 2);
})();
|
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.
| #Prolog | Prolog | :- module('bt_convert.pl', [bt_convert/2,
op(950, xfx, btconv),
btconv/2]).
:- use_module(library(clpfd)).
:- op(950, xfx, btconv).
X btconv Y :-
bt_convert(X, Y).
% bt_convert(?X, ?L)
bt_convert(X, L) :-
( (nonvar(L), \+is_list(L)) ->string_to_list(L, L1); L1 = L),
convert(X, L1),
( var(L) -> string_to_list(L, L1); true).
% map numbers toward digits +, - 0
plus_moins( 1, 43).
plus_moins(-1, 45).
plus_moins( 0, 48).
convert(X, [48| L]) :-
var(X),
( L \= [] -> convert(X, L); X = 0, !).
convert(0, L) :-
var(L), !, string_to_list(L, [48]).
convert(X, L) :-
( (nonvar(X), X > 0)
; (var(X), X #> 0,
L = [43|_],
maplist(plus_moins, L1, L))),
!,
convert(X, 0, [], L1),
( nonvar(X) -> maplist(plus_moins, L1, LL), string_to_list(L, LL)
; true).
convert(X, L) :-
( nonvar(X) -> Y is -X
; X #< 0,
maplist(plus_moins, L2, L),
maplist(mult(-1), L2, L1)),
convert(Y, 0, [], L1),
( nonvar(X) ->
maplist(mult(-1), L1, L2),
maplist(plus_moins, L2, LL),
string_to_list(L, LL)
; X #= -Y).
mult(X, Y, Z) :-
Z #= X * Y.
convert(0, 0, L, L) :- !.
convert(0, 1, L, [1 | L]) :- !.
convert(N, C, LC, LF) :-
R #= N mod 3 + C,
R #> 1 #<==> C1,
N1 #= N / 3,
R1 #= R - 3 * C1, % C1 #= 1,
convert(N1, C1, [R1 | LC], LF).
|
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.
| #Racket | Racket | ;; Text from a semicolon to the end of a line is ignored
;; This lets the racket engine know it is running racket
#lang racket
;; “define” defines a function in the engine
;; we can use an English name for the function
;; a number ends in 269696 when its remainder when
;; divided by 1000000 is 269696 (we omit commas in
;; numbers... they are used for another reason).
(define (ends-in-269696? x)
(= (remainder x 1000000) 269696))
;; we now define another function square-ends-in-269696?
;; actually this is the composition of ends-in-269696? and
;; the squaring function (which is called “sqr” in racket)
(define square-ends-in-269696? (compose ends-in-269696? sqr))
;; a for loop lets us iterate (it’s a long Latin word which
;; Victorians are good at using) over a number range.
;;
;; for/first go through the range and break when it gets to
;; the first true value
;;
;; (in-range a b) produces all of the integers from a (inclusive)
;; to b (exclusive). Because we know that 99736² ends in 269696,
;; we will stop there. The add1 is to make in-range include 99736
;;
;; we define a new variable, so that we can test the verity of
;; our result
(define first-number-that-when-squared-ends-in-269696
(for/first ((i ; “i” will become the ubiquetous looping variable of the future!
(in-range 1 (add1 99736)))
; when returns when only the first one that matches
#:when (square-ends-in-269696? i))
i))
;; display prints values out; newline writes a new line (otherwise everything
;; gets stuck together)
(display first-number-that-when-squared-ends-in-269696)
(newline)
(display (sqr first-number-that-when-squared-ends-in-269696))
(newline)
(newline)
(display (ends-in-269696? (sqr first-number-that-when-squared-ends-in-269696)))
(newline)
(display (square-ends-in-269696? first-number-that-when-squared-ends-in-269696))
(newline)
;; that all seems satisfactory |
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.
| #Raku | Raku | # For all positives integers from 1 to Infinity
for 1 .. Inf -> $integer {
# calculate the square of the integer
my $square = $integer²;
# print the integer and square and exit if the square modulo 1000000 is equal to 269696
print "{$integer}² equals $square" and exit if $square mod 1000000 == 269696;
} |
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.
| #Pascal | Pascal | program approximateEqual(output);
{
\brief determines whether two `real` values are approximately equal
\param x a reference value
\param y the value to compare with \param x
\return true if \param x is equal or approximately equal to \param y
}
function equal(protected x, y: real): Boolean;
function approximate: Boolean;
function d(protected x: real): integer;
begin
d := trunc(ln(abs(x) + minReal) / ln(2)) + 1
end;
begin
approximate := abs(x - y) <= epsReal * (maxReal / (d(x) + d(y)))
end;
begin
equal := (x = y) or_else (x * y >= 0.0) and_then approximate
end;
{ --- auxilliary routines ---------------------------------------------- }
procedure test(protected x, y: real);
const
{ ANSI escape code for color coding }
CSI = chr(8#33) + '[';
totalMinimumWidth = 40;
postRadixDigits = 24;
begin
write(x:totalMinimumWidth:postRadixDigits, '':1, CSI, '1;3');
if equal(x, y) then
begin
if x = y then
begin
write('2m≅')
end
else
begin
write('5m≆')
end
end
else
begin
write('1m≇')
end;
writeLn(CSI, 'm', '':1, y:totalMinimumWidth:postRadixDigits)
end;
{ === MAIN ============================================================= }
var
n: integer;
x: real;
begin
{ Variables were used to thwart compile-time evaluation done }
{ by /some/ compilers potentially confounding the results. }
n := 2;
x := 100000000000000.01;
test(x, 100000000000000.011);
test(100.01, 100.011);
test(x / 10000.0, 1000000000.0000001000);
test(0.001, 0.0010000001);
test(0.000000000000000000000101, 0.0);
x := sqrt(n);
test(sqr(x), 2.0);
test((-x) * x, -2.0);
test(3.14159265358979323846, 3.14159265358979324)
end. |
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #Crystal | Crystal | def generate(n : Int)
(['[',']'] * n).shuffle.join # Implicit return
end
def is_balanced(str : String)
count = 0
str.each_char do |ch|
case ch
when '['
count += 1
when ']'
count -= 1
if count < 0
return false
end
else
return false
end
end
count == 0
end
10.times do |i|
str = generate(i)
puts "#{str}: #{is_balanced(str)}"
end |
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file | Append a record to the end of a text file | Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment.
This feature is most useful in the case of log files, where many jobs may be appending to the log file at the same time, or where care must be taken to avoid concurrently overwriting the same record from another job.
Task
Given a two record sample for a mythical "passwd" file:
Write these records out in the typical system format.
Ideally these records will have named fields of various types.
Close the file, then reopen the file for append.
Append a new record to the file and close the file again.
Take appropriate care to avoid concurrently overwrites from another job.
Open the file and demonstrate the new record has indeed written to the end.
Source record field types and contents.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
jsmith
x
1001
1000
Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]
/home/jsmith
/bin/bash
jdoe
x
1002
1000
Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]
/home/jdoe
/bin/bash
Record to be appended.
account
password
UID
GID
fullname,office,extension,homephone,email
directory
shell
string
string
int
int
struct(string,string,string,string,string)
string
string
xyz
x
1003
1000
X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]
/home/xyz
/bin/bash
Resulting file format: should mimic Linux's /etc/passwd file format with particular attention to the "," separator used in the GECOS field. But if the specific language has a particular or unique format of storing records in text file, then this format should be named and demonstrated with an additional example.
Expected output:
Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash
Finally: Provide a summary of the language's "append record" capabilities in a table. eg.
Append Capabilities.
Data Representation
IO
Library
Append
Possible
Automatic
Append
Multi-tasking
Safe
In core
On disk
C struct
CSV text file
glibc/stdio
☑
☑
☑ (Not all, eg NFS)
Alternatively: If the language's appends can not guarantee its writes will always append, then note this restriction in the table. If possible, provide an actual code example (possibly using file/record locking) to guarantee correct concurrent appends.
| #D | D | class Record {
private const string account;
private const string password;
private const int uid;
private const int gid;
private const string[] gecos;
private const string directory;
private const string shell;
public this(string account, string password, int uid, int gid, string[] gecos, string directory, string shell) {
import std.exception;
this.account = enforce(account);
this.password = enforce(password);
this.uid = uid;
this.gid = gid;
this.gecos = enforce(gecos);
this.directory = enforce(directory);
this.shell = enforce(shell);
}
public void toString(scope void delegate(const(char)[]) sink) const {
import std.conv : toTextRange;
import std.format : formattedWrite;
import std.range : put;
sink(account);
put(sink, ':');
sink(password);
put(sink, ':');
toTextRange(uid, sink);
put(sink, ':');
toTextRange(gid, sink);
put(sink, ':');
formattedWrite(sink, "%-(%s,%)", gecos);
put(sink, ':');
sink(directory);
put(sink, ':');
sink(shell);
}
}
public Record parse(string text) {
import std.array : split;
import std.conv : to;
import std.string : chomp;
string[] tokens = text.chomp.split(':');
return new Record(
tokens[0],
tokens[1],
to!int(tokens[2]),
to!int(tokens[3]),
tokens[4].split(','),
tokens[5],
tokens[6]);
}
void main() {
import std.algorithm : map;
import std.file : exists, mkdir;
import std.stdio;
auto rawData = [
"jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash",
"jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash",
"xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash"
];
auto records = rawData.map!parse;
if (!exists("_rosetta")) {
mkdir("_rosetta");
}
auto passwd = File("_rosetta/.passwd", "w");
passwd.lock();
passwd.writeln(records[0]);
passwd.writeln(records[1]);
passwd.unlock();
passwd.close();
passwd.open("_rosetta/.passwd", "a");
passwd.lock();
passwd.writeln(records[2]);
passwd.unlock();
passwd.close();
passwd.open("_rosetta/.passwd");
foreach(string line; passwd.lines()) {
parse(line).writeln();
}
passwd.close();
} |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #App_Inventor | App Inventor |
/* ARM assembly Raspberry PI or android 32 bits */
/* program hashmap.s */
/* */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
.equ MAXI, 10 @ size hashmap
.equ HEAPSIZE,20000
.equ LIMIT, 10 @ key characters number for compute index
.equ COEFF, 80 @ filling rate 80 = 80%
/*******************************************/
/* Structures */
/********************************************/
/* structure hashMap */
.struct 0
hash_count: // stored values counter
.struct hash_count + 4
hash_key: // key
.struct hash_key + (4 * MAXI)
hash_data: // data
.struct hash_data + (4 * MAXI)
hash_fin:
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessFin: .asciz "End program.\n"
szCarriageReturn: .asciz "\n"
szMessNoP: .asciz "Key not found !!!\n"
szKey1: .asciz "one"
szData1: .asciz "Ceret"
szKey2: .asciz "two"
szData2: .asciz "Maureillas"
szKey3: .asciz "three"
szData3: .asciz "Le Perthus"
szKey4: .asciz "four"
szData4: .asciz "Le Boulou"
.align 4
iptZoneHeap: .int sZoneHeap // start heap address
iptZoneHeapEnd: .int sZoneHeap + HEAPSIZE // end heap address
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
//sZoneConv: .skip 24
tbHashMap1: .skip hash_fin @ hashmap
sZoneHeap: .skip HEAPSIZE @ heap
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrtbHashMap1
bl hashInit @ init hashmap
ldr r0,iAdrtbHashMap1
ldr r1,iAdrszKey1 @ store key one
ldr r2,iAdrszData1
bl hashInsert
cmp r0,#0 @ error ?
bne 100f
ldr r0,iAdrtbHashMap1
ldr r1,iAdrszKey2 @ store key two
ldr r2,iAdrszData2
bl hashInsert
cmp r0,#0
bne 100f
ldr r0,iAdrtbHashMap1
ldr r1,iAdrszKey3 @ store key three
ldr r2,iAdrszData3
bl hashInsert
cmp r0,#0
bne 100f
ldr r0,iAdrtbHashMap1
ldr r1,iAdrszKey4 @ store key four
ldr r2,iAdrszData4
bl hashInsert
cmp r0,#0
bne 100f
ldr r0,iAdrtbHashMap1
ldr r1,iAdrszKey2 @ remove key two
bl hashRemoveKey
cmp r0,#0
bne 100f
ldr r0,iAdrtbHashMap1
ldr r1,iAdrszKey1 @ search key
bl searchKey
cmp r0,#-1
beq 1f
bl affichageMess
ldr r0,iAdrszCarriageReturn
bl affichageMess
b 2f
1:
ldr r0,iAdrszMessNoP
bl affichageMess
2:
ldr r0,iAdrtbHashMap1
ldr r1,iAdrszKey2
bl searchKey
cmp r0,#-1
beq 3f
bl affichageMess
ldr r0,iAdrszCarriageReturn
bl affichageMess
b 4f
3:
ldr r0,iAdrszMessNoP
bl affichageMess
4:
ldr r0,iAdrtbHashMap1
ldr r1,iAdrszKey4
bl searchKey
cmp r0,#-1
beq 5f
bl affichageMess
ldr r0,iAdrszCarriageReturn
bl affichageMess
b 6f
5:
ldr r0,iAdrszMessNoP
bl affichageMess
6:
ldr r0,iAdrszMessFin
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrszMessFin: .int szMessFin
iAdrtbHashMap1: .int tbHashMap1
iAdrszKey1: .int szKey1
iAdrszData1: .int szData1
iAdrszKey2: .int szKey2
iAdrszData2: .int szData2
iAdrszKey3: .int szKey3
iAdrszData3: .int szData3
iAdrszKey4: .int szKey4
iAdrszData4: .int szData4
iAdrszMessNoP: .int szMessNoP
/***************************************************/
/* init hashMap */
/***************************************************/
// r0 contains address to hashMap
hashInit:
push {r1-r3,lr} @ save registers
mov r1,#0
mov r2,#0
str r2,[r0,#hash_count] @ init counter
add r0,r0,#hash_key @ start zone key/value
1:
lsl r3,r1,#3
add r3,r3,r0
str r2,[r3,#hash_key]
str r2,[r3,#hash_data]
add r1,r1,#1
cmp r1,#MAXI
blt 1b
100:
pop {r1-r3,pc} @ restaur registers
/***************************************************/
/* insert key/datas */
/***************************************************/
// r0 contains address to hashMap
// r1 contains address to key
// r2 contains address to datas
hashInsert:
push {r1-r8,lr} @ save registers
mov r6,r0 @ save address
bl hashIndex @ search void key or identical key
cmp r0,#0 @ error ?
blt 100f
ldr r3,iAdriptZoneHeap
ldr r3,[r3]
ldr r8,iAdriptZoneHeapEnd
ldr r8,[r8]
sub r8,r8,#50
lsl r0,r0,#2 @ 4 bytes
add r7,r6,#hash_key @ start zone key/value
ldr r4,[r7,r0]
cmp r4,#0 @ key already stored ?
bne 1f
ldr r4,[r6,#hash_count] @ no -> increment counter
add r4,r4,#1
cmp r4,#(MAXI * COEFF / 100)
bge 98f
str r4,[r6,#hash_count]
1:
str r3,[r7,r0]
mov r4,#0
2: @ copy key loop in heap
ldrb r5,[r1,r4]
strb r5,[r3,r4]
cmp r5,#0
add r4,r4,#1
bne 2b
add r3,r3,r4
cmp r3,r8
bge 99f
add r7,r6,#hash_data
str r3,[r7,r0]
mov r4,#0
3: @ copy data loop in heap
ldrb r5,[r2,r4]
strb r5,[r3,r4]
cmp r5,#0
add r4,r4,#1
bne 3b
add r3,r3,r4
cmp r3,r8
bge 99f
ldr r0,iAdriptZoneHeap
str r3,[r0] @ new heap address
mov r0,#0 @ insertion OK
b 100f
98: @ error hashmap
adr r0,szMessErrInd
bl affichageMess
mov r0,#-1
b 100f
99: @ error heap
adr r0,szMessErrHeap
bl affichageMess
mov r0,#-1
100:
pop {r1-r8,lr} @ restaur registers
bx lr @ return
szMessErrInd: .asciz "Error : HashMap size Filling rate Maxi !!\n"
szMessErrHeap: .asciz "Error : Heap size Maxi !!\n"
.align 4
iAdriptZoneHeap: .int iptZoneHeap
iAdriptZoneHeapEnd: .int iptZoneHeapEnd
/***************************************************/
/* search void index in hashmap */
/***************************************************/
// r0 contains hashMap address
// r1 contains key address
hashIndex:
push {r1-r4,lr} @ save registers
add r4,r0,#hash_key
mov r2,#0 @ index
mov r3,#0 @ characters sum
1: @ loop to compute characters sum
ldrb r0,[r1,r2]
cmp r0,#0 @ string end ?
beq 2f
add r3,r3,r0 @ add to sum
add r2,r2,#1
cmp r2,#LIMIT
blt 1b
2:
mov r5,r1 @ save key address
mov r0,r3
mov r1,#MAXI
bl division @ compute remainder -> r3
mov r1,r5 @ key address
3:
ldr r0,[r4,r3,lsl #2] @ loak key for computed index
cmp r0,#0 @ void key ?
beq 4f
bl comparStrings @ identical key ?
cmp r0,#0
beq 4f @ yes
add r3,r3,#1 @ no search next void key
cmp r3,#MAXI @ maxi ?
movge r3,#0 @ restart to index 0
b 3b
4:
mov r0,r3 @ return index void array or key equal
100:
pop {r1-r4,pc} @ restaur registers
/***************************************************/
/* search key in hashmap */
/***************************************************/
// r0 contains hash map address
// r1 contains key address
searchKey:
push {r1-r2,lr} @ save registers
mov r2,r0
bl hashIndex
lsl r0,r0,#2
add r1,r0,#hash_key
ldr r1,[r2,r1]
cmp r1,#0
moveq r0,#-1
beq 100f
add r1,r0,#hash_data
ldr r0,[r2,r1]
100:
pop {r1-r2,pc} @ restaur registers
/***************************************************/
/* remove key in hashmap */
/***************************************************/
// r0 contains hash map address
// r1 contains key address
hashRemoveKey: @ INFO: hashRemoveKey
push {r1-r3,lr} @ save registers
mov r2,r0
bl hashIndex
lsl r0,r0,#2
add r1,r0,#hash_key
ldr r3,[r2,r1]
cmp r3,#0
beq 2f
add r3,r2,r1
mov r1,#0 @ raz key address
str r1,[r3]
add r1,r0,#hash_data
add r3,r2,r1
mov r1,#0
str r1,[r3] @ raz datas address
mov r0,#0
b 100f
2:
adr r0,szMessErrRemove
bl affichageMess
mov r0,#-1
100:
pop {r1-r3,pc} @ restaur registers
szMessErrRemove: .asciz "\033[31mError remove key !!\033[0m\n"
.align 4
/************************************/
/* Strings case sensitive comparisons */
/************************************/
/* r0 et r1 contains the address of strings */
/* return 0 in r0 if equals */
/* return -1 if string r0 < string r1 */
/* return 1 if string r0 > string r1 */
comparStrings:
push {r1-r4} @ save des registres
mov r2,#0 @ characters counter
1:
ldrb r3,[r0,r2] @ byte string 1
ldrb r4,[r1,r2] @ byte string 2
cmp r3,r4
movlt r0,#-1 @ smaller
movgt r0,#1 @ greather
bne 100f @ not equals
cmp r3,#0 @ 0 end string ?
moveq r0,#0 @ equals
beq 100f @ end string
add r2,r2,#1 @ else add 1 in counter
b 1b @ and loop
100:
pop {r1-r4}
bx lr
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
|
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #BASIC | BASIC | 10 DEFINT A-Z
20 N=1
30 IF S>=20 THEN END ELSE F=1
40 IF N<2 GOTO 70 ELSE FOR I=1 TO N\2
50 IF N MOD I=0 THEN F=F+1
60 NEXT
70 IF F<=M GOTO 110
80 PRINT N,
90 M=F
100 S=S+1
110 N=N+1
120 GOTO 30 |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #BASIC256 | BASIC256 |
Dim Results(20)
Candidate = 1
max_divisors = 0
Print "Los primeros 20 anti-primos son:"
For j = 0 To 19
Do
divisors = count_divisors(Candidate)
If max_divisors < divisors Then
Results[j] = Candidate
max_divisors = divisors
Exit Do
End If
Candidate += 1
Until false
Print Results[j];" ";
Next j
Function count_divisors(n)
cont = 1
For i = 1 To n/2
If (n % i) = 0 Then cont += 1
Next i
count_divisors = cont
End Function
|
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.
| #Java | Java | import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;
public class AtomicUpdates {
private static final int NUM_BUCKETS = 10;
public static class Buckets {
private final int[] data;
public Buckets(int[] data) {
this.data = data.clone();
}
public int getBucket(int index) {
synchronized (data) {
return data[index];
}
}
public int transfer(int srcIndex, int dstIndex, int amount) {
if (amount < 0)
throw new IllegalArgumentException("negative amount: " + amount);
if (amount == 0)
return 0;
synchronized (data) {
if (data[srcIndex] - amount < 0)
amount = data[srcIndex];
if (data[dstIndex] + amount < 0)
amount = Integer.MAX_VALUE - data[dstIndex];
if (amount < 0)
throw new IllegalStateException();
data[srcIndex] -= amount;
data[dstIndex] += amount;
return amount;
}
}
public int[] getBuckets() {
synchronized (data) {
return data.clone();
}
}
}
private static long getTotal(int[] values) {
long total = 0;
for (int value : values) {
total += value;
}
return total;
}
public static void main(String[] args) {
ThreadLocalRandom rnd = ThreadLocalRandom.current();
int[] values = new int[NUM_BUCKETS];
for (int i = 0; i < values.length; i++)
values[i] = rnd.nextInt() & Integer.MAX_VALUE;
System.out.println("Initial Array: " + getTotal(values) + " " + Arrays.toString(values));
Buckets buckets = new Buckets(values);
new Thread(() -> equalize(buckets), "equalizer").start();
new Thread(() -> transferRandomAmount(buckets), "transferrer").start();
new Thread(() -> print(buckets), "printer").start();
}
private static void transferRandomAmount(Buckets buckets) {
ThreadLocalRandom rnd = ThreadLocalRandom.current();
while (true) {
int srcIndex = rnd.nextInt(NUM_BUCKETS);
int dstIndex = rnd.nextInt(NUM_BUCKETS);
int amount = rnd.nextInt() & Integer.MAX_VALUE;
buckets.transfer(srcIndex, dstIndex, amount);
}
}
private static void equalize(Buckets buckets) {
ThreadLocalRandom rnd = ThreadLocalRandom.current();
while (true) {
int srcIndex = rnd.nextInt(NUM_BUCKETS);
int dstIndex = rnd.nextInt(NUM_BUCKETS);
int amount = (buckets.getBucket(srcIndex) - buckets.getBucket(dstIndex)) / 2;
if (amount >= 0)
buckets.transfer(srcIndex, dstIndex, amount);
}
}
private static void print(Buckets buckets) {
while (true) {
long nextPrintTime = System.currentTimeMillis() + 3000;
long now;
while ((now = System.currentTimeMillis()) < nextPrintTime) {
try {
Thread.sleep(nextPrintTime - now);
} catch (InterruptedException e) {
return;
}
}
int[] bucketValues = buckets.getBuckets();
System.out.println("Current values: " + getTotal(bucketValues) + " " + Arrays.toString(bucketValues));
}
}
} |
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.
| #GAP | GAP | # See section 7.5 of reference manual
# GAP has assertions levels. An assertion is tested if its level
# is less then the global level.
# Set global level
SetAssertionLevel(10);
a := 1;
Assert(20, a > 1, "a should be greater than one");
# nothing happens
a := 1;
Assert(4, a > 1, "a should be greater than one");
# error
# Show current global level
AssertionLevel();
# 10 |
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.
| #Go | Go | package main
func main() {
x := 43
if x != 42 {
panic(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.
| #Groovy | Groovy | def checkTheAnswer = {
assert it == 42 : "This: " + it + " is not the answer!"
} |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Babel | Babel | sq { dup * } < |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #BBC_BASIC | BBC BASIC | DIM a(4)
a() = 1, 2, 3, 4, 5
PROCmap(a(), FNsqrt())
FOR i = 0 TO 4
PRINT a(i)
NEXT
END
DEF FNsqrt(n) = SQR(n)
DEF PROCmap(array(), RETURN func%)
LOCAL I%
FOR I% = 0 TO DIM(array(),1)
array(I%) = FN(^func%)(array(I%))
NEXT
ENDPROC
|
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
| #Objeck | Objeck |
use Collection;
class Mode {
function : Main(args : String[]) ~ Nil {
Print(Mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]));
Print(Mode([1, 2, 4, 4, 1]));
}
function : Mode(coll : Int[]) ~ IntVector {
seen := IntMap->New();
max := 0;
maxElems := IntVector->New();
each(i : coll) {
value := coll[i];
featched := seen->Find(value)->As(IntHolder);
if(featched <> Nil) {
seen->Remove(value);
seen->Insert(value, IntHolder->New(featched->Get() + 1));
}
else {
seen->Insert(value, IntHolder->New(1));
};
featched := seen->Find(value)->As(IntHolder);
if(featched->Get() > max) {
max := featched->Get();
maxElems->Empty();
maxElems->AddBack(value);
}
else if(featched->Get() = max) {
maxElems->AddBack(value);
};
};
return maxElems;
}
function : Print(out : IntVector) ~ Nil {
'['->Print();
each(i : out) {
out->Get(i)->Print();
if(i + 1 < out->Size()) {
", "->Print();
};
};
']'->PrintLine();
}
}
|
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
| #Ceylon | Ceylon | shared void run() {
value myMap = map {
"foo" -> 5,
"bar" -> 10,
"baz" -> 15
};
for(key in myMap.keys) {
print(key);
}
for(item in myMap.items) {
print(item);
}
for(key->item in myMap) {
print("``key`` maps to ``item``");
}
} |
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
| #Chapel | Chapel | var A = [ "H2O" => "water", "NaCl" => "salt", "O2" => "oxygen" ];
for k in A.domain do
writeln("have key: ", k);
for v in A do
writeln("have value: ", v);
for (k,v) in zip(A.domain, A) do
writeln("have element: ", k, " -> ", v); |
http://rosettacode.org/wiki/Apply_a_digital_filter_(direct_form_II_transposed) | Apply a digital filter (direct form II transposed) | Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [1]
Task
Filter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667]
The signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]
| #Java | Java | public class DigitalFilter {
private static double[] filter(double[] a, double[] b, double[] signal) {
double[] result = new double[signal.length];
for (int i = 0; i < signal.length; ++i) {
double tmp = 0.0;
for (int j = 0; j < b.length; ++j) {
if (i - j < 0) continue;
tmp += b[j] * signal[i - j];
}
for (int j = 1; j < a.length; ++j) {
if (i - j < 0) continue;
tmp -= a[j] * result[i - j];
}
tmp /= a[0];
result[i] = tmp;
}
return result;
}
public static void main(String[] args) {
double[] a = new double[]{1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17};
double[] b = new double[]{0.16666667, 0.5, 0.5, 0.16666667};
double[] signal = new double[]{
-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
};
double[] result = filter(a, b, signal);
for (int i = 0; i < result.length; ++i) {
System.out.printf("% .8f", result[i]);
System.out.print((i + 1) % 5 != 0 ? ", " : "\n");
}
}
} |
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
| #Crystal | Crystal | # Crystal will return NaN if an empty array is passed
def mean(arr) : Float64
arr.sum / arr.size.to_f
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
| #D | D | real mean(Range)(Range r) pure nothrow @nogc {
real sum = 0.0;
int count;
foreach (item; r) {
sum += item;
count++;
}
if (count == 0)
return 0.0;
else
return sum / count;
}
void main() {
import std.stdio;
int[] data;
writeln("Mean: ", data.mean);
data = [3, 1, 4, 1, 5, 9];
writeln("Mean: ", data.mean);
} |
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
| #Raku | Raku | # Show original hashes
say my %base = :name('Rocket Skates'), :price<12.75>, :color<yellow>;
say my %update = :price<15.25>, :color<red>, :year<1974>;
# Need to assign to anonymous hash to get the desired results and avoid mutating
# TIMTOWTDI
say "\nUpdate:\n", join "\n", sort %=%base, %update;
# Same
say "\nUpdate:\n", {%base, %update}.sort.join: "\n";
say "\nMerge:\n", join "\n", sort ((%=%base).push: %update)».join: ', ';
# Same
say "\nMerge:\n", ({%base}.push: %update)».join(', ').sort.join: "\n";
# Demonstrate unmutated hashes
say "\n", %base, "\n", %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
| #REXX | REXX | /*REXX program merges two associative arrays (requiring an external list of indices). */
$.= /*define default value(s) for arrays. */
@.wAAn= 21; @.wKey= 7; @.wVal= 7 /*max widths of: AAname, keys, values.*/
call defAA 'base', "name Rocket Skates", 'price 12.75', "color yellow"
call defAA 'update', "price 15.25", "color red", 'year 1974'
call show 'base'
call show 'update'
call show 'new'
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
defAA: procedure expose $. @.; parse arg AAn; new= 'new' /*get AA name; set NEW.*/
do j=2 to arg(); parse value arg(j) with key val /*obtain key and value.*/
$.AAn.key= val /*assign a value to a key for AAn. */
if wordpos(key, $.AAN.?keys)==0 then $.AAn.?keys= $.AAn.?keys key
/* [↑] add to key list if not in list.*/
$.new.key= val /*assign a value to a key for "new".*/
if wordpos(key, $.new.?keys)==0 then $.new.?keys= $.new.?keys key
/* [↑] add to key list if not in list.*/
@.wKey= max(@.wKey, length(key) ) /*find max width of a name of a key. */
@.wVal= max(@.wVal, length(val) ) /* " " " " " " " " value.*/
@.wAA = max(@.wAAn, length(AAn) ) /* " " " " " " " array.*/
end /*j*/
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: procedure expose $. @.; parse arg AAn; say; _= '═' /*set title char.*/
do j=1 for words($.AAn.?keys) /*process keys. */
if j==1 then say center('associate array', @.wAAn, _) ,
center("key" , @.wKey, _) ,
center('value' , @.wVal + 2, _)
key= word($.AAn.?keys, j) /*get the name of a key.*/
say center(AAn, @.wAAn) right(key, @.wKey) $.AAn.key /*show some information.*/
end /*j*/
return |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.