task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of positive integers.
The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
A
(
x
1
,
…
,
x
n
)
=
x
1
+
⋯
+
x
n
n
{\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}}
The geometric mean is the
n
{\displaystyle n}
th root of the product of the list:
G
(
x
1
,
…
,
x
n
)
=
x
1
⋯
x
n
n
{\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}}
The harmonic mean is
n
{\displaystyle n}
divided by the sum of the reciprocal of each item in the list:
H
(
x
1
,
…
,
x
n
)
=
n
1
x
1
+
⋯
+
1
x
n
{\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Go | Go | package main
import (
"fmt"
"math"
)
func main() {
sum, sumr, prod := 0., 0., 1.
for n := 1.; n <= 10; n++ {
sum += n
sumr += 1 / n
prod *= n
}
a, g, h := sum/10, math.Pow(prod, .1), 10/sumr
fmt.Println("A:", a, "G:", g, "H:", h)
fmt.Println("A >= G >= H:", a >= g && g >= h)
} |
http://rosettacode.org/wiki/Balanced_ternary | Balanced ternary | Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1.
Examples
Decimal 11 = 32 + 31 − 30, thus it can be written as "++−"
Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0"
Task
Implement balanced ternary representation of integers with the following:
Support arbitrarily large integers, both positive and negative;
Provide ways to convert to and from text strings, using digits '+', '-' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5).
Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type is balanced ternary). If your native integers can't support arbitrary length, overflows during conversion must be indicated.
Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do not convert to native integers first.
Make your implementation efficient, with a reasonable definition of "efficient" (and with a reasonable definition of "reasonable").
Test case With balanced ternaries a from string "+-0++0+", b from native integer -436, c "+-++-":
write out a, b and c in decimal notation;
calculate a × (b − c), write out the result in both ternary and decimal notations.
Note: The pages generalised floating point addition and generalised floating point multiplication have code implementing arbitrary precision floating point balanced ternary.
| #Lua | Lua | function to_bt(n)
local d = { '0', '+', '-' }
local v = { 0, 1, -1 }
local b = ""
while n ~= 0 do
local r = n % 3
if r < 0 then
r = r + 3
end
b = b .. d[r + 1]
n = n - v[r + 1]
n = math.floor(n / 3)
end
return b:reverse()
end
function from_bt(s)
local n = 0
for i=1,s:len() do
local c = s:sub(i,i)
n = n * 3
if c == '+' then
n = n + 1
elseif c == '-' then
n = n - 1
end
end
return n
end
function last_char(s)
return s:sub(-1,-1)
end
function add(b1,b2)
local out = "oops"
if b1 ~= "" and b2 ~= "" then
local d = ""
local L1 = last_char(b1)
local c1 = b1:sub(1,-2)
local L2 = last_char(b2)
local c2 = b2:sub(1,-2)
if L2 < L1 then
L2, L1 = L1, L2
end
if L1 == '-' then
if L2 == '0' then
d = "-"
end
if L2 == '-' then
d = "+-"
end
elseif L1 == '+' then
if L2 == '0' then
d = "+"
elseif L2 == '-' then
d = "0"
elseif L2 == '+' then
d = "-+"
end
elseif L1 == '0' then
if L2 == '0' then
d = "0"
end
end
local ob1 = add(c1,d:sub(2,2))
local ob2 = add(ob1,c2)
out = ob2 .. d:sub(1,1)
elseif b1 ~= "" then
out = b1
elseif b2 ~= "" then
out = b2
else
out = ""
end
return out
end
function unary_minus(b)
local out = ""
for i=1, b:len() do
local c = b:sub(i,i)
if c == '-' then
out = out .. '+'
elseif c == '+' then
out = out .. '-'
else
out = out .. c
end
end
return out
end
function subtract(b1,b2)
return add(b1, unary_minus(b2))
end
function mult(b1,b2)
local r = "0"
local c1 = b1
local c2 = b2:reverse()
for i=1,c2:len() do
local c = c2:sub(i,i)
if c == '+' then
r = add(r, c1)
elseif c == '-' then
r = subtract(r, c1)
end
c1 = c1 .. '0'
end
while r:sub(1,1) == '0' do
r = r:sub(2)
end
return r
end
function main()
local a = "+-0++0+"
local b = to_bt(-436)
local c = "+-++-"
local d = mult(a, subtract(b, c))
print(string.format(" a: %14s %10d", a, from_bt(a)))
print(string.format(" b: %14s %10d", b, from_bt(b)))
print(string.format(" c: %14s %10d", c, from_bt(c)))
print(string.format("a*(b-c): %14s %10d", d, from_bt(d)))
end
main() |
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.
| #PILOT | PILOT | Remark:Lines identified as "remarks" are intended for the human reader, and will be ignored by the machine.
Remark:A "compute" instruction gives a value to a variable.
Remark:We begin by making the variable n equal to 2.
Compute:n = 2
Remark:Lines beginning with asterisks are labels. We can instruct the machine to "jump" to them, rather than carrying on to the next instruction as it normally would.
*CheckNextNumber
Remark:In "compute" instructions, "x * y" should be read as "x times y" and "x % y" as "x modulo y".
Compute:square = n * n
Compute:lastSix = square % 1000000
Remark:A "jump" instruction that includes an equation or an inequality in parentheses jumps to the designated label if and only if the equation or inequality is true.
Jump( lastSix = 269696 ):*FoundIt
Remark:If the last six digits are not equal to 269696, add 2 to n and jump back to "CheckNextNumber".
Compute:n = n + 2
Jump:*CheckNextNumber
*FoundIt
Remark:Type, i.e. print, the result. The symbol "#" means that what follows is one of our variables and the machine should type its value.
Type:The smallest number whose square ends in 269696 is #n. Its square is #square.
Remark:The end.
End: |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #Plain_English | Plain English | To run:
Start up.
Put 1 into a number.
Loop.
Divide the number times the number by 1000000 giving a quotient and a remainder.
If the remainder is 269696, break.
Bump the number.
Repeat.
Write "The answer is " then the number on the console.
Wait for the escape key.
Shut down. |
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.
| #Delphi | Delphi |
program Approximate_Equality;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Math;
const
EPSILON: Double = 1E-18;
procedure Test(a, b: Double; Expected: Boolean);
var
result: Boolean;
const
STATUS: array[Boolean] of string = ('FAIL', 'OK');
begin
result := SameValue(a, b, EPSILON);
Write(a, ' ', b, ' => ', result, ' '^I);
writeln(Expected, ^I, STATUS[Expected = result]);
end;
begin
Test(100000000000000.01, 100000000000000.011, True);
Test(100.01, 100.011, False);
Test(double(10000000000000.001) / double(10000.0), double(1000000000.0000001000),
False);
Test(0.001, 0.0010000001, False);
Test(0.000000000000000000000101, 0.0, True);
Test(double(Sqrt(2)) * double(Sqrt(2)), 2.0, False);
Test(-double(Sqrt(2)) * double(Sqrt(2)), -2.0, false);
Test(3.14159265358979323846, 3.14159265358979324, True);
Readln;
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
| #C.2B.2B | C++ | #include <algorithm>
#include <iostream>
#include <string>
std::string generate(int n, char left = '[', char right = ']')
{
std::string str(std::string(n, left) + std::string(n, right));
std::random_shuffle(str.begin(), str.end());
return str;
}
bool balanced(const std::string &str, char left = '[', char right = ']')
{
int count = 0;
for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
{
if (*it == left)
count++;
else if (*it == right)
if (--count < 0) return false;
}
return count == 0;
}
int main()
{
srand(time(NULL)); // seed rng
for (int i = 0; i < 9; ++i)
{
std::string s(generate(i));
std::cout << (balanced(s) ? " ok: " : "bad: ") << s << "\n";
}
} |
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.
| #Action.21 | Action! | PROC CreateLog(CHAR ARRAY fname)
CHAR ARRAY header="account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell"
BYTE dev=[1]
Close(dev)
Open(dev,fname,8)
PrintDE(dev,header)
Close(dev)
RETURN
PROC AppendLog(CHAR ARRAY fname,line)
BYTE dev=[1]
Close(dev)
Open(dev,fname,9)
PrintDE(dev,line)
Close(dev)
RETURN
PROC ReadFile(CHAR ARRAY fname)
CHAR ARRAY line(255)
BYTE dev=[1]
Close(dev)
Open(dev,fname,4)
WHILE Eof(dev)=0
DO
InputSD(dev,line)
IF line(0) THEN
PutE() Print(line)
FI
OD
Close(dev)
RETURN
PROC PrintInv(CHAR ARRAY a)
BYTE i
IF a(0)>0 THEN
FOR i=1 TO a(0)
DO
Put(a(i)%$80)
OD
FI
RETURN
PROC Main()
CHAR ARRAY fname="D:PASSWD"
BYTE LMARGIN=$52,oldLMARGIN
oldLMARGIN=LMARGIN
LMARGIN=0 ;remove left margin on the screen
Put(125) PutE() ;clear the screen
CreateLog(fname)
AppendLog(fname,"jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash")
AppendLog(fname,"jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash")
PrintInv("Initial log:")
ReadFile(fname)
AppendLog(fname,"xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash")
PutE() PrintInv("Updated log:")
ReadFile(fname)
LMARGIN=oldLMARGIN ;restore left margin on the screen
RETURN |
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
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */
/* program hashmap64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ MAXI, 10
.equ HEAPSIZE,20000
.equ LIMIT, 10 // key characters number for compute hash
.equ COEFF, 80 // filling rate 80 = 80%
/*******************************************/
/* Structures */
/********************************************/
/* structure hashMap */
.struct 0
hash_count: // stored values counter
.struct hash_count + 8
hash_key: // key
.struct hash_key + (8 * MAXI)
hash_data: // data
.struct hash_data + (8 * 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: .quad sZoneHeap // start heap address
iptZoneHeapEnd: .quad sZoneHeap + HEAPSIZE // end heap address
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
tbHashMap1: .skip hash_fin // hashmap
sZoneHeap: .skip HEAPSIZE // heap
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrtbHashMap1
bl hashInit // init hashmap
ldr x0,qAdrtbHashMap1
ldr x1,qAdrszKey1 // store key one
ldr x2,qAdrszData1
bl hashInsert
cmp x0,#0 // error ?
bne 100f
ldr x0,qAdrtbHashMap1
ldr x1,qAdrszKey2 // store key two
ldr x2,qAdrszData2
bl hashInsert
cmp x0,#0
bne 100f
ldr x0,qAdrtbHashMap1
ldr x1,qAdrszKey3 // store key three
ldr x2,qAdrszData3
bl hashInsert
cmp x0,#0
bne 100f
ldr x0,qAdrtbHashMap1
ldr x1,qAdrszKey4 // store key four
ldr x2,qAdrszData4
bl hashInsert
cmp x0,#0
bne 100f
ldr x0,qAdrtbHashMap1
ldr x1,qAdrszKey2 // remove key two
bl hashRemoveKey
cmp x0,#0
bne 100f
ldr x0,qAdrtbHashMap1
ldr x1,qAdrszKey1 // search key one
bl searchKey
cmp x0,#-1
beq 1f
bl affichageMess
ldr x0,qAdrszCarriageReturn
bl affichageMess
b 2f
1:
ldr x0,qAdrszMessNoP
bl affichageMess
2:
ldr x0,qAdrtbHashMap1
ldr x1,qAdrszKey2 // search key two
bl searchKey
cmp x0,#-1
beq 3f
bl affichageMess
ldr x0,qAdrszCarriageReturn
bl affichageMess
b 4f
3:
ldr x0,qAdrszMessNoP
bl affichageMess
4:
ldr x0,qAdrtbHashMap1
ldr x1,qAdrszKey4 // search key four
bl searchKey
cmp x0,#-1
beq 5f
bl affichageMess
ldr x0,qAdrszCarriageReturn
bl affichageMess
b 6f
5:
ldr x0,qAdrszMessNoP
bl affichageMess
6:
ldr x0,qAdrszMessFin
bl affichageMess
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszMessFin: .quad szMessFin
qAdrtbHashMap1: .quad tbHashMap1
qAdrszKey1: .quad szKey1
qAdrszData1: .quad szData1
qAdrszKey2: .quad szKey2
qAdrszData2: .quad szData2
qAdrszKey3: .quad szKey3
qAdrszData3: .quad szData3
qAdrszKey4: .quad szKey4
qAdrszData4: .quad szData4
qAdrszMessNoP: .quad szMessNoP
/***************************************************/
/* init hashMap */
/***************************************************/
// x0 contains address to hashMap
hashInit:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
mov x1,#0
mov x2,#0
str x2,[x0,#hash_count] // init counter
add x0,x0,#hash_key // start zone key/value
1:
lsl x3,x1,#3
add x3,x3,x0
str x2,[x3,#hash_key]
str x2,[x3,#hash_data]
add x1,x1,#1
cmp x1,#MAXI
blt 1b
100:
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
/***************************************************/
/* insert key/datas */
/***************************************************/
// x0 contains address to hashMap
// x1 contains address to key
// x2 contains address to datas
hashInsert:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
stp x6,x7,[sp,-16]! // save registres
mov x6,x0 // save address
bl hashIndex // search void key or identical key
cmp x0,#0 // error ?
blt 100f
ldr x3,qAdriptZoneHeap
ldr x3,[x3]
ldr x7,qAdriptZoneHeapEnd
ldr x7,[x7]
sub x7,x7,#50
lsl x0,x0,#3 // 8 bytes
add x5,x6,#hash_key // start zone key/value
ldr x4,[x5,x0]
cmp x4,#0 // key already stored ?
bne 1f
ldr x4,[x6,#hash_count] // no -> increment counter
add x4,x4,#1
cmp x4,#(MAXI * COEFF / 100)
bge 98f
str x4,[x6,#hash_count]
1:
str x3,[x5,x0] // store heap key address in hashmap
mov x4,#0
2: // copy key loop in heap
ldrb w5,[x1,x4]
strb w5,[x3,x4]
cmp w5,#0
add x4,x4,#1
bne 2b
add x3,x3,x4
cmp x3,x7
bge 99f
add x1,x6,#hash_data
str x3,[x1,x0] // store heap data address in hashmap
mov x4,#0
3: // copy data loop in heap
ldrb w5,[x2,x4]
strb w5,[x3,x4]
cmp w5,#0
add x4,x4,#1
bne 3b
add x3,x3,x4
cmp x3,x7
bge 99f
ldr x0,qAdriptZoneHeap
str x3,[x0] // new heap address
mov x0,#0 // insertion OK
b 100f
98: // error hashmap
adr x0,szMessErrInd
bl affichageMess
mov x0,#-1
b 100f
99: // error heap
adr x0,szMessErrHeap
bl affichageMess
mov x0,#-1
100:
ldp x6,x7,[sp],16 // restaur des 2 registres
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
szMessErrInd: .asciz "Error : HashMap size Filling rate Maxi !!\n"
szMessErrHeap: .asciz "Error : Heap size Maxi !!\n"
.align 4
qAdriptZoneHeap: .quad iptZoneHeap
qAdriptZoneHeapEnd: .quad iptZoneHeapEnd
/***************************************************/
/* search void index in hashmap */
/***************************************************/
// x0 contains hashMap address
// x1 contains key address
hashIndex:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
add x4,x0,#hash_key
mov x2,#0 // index
mov x3,#0 // characters sum
1: // loop to compute characters sum
ldrb w0,[x1,x2]
cmp w0,#0 // string end ?
beq 2f
add x3,x3,x0 // add to sum
add x2,x2,#1
cmp x2,#LIMIT
blt 1b
2:
mov x5,x1 // save key address
mov x0,x3
mov x1,#MAXI
udiv x2,x0,x1
msub x3,x2,x1,x0 // compute remainder -> x3
mov x1,x5 // key address
3:
ldr x0,[x4,x3,lsl #3] // loak key for computed index
cmp x0,#0 // void key ?
beq 4f
bl comparStrings // identical key ?
cmp x0,#0
beq 4f // yes
add x3,x3,#1 // no search next void key
cmp x3,#MAXI // maxi ?
csel x3,xzr,x3,ge // restart to index 0
b 3b
4:
mov x0,x3 // return index void array or key equal
100:
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
/***************************************************/
/* search key in hashmap */
/***************************************************/
// x0 contains hash map address
// x1 contains key address
searchKey:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
mov x2,x0
bl hashIndex
lsl x0,x0,#3
add x1,x0,#hash_key
ldr x1,[x2,x1]
cmp x1,#0
beq 2f
add x1,x0,#hash_data
ldr x0,[x2,x1]
b 100f
2:
mov x0,#-1
100:
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
/***************************************************/
/* remove key in hashmap */
/***************************************************/
// x0 contains hash map address
// x1 contains key address
hashRemoveKey:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
mov x2,x0
bl hashIndex
lsl x0,x0,#3
add x1,x0,#hash_key
ldr x3,[x2,x1]
cmp x3,#0
beq 2f
str xzr,[x2,x1] // raz key address
add x1,x0,#hash_data
str xzr,[x2,x1] // raz datas address
mov x0,0
b 100f
2:
adr x0,szMessErrRemove
bl affichageMess
mov x0,#-1
100:
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
szMessErrRemove: .asciz "\033[31mError remove key !!\033[0m\n"
.align 4
/************************************/
/* Strings case sensitive comparisons */
/************************************/
/* x0 et x1 contains the address of strings */
/* return 0 in x0 if equals */
/* return -1 if string x0 < string x1 */
/* return 1 if string x0 > string x1 */
comparStrings:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
mov x2,#0 // characters counter
1:
ldrb w3,[x0,x2] // byte string 1
ldrb w4,[x1,x2] // byte string 2
cmp w3,w4
blt 2f
bgt 3f
cmp w3,#0 // 0 end string ?
beq 4f
add x2,x2,#1 // else add 1 in counter
b 1b // and loop
2:
mov x0,#-1 // smaller
b 100f
3:
mov x0,#1 // greather
b 100f
4:
mov x0,#0 // equals
100:
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.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.
| #E | E | #!/usr/bin/env rune
pragma.syntax("0.9")
def pi := (-1.0).acos()
def makeEPainter := <unsafe:com.zooko.tray.makeEPainter>
def colors := <awt:makeColor>
# --------------------------------------------------------------
# --- Definitions
/** Execute 'task' repeatedly as long 'indicator' is unresolved. */
def doWhileUnresolved(indicator, task) {
def loop() {
if (!Ref.isResolved(indicator)) {
task()
loop <- ()
}
}
loop <- ()
}
/** The data structure specified for the task. */
def makeBuckets(size) {
def values := ([100] * size).diverge() # storage
def buckets {
to size() :int { return size }
/** get current quantity in bucket 'i' */
to get(i :int) { return values[i] }
/** transfer 'amount' units, as much as possible, from bucket 'i' to bucket 'j'
or vice versa if 'amount' is negative */
to transfer(i :int, j :int, amount :int) {
def amountLim := amount.min(values[i]).max(-(values[j]))
values[i] -= amountLim
values[j] += amountLim
}
}
return buckets
}
/** A view of the current state of the buckets. */
def makeDisplayComponent(buckets) {
def c := makeEPainter(def paintCallback {
to paintComponent(g) {
def pixelsW := c.getWidth()
def pixelsH := c.getHeight()
def bucketsW := buckets.size()
g.setColor(colors.getWhite())
g.fillRect(0, 0, pixelsW, pixelsH)
g.setColor(colors.getDarkGray())
var sum := 0
for i in 0..!bucketsW {
sum += def value := buckets[i]
def x0 := (i * pixelsW / bucketsW).floor()
def x1 := ((i + 1) * pixelsW / bucketsW).floor()
g.fillRect(x0 + 1, pixelsH - value,
x1 - x0 - 1, value)
}
g.setColor(colors.getBlack())
g."drawString(String, int, int)"(`Total: $sum`, 2, 20)
}
})
c.setPreferredSize(<awt:makeDimension>(500, 300))
return c
}
# --------------------------------------------------------------
# --- Application setup
def buckets := makeBuckets(100)
def done # Promise indicating when the window is closed
# Create the window
def frame := <unsafe:javax.swing.makeJFrame>("Atomic transfers")
frame.setContentPane(def display := makeDisplayComponent(buckets))
frame.addWindowListener(def mainWindowListener {
to windowClosing(event) :void {
bind done := null
}
match _ {}
})
frame.setLocation(50, 50)
frame.pack()
# --------------------------------------------------------------
# --- Tasks
# Neatens up buckets
var ni := 0
doWhileUnresolved(done, fn {
def i := ni
def j := (ni + 1) %% buckets.size()
buckets.transfer(i, j, (buckets[i] - buckets[j]) // 4)
ni := j
})
# Messes up buckets
var mi := 0
doWhileUnresolved(done, fn {
def i := (mi + entropy.nextInt(3)) %% buckets.size()
def j := (i + entropy.nextInt(3)) %% buckets.size() #entropy.nextInt(buckets.size())
buckets.transfer(i, j, (buckets[i] / pi).floor())
mi := j
})
# Updates display at fixed 10 Hz
# (Note: tries to catch up; on slow systems slow this down or it will starve the other tasks)
def clock := timer.every(100, def _(_) {
if (Ref.isResolved(done)) {
clock.stop()
} else {
display.repaint()
}
})
clock.start()
# --------------------------------------------------------------
# --- All ready, go visible and wait
frame.show()
interp.waitAtTop(done) |
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.
| #C.2B.2B | C++ | #include <cassert> // assert.h also works
int main()
{
int a;
// ... input or change a here
assert(a == 42); // Aborts program if a is not 42, unless the NDEBUG macro was defined
// when including <cassert>, in which case it has no effect
} |
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.
| #Clojure | Clojure |
(let [i 42]
(assert (= i 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.
| #Common_Lisp | Common Lisp | (let ((x 42))
(assert (and (integerp x) (= 42 x)) (x))) |
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.
| #6502_Assembly | 6502 Assembly | define SRC_LO $00
define SRC_HI $01
define DEST_LO $02
define DEST_HI $03
define temp $04 ;temp storage used by foo
;some prep work since easy6502 doesn't allow you to define arbitrary bytes before runtime.
SET_TABLE:
TXA
STA $1000,X
INX
BNE SET_TABLE
;stores the identity table at memory address $1000-$10FF
CLEAR_TABLE:
LDA #0
STA $1200,X
INX
BNE CLEAR_TABLE
;fills the range $1200-$12FF with zeroes.
LDA #$10
STA SRC_HI
LDA #$00
STA SRC_LO
;store memory address $1000 in zero page
LDA #$12
STA DEST_HI
LDA #$00
STA DEST_LO
;store memory address $1200 in zero page
loop:
LDA (SRC_LO),y ;load accumulator from memory address $1000+y
JSR foo ;multiplies accumulator by 3.
STA (DEST_LO),y ;store accumulator in memory address $1200+y
INY
CPY #$56 ;alternatively you can store a size variable and check that here instead.
BCC loop
BRK
foo:
STA temp
ASL ;double accumulator
CLC
ADC temp ;2a + a = 3a
RTS |
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.
| #68000_Assembly | 68000 Assembly | LEA MyArray,A0
MOVE.W #(MyArray_End-MyArray)-1,D7 ;Len(MyArray)-1
MOVEQ #0,D0 ;sanitize D0-D2 to ensure nothing from any previous work will affect our math.
MOVEQ #0,D1
MOVEQ #0,D2
loop:
MOVE.B (A0),D0
MOVE.B D0,D1
MOVE.B D0,D2
MULU D1,D2
MOVE.B D2,(A0)+
dbra d7,loop
jmp * ;halt the CPU
MyArray:
DC.B 1,2,3,4,5,6,7,8,9,10
MyArray_End: |
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
| #K | K | mode: {(?x)@&n=|/n:#:'=x}
mode 1 1 1 1 2 2 2 3 3 3 3 4 4 3 2 4 4 4
3 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
| #Kotlin | Kotlin | fun <T> modeOf(a: Array<T>) {
val sortedByFreq = a.groupBy { it }.entries.sortedByDescending { it.value.size }
val maxFreq = sortedByFreq.first().value.size
val modes = sortedByFreq.takeWhile { it.value.size == maxFreq }
if (modes.size == 1)
println("The mode of the collection is ${modes.first().key} which has a frequency of $maxFreq")
else {
print("There are ${modes.size} modes with a frequency of $maxFreq, namely : ")
println(modes.map { it.key }.joinToString(", "))
}
}
fun main(args: Array<String>) {
val a = arrayOf(7, 1, 1, 6, 2, 4, 2, 4, 2, 1, 5)
println("[" + a.joinToString(", ") + "]")
modeOf(a)
println()
val b = arrayOf(true, false, true, false, true, true)
println("[" + b.joinToString(", ") + "]")
modeOf(b)
} |
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
| #ATS | ATS | ; Create an associative array
obj := Object("red", 0xFF0000, "blue", 0x0000FF, "green", 0x00FF00)
enum := obj._NewEnum()
While enum[key, value]
t .= key "=" value "`n"
MsgBox % t |
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
| #AutoHotkey | AutoHotkey | ; Create an associative array
obj := Object("red", 0xFF0000, "blue", 0x0000FF, "green", 0x00FF00)
enum := obj._NewEnum()
While enum[key, value]
t .= key "=" value "`n"
MsgBox % t |
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]
| #C | C |
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
#define MAX_LEN 1000
typedef struct{
float* values;
int size;
}vector;
vector extractVector(char* str){
vector coeff;
int i=0,count = 1;
char* token;
while(str[i]!=00){
if(str[i++]==' ')
count++;
}
coeff.values = (float*)malloc(count*sizeof(float));
coeff.size = count;
token = strtok(str," ");
i = 0;
while(token!=NULL){
coeff.values[i++] = atof(token);
token = strtok(NULL," ");
}
return coeff;
}
vector processSignalFile(char* fileName){
int i,j;
float sum;
char str[MAX_LEN];
vector coeff1,coeff2,signal,filteredSignal;
FILE* fp = fopen(fileName,"r");
fgets(str,MAX_LEN,fp);
coeff1 = extractVector(str);
fgets(str,MAX_LEN,fp);
coeff2 = extractVector(str);
fgets(str,MAX_LEN,fp);
signal = extractVector(str);
fclose(fp);
filteredSignal.values = (float*)calloc(signal.size,sizeof(float));
filteredSignal.size = signal.size;
for(i=0;i<signal.size;i++){
sum = 0;
for(j=0;j<coeff2.size;j++){
if(i-j>=0)
sum += coeff2.values[j]*signal.values[i-j];
}
for(j=0;j<coeff1.size;j++){
if(i-j>=0)
sum -= coeff1.values[j]*filteredSignal.values[i-j];
}
sum /= coeff1.values[0];
filteredSignal.values[i] = sum;
}
return filteredSignal;
}
void printVector(vector v, char* outputFile){
int i;
if(outputFile==NULL){
printf("[");
for(i=0;i<v.size;i++)
printf("%.12f, ",v.values[i]);
printf("\b\b]");
}
else{
FILE* fp = fopen(outputFile,"w");
for(i=0;i<v.size-1;i++)
fprintf(fp,"%.12f, ",v.values[i]);
fprintf(fp,"%.12f",v.values[i]);
fclose(fp);
}
}
int main(int argC,char* argV[])
{
char *str;
if(argC<2||argC>3)
printf("Usage : %s <name of signal data file and optional output file.>",argV[0]);
else{
if(argC!=2){
str = (char*)malloc((strlen(argV[2]) + strlen(str) + 1)*sizeof(char));
strcpy(str,"written to ");
}
printf("Filtered signal %s",(argC==2)?"is:\n":strcat(str,argV[2]));
printVector(processSignalFile(argV[1]),argV[2]);
}
return 0;
}
|
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #bc | bc | define m(a[], n) {
auto i, s
for (i = 0; i < n; i++) {
s += a[i]
}
return(s / 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
| #Befunge | Befunge | &:0\:!v!:-1<
@./\$_\&+\^ |
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
| #Icon_and_Unicon | Icon and Unicon | procedure main()
local base, update, master, f, k
base := table()
base["name"] := "Rocket Skates"
base["price"] := 12.75
base["color"] := "yellow"
update := table()
update["price"] := 15.25
update["color"] := "red"
update["year"] := 1974
master := table()
every k := key((f := base | update)) do {
master[k] := f[k]
}
every k := key(master) do {
write(k, " = ", master[k])
}
end |
http://rosettacode.org/wiki/Associative_array/Merging | Associative array/Merging | Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:
Key
Value
"name"
"Rocket Skates"
"price"
15.25
"color"
"red"
"year"
1974
| #J | J |
merge=: ,. NB. use: update merge original
compress=: #"1~ ~:@:keys
keys=: {.
values=: {:
get=: [: > ((i.~ keys)~ <)~ { values@:] NB. key get (associative array)
pair=: [: |: <;._2;._2
|
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%)
| #Java | Java | import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class AverageLoopLength {
private static final int N = 100000;
//analytical(n) = sum_(i=1)^n (n!/(n-i)!/n**i)
private static double analytical(int n) {
double[] factorial = new double[n + 1];
double[] powers = new double[n + 1];
powers[0] = 1.0;
factorial[0] = 1.0;
for (int i = 1; i <= n; i++) {
factorial[i] = factorial[i - 1] * i;
powers[i] = powers[i - 1] * n;
}
double sum = 0;
//memoized factorial and powers
for (int i = 1; i <= n; i++) {
sum += factorial[n] / factorial[n - i] / powers[i];
}
return sum;
}
private static double average(int n) {
Random rnd = new Random();
double sum = 0.0;
for (int a = 0; a < N; a++) {
int[] random = new int[n];
for (int i = 0; i < n; i++) {
random[i] = rnd.nextInt(n);
}
Set<Integer> seen = new HashSet<>(n);
int current = 0;
int length = 0;
while (seen.add(current)) {
length++;
current = random[current];
}
sum += length;
}
return sum / N;
}
public static void main(String[] args) {
System.out.println(" N average analytical (error)");
System.out.println("=== ========= ============ =========");
for (int i = 1; i <= 20; i++) {
double avg = average(i);
double ana = analytical(i);
System.out.println(String.format("%3d %9.4f %12.4f (%6.2f%%)", i, avg, ana, ((ana - avg) / ana * 100)));
}
}
} |
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period.
It can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA().
The word stateful in the task description refers to the need for SMA() to remember certain information between calls to it:
The period, P
An ordered container of at least the last P numbers from each of its individual calls.
Stateful also means that successive calls to I(), the initializer, should return separate routines that do not share saved state so they could be used on two independent streams of data.
Pseudo-code for an implementation of SMA is:
function SMA(number: N):
stateful integer: P
stateful list: stream
number: average
stream.append_last(N)
if stream.length() > P:
# Only average the last P elements of the stream
stream.delete_first()
if stream.length() == 0:
average = 0
else:
average = sum( stream.values() ) / stream.length()
return average
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #R | R | #concat concatenates the new values to the existing vector of values, then discards any values that are too old.
lastvalues <- local(
{
values <- c();
function(x, len)
{
values <<- c(values, x);
lenv <- length(values);
if(lenv > len) values <<- values[(len-lenv):-1]
values
}
})
#moving.average accepts a numeric scalars input (and optionally a length, i.e. the number of values to retain) and calculates the stateful moving average.
moving.average <- function(latestvalue, len=3)
{
#Check that all inputs are numeric scalars
is.numeric.scalar <- function(x) is.numeric(x) && length(x)==1L
if(!is.numeric.scalar(latestvalue) || !is.numeric.scalar(len))
{
stop("all arguments must be numeric scalars")
}
#Calculate mean of variables so far
mean(lastvalues(latestvalue, len))
}
moving.average(5) # 5
moving.average(1) # 3
moving.average(-3) # 1
moving.average(8) # 2
moving.average(7) # 4 |
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.
| #F.23 | F# | // attractive_numbers.fsx
// taken from Primality by trial division
let rec primes =
let next_state s = Some(s, s + 2)
Seq.cache
(Seq.append
(seq[ 2; 3; 5 ])
(Seq.unfold next_state 7
|> Seq.filter is_prime))
and is_prime number =
let rec is_prime_core number current limit =
let cprime = primes |> Seq.item current
if cprime >= limit then true
elif number % cprime = 0 then false
else is_prime_core number (current + 1) (number/cprime)
if number = 2 then true
elif number < 2 then false
else is_prime_core number 0 number
// taken from Prime decomposition task and modified to add
let count_prime_divisors n =
let rec loop c n count =
let p = Seq.item n primes
if c < (p * p) then count
elif c % p = 0 then loop (c / p) n (count + 1)
else loop c (n + 1) count
loop n 0 1
let is_attractive = count_prime_divisors >> is_prime
let print_iter i n =
if i % 10 = 9
then printfn "%d" n
else printf "%d\t" n
[1..120]
|> List.filter is_attractive
|> List.iteri print_iter
|
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
| #jq | jq | # input: array of "h:m:s"
def mean_time_of_day:
def pi: 4 * (1|atan);
def to_radians: pi * . /(12*60*60);
def from_radians: (. * 12*60*60) / pi;
def secs2time: # produce "hh:mm:ss" string
def pad: tostring | (2 - length) * "0" + .;
"\(./60/60 % 24 | pad):\(./60 % 60 | pad):\(. % 60 | pad)";
def round:
if . < 0 then -1 * ((- .) | round) | if . == -0 then 0 else . end
else floor as $x
| if (. - $x) < 0.5 then $x else $x+1 end
end;
map( split(":")
| map(tonumber)
| (.[0]*3600 + .[1]*60 + .[2])
| to_radians )
| (map(sin) | add) as $y
| (map(cos) | add) as $x
| if $x == 0 then (if $y > 3e-14 then pi/2 elif $y < -3e-14 then -(pi/2) else null end)
else ($y / $x) | atan
end
| if . == null then null
else from_radians
| if (.<0) then . + (24*60*60) else . end
| round
| secs2time
end ; |
http://rosettacode.org/wiki/Averages/Mean_time_of_day | Averages/Mean time of day | Task[edit]
A particular activity of bats occurs at these times of the day:
23:00:17, 23:40:20, 00:12:45, 00:17:19
Using the idea that there are twenty-four hours in a day,
which is analogous to there being 360 degrees in a circle,
map times of day to and from angles;
and using the ideas of Averages/Mean angle
compute and show the average time of the nocturnal activity
to an accuracy of one second of time.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Julia | Julia | using Statistics
function meantime(times::Array, dlm::String=":")
c = π / (12 * 60 * 60)
a = map(x -> parse.(Int, x), split.(times, dlm))
ϕ = collect(3600t[1] + 60t[2] + t[3] for t in a)
d = angle(mean(exp.(c * im * ϕ))) / 2π # days
if d < 0 d += 1 end
# Convert to h:m:s
h = trunc(Int, d * 24)
m = trunc(Int, d * 24 * 60) - h * 60
s = trunc(Int, d * 24 * 60 * 60) - h * 60 * 60 - m * 60
return "$h:$m:$s"
end
times = String["23:00:17", "23:40:20", "00:12:45", "00:17:19"]
mtime = meantime(times)
println("Times:")
println.(times)
println("Mean: $mtime") |
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.
| #Kotlin | Kotlin | class AvlTree {
private var root: Node? = null
private class Node(var key: Int, var parent: Node?) {
var balance: Int = 0
var left : Node? = null
var right: Node? = null
}
fun insert(key: Int): Boolean {
if (root == null)
root = Node(key, null)
else {
var n: Node? = root
var parent: Node
while (true) {
if (n!!.key == key) return false
parent = n
val goLeft = n.key > key
n = if (goLeft) n.left else n.right
if (n == null) {
if (goLeft)
parent.left = Node(key, parent)
else
parent.right = Node(key, parent)
rebalance(parent)
break
}
}
}
return true
}
fun delete(delKey: Int) {
if (root == null) return
var n: Node? = root
var parent: Node? = root
var delNode: Node? = null
var child: Node? = root
while (child != null) {
parent = n
n = child
child = if (delKey >= n.key) n.right else n.left
if (delKey == n.key) delNode = n
}
if (delNode != null) {
delNode.key = n!!.key
child = if (n.left != null) n.left else n.right
if (0 == root!!.key.compareTo(delKey)) {
root = child
if (null != root) {
root!!.parent = null
}
} else {
if (parent!!.left == n)
parent.left = child
else
parent.right = child
if (null != child) {
child.parent = parent
}
rebalance(parent)
}
}
private fun rebalance(n: Node) {
setBalance(n)
var nn = n
if (nn.balance == -2)
if (height(nn.left!!.left) >= height(nn.left!!.right))
nn = rotateRight(nn)
else
nn = rotateLeftThenRight(nn)
else if (nn.balance == 2)
if (height(nn.right!!.right) >= height(nn.right!!.left))
nn = rotateLeft(nn)
else
nn = rotateRightThenLeft(nn)
if (nn.parent != null) rebalance(nn.parent!!)
else root = nn
}
private fun rotateLeft(a: Node): Node {
val b: Node? = a.right
b!!.parent = a.parent
a.right = b.left
if (a.right != null) a.right!!.parent = a
b.left = a
a.parent = b
if (b.parent != null) {
if (b.parent!!.right == a)
b.parent!!.right = b
else
b.parent!!.left = b
}
setBalance(a, b)
return b
}
private fun rotateRight(a: Node): Node {
val b: Node? = a.left
b!!.parent = a.parent
a.left = b.right
if (a.left != null) a.left!!.parent = a
b.right = a
a.parent = b
if (b.parent != null) {
if (b.parent!!.right == a)
b.parent!!.right = b
else
b.parent!!.left = b
}
setBalance(a, b)
return b
}
private fun rotateLeftThenRight(n: Node): Node {
n.left = rotateLeft(n.left!!)
return rotateRight(n)
}
private fun rotateRightThenLeft(n: Node): Node {
n.right = rotateRight(n.right!!)
return rotateLeft(n)
}
private fun height(n: Node?): Int {
if (n == null) return -1
return 1 + Math.max(height(n.left), height(n.right))
}
private fun setBalance(vararg nodes: Node) {
for (n in nodes) n.balance = height(n.right) - height(n.left)
}
fun printKey() {
printKey(root)
println()
}
private fun printKey(n: Node?) {
if (n != null) {
printKey(n.left)
print("${n.key} ")
printKey(n.right)
}
}
fun printBalance() {
printBalance(root)
println()
}
private fun printBalance(n: Node?) {
if (n != null) {
printBalance(n.left)
print("${n.balance} ")
printBalance(n.right)
}
}
}
fun main(args: Array<String>) {
val tree = AvlTree()
println("Inserting values 1 to 10")
for (i in 1..10) tree.insert(i)
print("Printing key : ")
tree.printKey()
print("Printing balance : ")
tree.printBalance()
} |
http://rosettacode.org/wiki/Averages/Mean_angle | Averages/Mean angle | When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle.
If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the second was of 10 degrees then the average of the numbers is 180 degrees, whereas if you can note that 350 degrees is equivalent to -10 degrees and so you have two readings at 10 degrees either side of zero degrees leading to a more fitting mean angle of zero degrees.
To calculate the mean angle of several angles:
Assume all angles are on the unit circle and convert them to complex numbers expressed in real and imaginary form.
Compute the mean of the complex numbers.
Convert the complex mean to polar coordinates whereupon the phase of the complex mean is the required angular mean.
(Note that, since the mean is the sum divided by the number of numbers, and division by a positive real number does not affect the angle, you can also simply compute the sum for step 2.)
You can alternatively use this formula:
Given the angles
α
1
,
…
,
α
n
{\displaystyle \alpha _{1},\dots ,\alpha _{n}}
the mean is computed by
α
¯
=
atan2
(
1
n
⋅
∑
j
=
1
n
sin
α
j
,
1
n
⋅
∑
j
=
1
n
cos
α
j
)
{\displaystyle {\bar {\alpha }}=\operatorname {atan2} \left({\frac {1}{n}}\cdot \sum _{j=1}^{n}\sin \alpha _{j},{\frac {1}{n}}\cdot \sum _{j=1}^{n}\cos \alpha _{j}\right)}
Task[edit]
write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle.
(You should use a built-in function if you have one that does this for degrees or radians).
Use the function to compute the means of these lists of angles (in degrees):
[350, 10]
[90, 180, 270, 360]
[10, 20, 30]
Show your output here.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #J | J | avgAngleD=: 360|(_1 { [: (**|)&.+.@(+/ % #)&.(*.inv) 1,.])&.(1r180p1&*) |
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
| #Java | Java | import java.util.Arrays;
public class AverageMeanAngle {
public static void main(String[] args) {
printAverageAngle(350.0, 10.0);
printAverageAngle(90.0, 180.0, 270.0, 360.0);
printAverageAngle(10.0, 20.0, 30.0);
printAverageAngle(370.0);
printAverageAngle(180.0);
}
private static void printAverageAngle(double... sample) {
double meanAngle = getMeanAngle(sample);
System.out.printf("The mean angle of %s is %s%n", Arrays.toString(sample), meanAngle);
}
public static double getMeanAngle(double... anglesDeg) {
double x = 0.0;
double y = 0.0;
for (double angleD : anglesDeg) {
double angleR = Math.toRadians(angleD);
x += Math.cos(angleR);
y += Math.sin(angleR);
}
double avgR = Math.atan2(y / anglesDeg.length, x / anglesDeg.length);
return Math.toDegrees(avgR);
}
} |
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
| #D | D | import std.stdio, std.algorithm;
T median(T)(T[] nums) pure nothrow {
nums.sort();
if (nums.length & 1)
return nums[$ / 2];
else
return (nums[$ / 2 - 1] + nums[$ / 2]) / 2.0;
}
void main() {
auto a1 = [5.1, 2.6, 6.2, 8.8, 4.6, 4.1];
writeln("Even median: ", a1.median);
auto a2 = [5.1, 2.6, 8.8, 4.6, 4.1];
writeln("Odd median: ", a2.median);
} |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of positive integers.
The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
A
(
x
1
,
…
,
x
n
)
=
x
1
+
⋯
+
x
n
n
{\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}}
The geometric mean is the
n
{\displaystyle n}
th root of the product of the list:
G
(
x
1
,
…
,
x
n
)
=
x
1
⋯
x
n
n
{\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}}
The harmonic mean is
n
{\displaystyle n}
divided by the sum of the reciprocal of each item in the list:
H
(
x
1
,
…
,
x
n
)
=
n
1
x
1
+
⋯
+
1
x
n
{\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Groovy | Groovy | def arithMean = { list ->
list == null \
? null \
: list.empty \
? 0 \
: list.sum() / list.size()
}
def geomMean = { list ->
list == null \
? null \
: list.empty \
? 1 \
: list.inject(1) { prod, item -> prod*item } ** (1 / list.size())
}
def harmMean = { list ->
list == null \
? null \
: list.empty \
? 0 \
: list.size() / list.collect { 1.0/it }.sum()
} |
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.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | frombt = FromDigits[StringCases[#, {"+" -> 1, "-" -> -1, "0" -> 0}],
3] &;
tobt = If[Quotient[#, 3, -1] == 0,
"", #0@Quotient[#, 3, -1]] <> (Mod[#,
3, -1] /. {1 -> "+", -1 -> "-", 0 -> "0"}) &;
btnegate = StringReplace[#, {"+" -> "-", "-" -> "+"}] &;
btadd = StringReplace[
StringJoin[
Fold[Sort@{#1[[1]],
Sequence @@ #2} /. {{x_, x_, x_} :> {x,
"0" <> #1[[2]]}, {"-", "+", x_} | {x_, "-", "+"} | {x_,
"0", "0"} :> {"0", x <> #1[[2]]}, {"+", "+", "0"} -> {"+",
"-" <> #1[[2]]}, {"-", "-", "0"} -> {"-",
"+" <> #1[[2]]}} &, {"0", ""},
Reverse@Transpose@PadLeft[Characters /@ {#1, #2}] /. {0 ->
"0"}]], StartOfString ~~ "0" .. ~~ x__ :> x] &;
btsubtract = btadd[#1, btnegate@#2] &;
btmultiply =
btadd[Switch[StringTake[#2, -1], "0", "0", "+", #1, "-",
btnegate@#1],
If[StringLength@#2 == 1,
"0", #0[#1, StringDrop[#2, -1]] <> "0"]] &; |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #PL.2FI | PL/I |
/* Babbage might have used a difference engine to compute squares. */
/* The algorithm used here uses only additions to form successive squares. */
/* Since there is no guarantee that the final square will not exceed a */
/* 32-bit integer word, modulus is formed to limit the magnitude of the */
/* squares, since we are really interested only in the last six digits of */
/* the square. */
Babbage_problem: procedure options (main); /* R. Vowels, 19 Dec. 2021 */
declare n fixed decimal (5);
declare (odd, sq) fixed binary (31);
odd = 3; sq = 4; /* the initial square is 4 */
do n = 3 to 99736;
odd = odd + 2;
sq = sq + odd; /* form the next square */
if sq >= 1000000 then sq = sq - 1000000; /* keep the remainder */
if sq = 269696 then leave;
end;
put ('The smallest number whose square ends in 269696 is ' || trim(n) );
put skip list ('The corresponding square is ' || trim (n*n) );
/* Even if the number had been 99736, n*n would not have overflowed */
/* because decimal arithmetic allows up to 15 decimal digits. */
end Babbage_problem;
|
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.
| #Factor | Factor | USING: formatting generalizations kernel math math.functions ;
100000000000000.01 100000000000000.011
100.01 100.011
10000000000000.001 10000.0 /f 1000000000.0000001000
0.001 0.0010000001
0.000000000000000000000101 0.0
2 sqrt dup * 2.0
2 sqrt dup neg * -2.0
3.14159265358979323846 3.14159265358979324
[ 2dup -1e-15 ~ "%+47.30f %+47.30f -1e-15 ~ : %u\n" printf ]
2 8 mnapply |
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.
| #Forth | Forth |
: test-f~ ( f1 f2 -- )
1e-18 \ epsilon
f~ \ AproximateEqual
if ." True" else ." False" then
;
|
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.
| #Fortran | Fortran | program main
implicit none
integer :: i
double precision, allocatable :: vals(:)
vals = [ 100000000000000.01d0, 100000000000000.011d0, &
& 100.01d0, 100.011d0, &
& 10000000000000.001d0/10000d0, 1000000000.0000001000d0, &
& 0.001d0, 0.0010000001d0, &
& 0.000000000000000000000101d0, 0d0, &
& sqrt(2d0)*sqrt(2d0), 2d0, &
& -sqrt(2d0)*sqrt(2d0), -2d0, &
& 3.14159265358979323846d0, 3.14159265358979324d0 ]
do i = 1, size(vals)/2
print '(ES30.18, A, ES30.18, A, L)', vals(2*i-1), ' == ', vals(2*i), ' ? ', eq_approx(vals(2*i-1), vals(2*i))
end do
contains
logical function eq_approx(a, b, reltol, abstol)
!! is a approximately equal b?
double precision, intent(in) :: a, b
!! values to compare
double precision, intent(in), optional :: reltol, abstol
!! relative and absolute error thresholds.
!! defaults: epsilon, smallest non-denormal number
double precision :: rt, at
rt = epsilon(1d0)
at = tiny(1d0)
if (present(reltol)) rt = reltol
if (present(abstol)) at = abstol
eq_approx = abs(a - b) .le. max(rt * max(abs(a), abs(b)), at)
return
end function
end program |
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #Ceylon | Ceylon | import com.vasileff.ceylon.random.api {
platformRandom,
Random
}
"""Run the example code for Rosetta Code ["Balanced brackets" task] (http://rosettacode.org/wiki/Balanced_brackets)."""
shared void run() {
value rnd = platformRandom();
for (len in (0..10)) {
value c = generate(rnd, len);
print("``c.padTrailing(20)`` - ``if (balanced(c)) then "OK" else "NOT OK" ``");
}
}
String generate(Random rnd, Integer count)
=> if (count == 0) then ""
else let(length = 2*count,
brackets = zipEntries(rnd.integers(length).take(length),
"[]".repeat(count))
.sort((a,b) => a.key<=>b.key)
.map(Entry.item))
String(brackets);
Boolean balanced(String input)
=> let (value ints = { for (c in input) if (c == '[') then 1 else -1 })
ints.filter((i) => i != 0)
.scan(0)(plus<Integer>)
.every((i) => i >= 0); |
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.
| #Ada | Ada |
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Strings.Bounded;
procedure Main is
package data_string is new Ada.Strings.Bounded.Generic_Bounded_Length(80);
use data_string;
type GCOSE_Rec is record
Full_Name : Bounded_String;
Office : Bounded_String;
Extension : Bounded_String;
Homephone : Bounded_String;
Email : Bounded_String;
end record;
type Password_Rec is record
Account : Bounded_String;
Password : Bounded_String;
Uid : Natural;
Gid : Natural;
GCOSE : GCOSE_Rec;
Directory : Bounded_String;
Shell : Bounded_String;
end record;
function To_String(Item : GCOSE_Rec) return String is
begin
return To_String(Item.Full_Name) & "," &
To_String(Item.Office) & "," &
To_String(Item.Extension) & "," &
To_String(Item.Homephone) & "," &
To_String(Item.Email);
end To_String;
function To_String(Item : Password_Rec) return String is
uid_str : string(1..4);
gid_str : string(1..4);
Temp : String(1..5);
begin
Temp := Item.Uid'Image;
uid_str := Temp(2..5);
Temp := Item.Gid'Image;
gid_str := Temp(2..5);
return To_String(Item.Account) & ":" &
To_String(Item.Password) & ":" &
uid_str & ":" & gid_str & ":" &
To_String(Item.GCOSE) & ":" &
To_String(Item.Directory) & ":" &
To_String(Item.Shell);
end To_String;
Pwd_List : array (1..3) of Password_Rec;
Filename : String := "password.txt";
The_File : File_Type;
Line : String(1..256);
Length : Natural;
begin
Pwd_List(1) := (Account => To_Bounded_String("jsmith"),
Password => To_Bounded_String("x"),
Uid => 1001, GID => 1000,
GCOSE => (Full_Name => To_Bounded_String("Joe Smith"),
Office => To_Bounded_String("Room 1007"),
Extension => To_Bounded_String("(234)555-8917"),
Homephone => To_Bounded_String("(234)555-0077"),
email => To_Bounded_String("[email protected]")),
directory => To_Bounded_String("/home/jsmith"),
shell => To_Bounded_String("/bin/bash"));
Pwd_List(2) := (Account => To_Bounded_String("jdoe"),
Password => To_Bounded_String("x"),
Uid => 1002, GID => 1000,
GCOSE => (Full_Name => To_Bounded_String("Jane Doe"),
Office => To_Bounded_String("Room 1004"),
Extension => To_Bounded_String("(234)555-8914"),
Homephone => To_Bounded_String("(234)555-0044"),
email => To_Bounded_String("[email protected]")),
directory => To_Bounded_String("/home/jdoe"),
shell => To_Bounded_String("/bin/bash"));
Pwd_List(3) := (Account => To_Bounded_String("xyz"),
Password => To_Bounded_String("x"),
Uid => 1003, GID => 1000,
GCOSE => (Full_Name => To_Bounded_String("X Yz"),
Office => To_Bounded_String("Room 1003"),
Extension => To_Bounded_String("(234)555-8913"),
Homephone => To_Bounded_String("(234)555-0033"),
email => To_Bounded_String("[email protected]")),
directory => To_Bounded_String("/home/xyz"),
shell => To_Bounded_String("/bin/bash"));
Create(File => The_File,
Mode => Out_File,
Name => Filename);
for I in 1..2 loop
Put_Line(File => The_File,
Item => To_String(Pwd_List(I)));
end loop;
Reset(File => The_File,
Mode => In_File);
while not End_Of_File(The_File) loop
Get_Line(File => The_File,
Item => Line,
Last => Length);
Put_Line(Line(1..Length));
end loop;
New_Line;
Reset(File => The_File,
Mode => Append_File);
Put_Line(File => The_File,
Item => To_String(Pwd_List(3)));
Reset(File => The_File,
Mode => In_File);
while not End_Of_File(The_File) loop
Get_Line(File => The_File,
Item => Line,
Last => Length);
Put_Line(Line(1..Length));
end loop;
Close(The_File);
end 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
| #ActionScript | ActionScript | var map:Object = {key1: "value1", key2: "value2"};
trace(map['key1']); // outputs "value1"
// Dot notation can also be used
trace(map.key2); // outputs "value2"
// More keys and values can then be added
map['key3'] = "value3";
trace(map['key3']); // outputs "value3" |
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
| #11l | 11l | V max_divisors = 0
V c = 0
V n = 1
L
V divisors = 1
L(i) 1 .. n I/ 2
I n % i == 0
divisors++
I divisors > max_divisors
max_divisors = divisors
print(n, end' ‘ ’)
c++
I c == 20
L.break
n++ |
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.
| #Erlang | Erlang | [1,2,3,4,5,6,7,8,9,10] = 55
[1,3,4,7,2,5,13,8,4,8] = 55
[6,13,6,0,8,3,1,0,8,10] = 55
[8,0,9,0,5,9,8,8,8,0] = 55
[8,11,9,3,1,12,8,0,0,3] = 55
[13,4,3,8,1,5,10,4,5,2] = 55
[6,6,9,5,6,5,6,1,5,6] = 55
[20,7,5,0,5,0,0,10,8,0] = 55
[2,10,0,10,0,4,8,3,15,3] = 55
[0,11,7,0,4,16,7,0,10,0] = 55
|
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.
| #Euphoria | Euphoria | function move(sequence s, integer amount, integer src, integer dest)
if src < 1 or src > length(s) or dest < 1 or dest > length(s) or amount < 0 then
return -1
else
if src != dest and amount then
if amount > s[src] then
amount = s[src]
end if
s[src] -= amount
s[dest] += amount
end if
return s
end if
end function
sequence buckets
buckets = repeat(100,10)
procedure equalize()
integer i, j, diff
while 1 do
i = rand(length(buckets))
j = rand(length(buckets))
diff = buckets[i] - buckets[j]
if diff >= 2 then
buckets = move(buckets, floor(diff / 2), i, j)
elsif diff <= -2 then
buckets = move(buckets, -floor(diff / 2), j, i)
end if
task_yield()
end while
end procedure
procedure redistribute()
integer i, j
while 1 do
i = rand(length(buckets))
j = rand(length(buckets))
if buckets[i] then
buckets = move(buckets, rand(buckets[i]), i, j)
end if
task_yield()
end while
end procedure
function sum(sequence s)
integer sum
sum = 0
for i = 1 to length(s) do
sum += s[i]
end for
return sum
end function
atom task
task = task_create(routine_id("equalize"), {})
task_schedule(task, 1)
task = task_create(routine_id("redistribute"), {})
task_schedule(task, 1)
task_schedule(0, {0.5, 0.5})
for i = 1 to 24 do
print(1,buckets)
printf(1," sum: %d\n", {sum(buckets)})
task_yield()
end for |
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.
| #Component_Pascal | Component Pascal |
MODULE Assertions;
VAR
x: INTEGER;
PROCEDURE DoIt*;
BEGIN
x := 41;
ASSERT(x = 42);
END DoIt;
END Assertions.
Assertions.DoIt
|
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.
| #Crystal | Crystal | class AssertionError < Exception
end
def assert(predicate : Bool, msg = "The asserted condition was false")
raise AssertionError.new(msg) unless predicate
end
assert(12 == 42, "It appears that 12 doesn't equal 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.
| #D | D | import std.exception: enforce;
int foo(in bool condition) pure nothrow
in {
// Assertions are used in contract programming.
assert(condition);
} out(result) {
assert(result > 0);
} body {
if (condition)
return 42;
// assert(false) is never stripped from the code, it generates an
// error in debug builds, and it becomes a HALT instruction in
// -release mode.
//
// It's used as a mark by the D type system. If you remove this
// line the compiles gives an error:
//
// Error: function assertions.foo no return exp;
// or assert(0); at end of function
assert(false, "This can't happen.");
}
void main() pure {
int x = foo(true);
// A regular assertion, it throws an error.
// Use -release to disable it.
// It can be used in nothrow functions.
assert(x == 42, "x is not 42");
// This throws an exception and it can't be disabled.
// There are some different versions of this lazy function.
enforce(x == 42, "x is not 42");
} |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #8th | 8th |
[ 1 , 2, 3 ]
' n:sqr
a:map
|
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.
| #ACL2 | ACL2 | (defun apply-to-each (xs)
(if (endp xs)
nil
(cons (fn-to-apply (first xs))
(sq-each (rest xs)))))
(defun fn-to-apply (x)
(* x x))
|
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
| #Lasso | Lasso | define getmode(a::array)::array => {
local(mmap = map, maxv = 0, modes = array)
// store counts
with e in #a do => { #mmap->keys >> #e ? #mmap->find(#e) += 1 | #mmap->insert(#e = 1) }
// get max value
with e in #mmap->keys do => { #mmap->find(#e) > #maxv ? #maxv = #mmap->find(#e) }
// get modes with max value
with e in #mmap->keys where #mmap->find(#e) == #maxv do => { #modes->insert(#e) }
return #modes
}
getmode(array(1,3,6,6,6,6,7,7,12,12,17))
getmode(array(1,3,6,3,4,8,9,1,2,3,2,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
| #Liberty_BASIC | Liberty BASIC |
a$ = "1 3 6 6 6 6 7 7 12 12 17"
b$ = "1 2 4 4 1"
print "Modes for ";a$
print modes$(a$)
print "Modes for ";b$
print modes$(b$)
function modes$(a$)
'get array size
n=0
t$ = "*"
while t$<>""
n=n+1
t$=word$(a$, n)
'print n, t$
wend
n=n-1
'print "n=", n
'dim array
'read in array
redim a(n)
for i = 1 to n
a(i)=val(word$(a$, i))
'print i, a(i)
next
'sort
sort a(), 1, n
'get the modes
occurence = 1
maxOccurence = 0
oldVal = a(1)
modes$ = ""
for i = 2 to n
'print i, a(i)
if a(i) = oldVal then
occurence = occurence + 1
else
select case
case occurence > maxOccurence
maxOccurence = occurence
modes$ = oldVal; " "
case occurence = maxOccurence
modes$ = modes$; oldVal; " "
end select
occurence = 1
end if
oldVal = a(i)
next
'check after loop
select case
case occurence > maxOccurence
maxOccurence = occurence
modes$ = oldVal; " "
case occurence = maxOccurence
modes$ = modes$; oldVal; " "
end select
end function |
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
| #AWK | AWK | BEGIN {
a["hello"] = 1
a["world"] = 2
a["!"] = 3
# iterate over keys, undefined order
for(key in a) {
print key, a[key]
}
} |
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
| #Babel | Babel | births (('Washington' 1732) ('Lincoln' 1809) ('Roosevelt' 1882) ('Kennedy' 1917)) ls2map ! < |
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]
| #C.23 | C# | using System;
namespace ApplyDigitalFilter {
class Program {
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 = 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) {
Console.Write("{0,11:F8}", result[i]);
Console.Write((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
| #blz | blz |
:mean(vec)
vec.fold_left(0, (x, y -> x + y)) / vec.length()
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
| #Bracmat | Bracmat |
(mean1=
sum length n
. 0:?sum:?length
& whl
' ( !arg:%?n ?arg
& 1+!length:?length
& !n+!sum:?sum
)
& !sum*!length^-1
);
(mean2=
sum length n
. 0:?sum:?length
& !arg
: ?
( #%@?n
& 1+!length:?length
& !n+!sum:?sum
& ~
)
?
| !sum*!length^-1
);
|
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
| #Java | Java | import java.util.*;
class MergeMaps {
public static void main(String[] args) {
Map<String, Object> base = new HashMap<>();
base.put("name", "Rocket Skates");
base.put("price", 12.75);
base.put("color", "yellow");
Map<String, Object> update = new HashMap<>();
update.put("price", 15.25);
update.put("color", "red");
update.put("year", 1974);
Map<String, Object> result = new HashMap<>(base);
result.putAll(update);
System.out.println(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
| #JavaScript | JavaScript | (() => {
'use strict';
console.log(JSON.stringify(
Object.assign({}, // Fresh dictionary.
{ // Base.
"name": "Rocket Skates",
"price": 12.75,
"color": "yellow"
}, { // Update.
"price": 15.25,
"color": "red",
"year": 1974
}
),
null, 2
))
})(); |
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%)
| #Julia | Julia | using Printf
analytical(n::Integer) = sum(factorial(n) / big(n) ^ i / factorial(n - i) for i = 1:n)
function test(n::Integer, times::Integer = 1000000)
c = 0
for i = range(0, times)
x, bits = 1, 0
while (bits & x) == 0
c += 1
bits |= x
x = 1 << rand(0:(n - 1))
end
end
return c / times
end
function main(n::Integer)
println(" n\tavg\texp.\tdiff\n-------------------------------")
for n in 1:n
avg = test(n)
theory = analytical(n)
diff = (avg / theory - 1) * 100
@printf(STDOUT, "%2d %8.4f %8.4f %6.3f%%\n", n, avg, theory, diff)
end
end
main(20)
|
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%)
| #Kotlin | Kotlin | const val NMAX = 20
const val TESTS = 1000000
val rand = java.util.Random()
fun avg(n: Int): Double {
var sum = 0
for (t in 0 until TESTS) {
val v = BooleanArray(NMAX)
var x = 0
while (!v[x]) {
v[x] = true
sum++
x = rand.nextInt(n)
}
}
return sum.toDouble() / TESTS
}
fun ana(n: Int): Double {
val nn = n.toDouble()
var term = 1.0
var sum = 1.0
for (i in n - 1 downTo 1) {
term *= i / nn
sum += term
}
return sum
}
fun main(args: Array<String>) {
println(" N average analytical (error)")
println("=== ========= ============ =========")
for (n in 1..NMAX) {
val a = avg(n)
val b = ana(n)
println(String.format("%3d %6.4f %10.4f (%4.2f%%)", n, a, b, Math.abs(a - b) / b * 100.0))
}
} |
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period.
It can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA().
The word stateful in the task description refers to the need for SMA() to remember certain information between calls to it:
The period, P
An ordered container of at least the last P numbers from each of its individual calls.
Stateful also means that successive calls to I(), the initializer, should return separate routines that do not share saved state so they could be used on two independent streams of data.
Pseudo-code for an implementation of SMA is:
function SMA(number: N):
stateful integer: P
stateful list: stream
number: average
stream.append_last(N)
if stream.length() > P:
# Only average the last P elements of the stream
stream.delete_first()
if stream.length() == 0:
average = 0
else:
average = sum( stream.values() ) / stream.length()
return average
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Racket | Racket | #lang racket
(require data/queue)
(define (simple-moving-average period)
(define queue (make-queue))
(define sum 0.0)
(lambda (x)
(enqueue! queue x)
(set! sum (+ sum x))
(when (> (queue-length queue) period)
(set! sum (- sum (dequeue! queue))))
(/ sum (queue-length queue))))
;; Tests
(define sma3 (simple-moving-average 3))
(define sma5 (simple-moving-average 5))
(for/lists (lst1 lst2)
([i '(1 2 3 4 5 5 4 3 2 1)])
(values (sma3 i) (sma5 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.
| #Factor | Factor | USING: formatting grouping io math.primes math.primes.factors
math.ranges sequences ;
"The attractive numbers up to and including 120 are:" print
120 [1,b] [ factors length prime? ] filter 20 <groups>
[ [ "%4d" printf ] each nl ] each |
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.
| #Fortran | Fortran |
program attractive_numbers
use iso_fortran_env, only: output_unit
implicit none
integer, parameter :: maximum=120, line_break=20
integer :: i, counter
write(output_unit,'(A,x,I0,x,A)') "The attractive numbers up to and including", maximum, "are:"
counter = 0
do i = 1, maximum
if (is_prime(count_prime_factors(i))) then
write(output_unit,'(I0,x)',advance="no") i
counter = counter + 1
if (modulo(counter, line_break) == 0) write(output_unit,*)
end if
end do
write(output_unit,*)
contains
pure function is_prime(n)
integer, intent(in) :: n
logical :: is_prime
integer :: d
is_prime = .false.
d = 5
if (n < 2) return
if (modulo(n, 2) == 0) then
is_prime = n==2
return
end if
if (modulo(n, 3) == 0) then
is_prime = n==3
return
end if
do
if (d**2 > n) then
is_prime = .true.
return
end if
if (modulo(n, d) == 0) then
is_prime = .false.
return
end if
d = d + 2
if (modulo(n, d) == 0) then
is_prime = .false.
return
end if
d = d + 4
end do
is_prime = .true.
end function is_prime
pure function count_prime_factors(n)
integer, intent(in) :: n
integer :: count_prime_factors
integer :: i, f
count_prime_factors = 0
if (n == 1) return
if (is_prime(n)) then
count_prime_factors = 1
return
end if
count_prime_factors = 0
f = 2
i = n
do
if (modulo(i, f) == 0) then
count_prime_factors = count_prime_factors + 1
i = i/f
if (i == 1) exit
if (is_prime(i)) f = i
else if (f >= 3) then
f = f + 2
else
f = 3
end if
end do
end function count_prime_factors
end program attractive_numbers
|
http://rosettacode.org/wiki/Averages/Mean_time_of_day | Averages/Mean time of day | Task[edit]
A particular activity of bats occurs at these times of the day:
23:00:17, 23:40:20, 00:12:45, 00:17:19
Using the idea that there are twenty-four hours in a day,
which is analogous to there being 360 degrees in a circle,
map times of day to and from angles;
and using the ideas of Averages/Mean angle
compute and show the average time of the nocturnal activity
to an accuracy of one second of time.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Kotlin | Kotlin | // version 1.0.6
fun meanAngle(angles: DoubleArray): Double {
val sinSum = angles.sumByDouble { Math.sin(it * Math.PI / 180.0) }
val cosSum = angles.sumByDouble { Math.cos(it * Math.PI / 180.0) }
return Math.atan2(sinSum / angles.size, cosSum / angles.size) * 180.0 / Math.PI
}
/* time string assumed to be in format "hh:mm:ss" */
fun timeToSecs(t: String): Int {
val hours = t.slice(0..1).toInt()
val mins = t.slice(3..4).toInt()
val secs = t.slice(6..7).toInt()
return 3600 * hours + 60 * mins + secs
}
/* 1 second of time = 360/(24 * 3600) = 1/240th degree */
fun timeToDegrees(t: String): Double = timeToSecs(t) / 240.0
fun degreesToTime(d: Double): String {
var dd = d
if (dd < 0.0) dd += 360.0
var secs = (dd * 240.0).toInt()
val hours = secs / 3600
var mins = secs % 3600
secs = mins % 60
mins /= 60
return String.format("%2d:%2d:%2d", hours, mins, secs)
}
fun main(args: Array<String>) {
val tm = arrayOf("23:00:17", "23:40:20", "00:12:45", "00:17:19")
val angles = DoubleArray(4) { timeToDegrees(tm[it]) }
val mean = meanAngle(angles)
println("Average time is : ${degreesToTime(mean)}")
} |
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.
| #Lua | Lua | AVL={balance=0}
AVL.__mt={__index = AVL}
function AVL:new(list)
local o={}
setmetatable(o, AVL.__mt)
for _,v in ipairs(list or {}) do
o=o:insert(v)
end
return o
end
function AVL:rebalance()
local rotated=false
if self.balance>1 then
if self.right.balance<0 then
self.right, self.right.left.right, self.right.left = self.right.left, self.right, self.right.left.right
self.right.right.balance=self.right.balance>-1 and 0 or 1
self.right.balance=self.right.balance>0 and 2 or 1
end
self, self.right.left, self.right = self.right, self, self.right.left
self.left.balance=1-self.balance
self.balance=self.balance==0 and -1 or 0
rotated=true
elseif self.balance<-1 then
if self.left.balance>0 then
self.left, self.left.right.left, self.left.right = self.left.right, self.left, self.left.right.left
self.left.left.balance=self.left.balance<1 and 0 or -1
self.left.balance=self.left.balance<0 and -2 or -1
end
self, self.left.right, self.left = self.left, self, self.left.right
self.right.balance=-1-self.balance
self.balance=self.balance==0 and 1 or 0
rotated=true
end
return self,rotated
end
function AVL:insert(v)
if not self.value then
self.value=v
self.balance=0
return self,1
end
local grow
if v==self.value then
return self,0
elseif v<self.value then
if not self.left then self.left=self:new() end
self.left,grow=self.left:insert(v)
self.balance=self.balance-grow
else
if not self.right then self.right=self:new() end
self.right,grow=self.right:insert(v)
self.balance=self.balance+grow
end
self,rotated=self:rebalance()
return self, (rotated or self.balance==0) and 0 or grow
end
function AVL:delete_move(dir,other,mul)
if self[dir] then
local sb2,v
self[dir], sb2, v=self[dir]:delete_move(dir,other,mul)
self.balance=self.balance+sb2*mul
self,sb2=self:rebalance()
return self,(sb2 or self.balance==0) and -1 or 0,v
else
return self[other],-1,self.value
end
end
function AVL:delete(v,isSubtree)
local grow=0
if v==self.value then
local v
if self.balance>0 then
self.right,grow,v=self.right:delete_move("left","right",-1)
elseif self.left then
self.left,grow,v=self.left:delete_move("right","left",1)
grow=-grow
else
return not isSubtree and AVL:new(),-1
end
self.value=v
self.balance=self.balance+grow
elseif v<self.value and self.left then
self.left,grow=self.left:delete(v,true)
self.balance=self.balance-grow
elseif v>self.value and self.right then
self.right,grow=self.right:delete(v,true)
self.balance=self.balance+grow
else
return self,0
end
self,rotated=self:rebalance()
return self, grow~=0 and (rotated or self.balance==0) and -1 or 0
end
-- output functions
function AVL:toList(list)
if not self.value then return {} end
list=list or {}
if self.left then self.left:toList(list) end
list[#list+1]=self.value
if self.right then self.right:toList(list) end
return list
end
function AVL:dump(depth)
if not self.value then return end
depth=depth or 0
if self.right then self.right:dump(depth+1) end
print(string.rep(" ",depth)..self.value.." ("..self.balance..")")
if self.left then self.left:dump(depth+1) end
end
-- test
local test=AVL:new{1,10,5,15,20,3,5,14,7,13,2,8,3,4,5,10,9,8,7}
test:dump()
print("\ninsert 17:")
test=test:insert(17)
test:dump()
print("\ndelete 10:")
test=test:delete(10)
test:dump()
print("\nlist:")
print(unpack(test:toList()))
|
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
| #JavaScript | JavaScript | function sum(a) {
var s = 0;
for (var i = 0; i < a.length; i++) s += a[i];
return s;
}
function degToRad(a) {
return Math.PI / 180 * a;
}
function meanAngleDeg(a) {
return 180 / Math.PI * Math.atan2(
sum(a.map(degToRad).map(Math.sin)) / a.length,
sum(a.map(degToRad).map(Math.cos)) / a.length
);
}
var a = [350, 10], b = [90, 180, 270, 360], c = [10, 20, 30];
console.log(meanAngleDeg(a));
console.log(meanAngleDeg(b));
console.log(meanAngleDeg(c)); |
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
| #Delphi | Delphi | program AveragesMedian;
{$APPTYPE CONSOLE}
uses Generics.Collections, Types;
function Median(aArray: TDoubleDynArray): Double;
var
lMiddleIndex: Integer;
begin
TArray.Sort<Double>(aArray);
lMiddleIndex := Length(aArray) div 2;
if Odd(Length(aArray)) then
Result := aArray[lMiddleIndex]
else
Result := (aArray[lMiddleIndex - 1] + aArray[lMiddleIndex]) / 2;
end;
begin
Writeln(Median(TDoubleDynArray.Create(4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2)));
Writeln(Median(TDoubleDynArray.Create(4.1, 7.2, 1.7, 9.3, 4.4, 3.2)));
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
| #Haskell | Haskell | import Data.List (genericLength)
import Control.Monad (zipWithM_)
mean :: Double -> [Double] -> Double
mean 0 xs = product xs ** (1 / genericLength xs)
mean p xs = (1 / genericLength xs * sum (map (** p) xs)) ** (1/p)
main = do
let ms = zipWith ((. flip mean [1..10]). (,)) "agh" [1, 0, -1]
mapM_ (\(t,m) -> putStrLn $ t : ": " ++ show m) ms
putStrLn $ " a >= g >= h is " ++ show ((\(_,[a,g,h])-> a>=g && g>=h) (unzip ms)) |
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.
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | ЗН П2 Вx |x| П0 0 П3 П4 1 П5
ИП0 /-/ x<0 80
ИП0 ^ ^ 3 / [x] П0 3 * - П1
ИП3 x#0 54
ИП1 x=0 38 ИП2 ПП 88 0 П3 БП 10
ИП1 1 - x=0 49 ИП2 /-/ ПП 88 БП 10
0 ПП 88 БП 10
ИП1 x=0 62 0 ПП 88 БП 10
ИП1 1 - x=0 72 ИП2 ПП 88 БП 10
ИП2 /-/ ПП 88 1 П3 БП 10
ИП3 x#0 86 ИП2 ПП 88 ИП4 С/П
8 + ИП5 * ИП4 + П4 ИП5 1 0 * П5 В/О |
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.
| #PowerShell | PowerShell |
###########################################################################################
#
# Definitions:
#
# Lines that begin with the "#" symbol are comments: they will be ignored by the machine.
#
# -----------------------------------------------------------------------------------------
#
# While
#
# Run a command block based on the results of a conditional test.
#
# Syntax
# while (condition) {command_block}
#
# Key
#
# condition If this evaluates to TRUE the loop {command_block} runs.
# when the loop has run once the condition is evaluated again.
#
# command_block Commands to run each time the loop repeats.
#
# As long as the condition remains true, PowerShell reruns the {command_block} section.
#
# -----------------------------------------------------------------------------------------
#
# * means 'multiplied by'
# % means 'modulo', or remainder after division
# -ne means 'is not equal to'
# ++ means 'increment variable by one'
#
###########################################################################################
# Declare a variable, $integer, with a starting value of 0.
$integer = 0
while (($integer * $integer) % 1000000 -ne 269696)
{
$integer++
}
# Show the result.
$integer
|
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.
| #FreeBASIC | FreeBASIC | #include "string.bi"
Dim Shared As Double epsilon = 1
Sub eq_approx(a As Double,b As Double)
Dim As Boolean tmp = Abs(a - b) < epsilon
Print Using "& & &";tmp;a;b
End Sub
While (1 + epsilon <> 1)
epsilon /= 2
Wend
Print "epsilon = "; Format(epsilon, "0.000000000000000e-00")
Print
eq_approx(100000000000000.01, 100000000000000.011)
eq_approx(100.01, 100.011)
eq_approx(10000000000000.001/10000.0, 1000000000.0000001000)
eq_approx(0.001, 0.0010000001)
eq_approx(0.000000000000000000000101, 0.0)
eq_approx(Sqr(2)*Sqr(2), 2.0)
eq_approx(-Sqr(2)*Sqr(2), -2.0)
eq_approx(3.14159265358979323846, 3.14159265358979324)
Sleep |
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.
| #Go | Go | package main
import (
"fmt"
"log"
"math/big"
)
func max(a, b *big.Float) *big.Float {
if a.Cmp(b) > 0 {
return a
}
return b
}
func isClose(a, b *big.Float) bool {
relTol := big.NewFloat(1e-9) // same as default for Python's math.isclose() function
t := new(big.Float)
t.Sub(a, b)
t.Abs(t)
u, v, w := new(big.Float), new(big.Float), new(big.Float)
u.Mul(relTol, max(v.Abs(a), w.Abs(b)))
return t.Cmp(u) <= 0
}
func nbf(s string) *big.Float {
n, ok := new(big.Float).SetString(s)
if !ok {
log.Fatal("invalid floating point number")
}
return n
}
func main() {
root2 := big.NewFloat(2.0)
root2.Sqrt(root2)
pairs := [][2]*big.Float{
{nbf("100000000000000.01"), nbf("100000000000000.011")},
{nbf("100.01"), nbf("100.011")},
{nbf("0").Quo(nbf("10000000000000.001"), nbf("10000.0")), nbf("1000000000.0000001000")},
{nbf("0.001"), nbf("0.0010000001")},
{nbf("0.000000000000000000000101"), nbf("0.0")},
{nbf("0").Mul(root2, root2), nbf("2.0")},
{nbf("0").Mul(nbf("0").Neg(root2), root2), nbf("-2.0")},
{nbf("100000000000000003.0"), nbf("100000000000000004.0")},
{nbf("3.14159265358979323846"), nbf("3.14159265358979324")},
}
for _, pair := range pairs {
s := "≉"
if isClose(pair[0], pair[1]) {
s = "≈"
}
fmt.Printf("% 21.19g %s %- 21.19g\n", pair[0], s, pair[1])
}
} |
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #Clojure | Clojure | (defn gen-brackets [n]
(->> (concat (repeat n \[) (repeat n \]))
shuffle
(apply str ,)))
(defn balanced? [s]
(loop [[first & coll] (seq s)
stack '()]
(if first
(if (= first \[)
(recur coll (conj stack \[))
(when (= (peek stack) \[)
(recur coll (pop stack))))
(zero? (count stack))))) |
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.
| #AWK | AWK |
# syntax: GAWK -f APPEND_A_RECORD_TO_THE_END_OF_A_TEXT_FILE.AWK
BEGIN {
fn = "\\etc\\passwd"
# create and populate file
print("account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell") >fn
print("jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash") >fn
print("jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash") >fn
close(fn)
show_file("initial file")
# append record
print("xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash") >>fn
close(fn)
show_file("file after append")
exit(0)
}
function show_file(desc, nr,rec) {
printf("%s:\n",desc)
while (getline rec <fn > 0) {
nr++
printf("%s\n",rec)
}
close(fn)
printf("%d records\n\n",nr)
}
|
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
| #Ada | Ada | with Ada.Containers.Ordered_Maps;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO;
procedure Associative_Array is
-- Instantiate the generic package Ada.Containers.Ordered_Maps
package Associative_Int is new Ada.Containers.Ordered_Maps(Unbounded_String, Integer);
use Associative_Int;
Color_Map : Map;
Color_Cursor : Cursor;
Success : Boolean;
Value : Integer;
begin
-- Add values to the ordered map
Color_Map.Insert(To_Unbounded_String("Red"), 10, Color_Cursor, Success);
Color_Map.Insert(To_Unbounded_String("Blue"), 20, Color_Cursor, Success);
Color_Map.Insert(To_Unbounded_String("Yellow"), 5, Color_Cursor, Success);
-- retrieve values from the ordered map and print the value and key
-- to the screen
Value := Color_Map.Element(To_Unbounded_String("Red"));
Ada.Text_Io.Put_Line("Red:" & Integer'Image(Value));
Value := Color_Map.Element(To_Unbounded_String("Blue"));
Ada.Text_IO.Put_Line("Blue:" & Integer'Image(Value));
Value := Color_Map.Element(To_Unbounded_String("Yellow"));
Ada.Text_IO.Put_Line("Yellow:" & Integer'Image(Value));
end Associative_Array; |
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
| #8086_Assembly | 8086 Assembly | puts: equ 9 ; MS-DOS print string syscall
amount: equ 20 ; Amount of antiprimes to find
cpu 8086
org 100h
xor si,si ; SI = current number
xor cx,cx ; CH = max # of factors, CL = # of antiprimes
cand: inc si
mov di,si ; DI = maximum factor to test
shr di,1
mov bp,1 ; BP = current candidate
xor bl,bl ; BL = factor count
.test: mov ax,si ; Test current candidate
xor dx,dx
div bp
test dx,dx ; Evenly divisible?
jnz .next
inc bx ; Then increment factors
.next: inc bp ; Next possible factor
cmp bp,si ; Are we there yet?
jbe .test ; If not, try next factor
cmp bl,ch ; Is it an antiprime?
jbe cand ; If not, next candidate
inc cx ; If so, increment the amount of antiprimes seen
mov ch,bl ; Update maximum amount of factors
mov bx,nbuf ; Convert current number to ASCII
mov ax,si
mov di,10
digit: xor dx,dx ; Extract a digit
div di
add dl,'0' ; Add ASCII 0
dec bx
mov [bx],dl ; Store it
test ax,ax ; Any more digits?
jnz digit ; If so, get next digit
mov dx,bx
mov ah,puts
int 21h ; Print using MS-DOS
cmp cl,amount ; Do we need any more antiprimes?
jb cand ; If so, find the next one
ret ; Otherwise, back to DOS
db '.....' ; Placeholder for decimal output
nbuf: db ' $' |
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.
| #F.23 | F# |
open System.Threading
type Buckets(n) =
let rand = System.Random()
let mutex = Array.init n (fun _ -> new Mutex())
let bucket = Array.init n (fun _ -> 100)
member this.Count = n
member this.Item n = bucket.[n]
member private this.Lock is k =
let is = Seq.sort is
for i in is do
mutex.[i].WaitOne() |> ignore
try k() finally
for i in is do
mutex.[i].ReleaseMutex()
member this.Transfer i j d =
if i <> j && d <> 0 then
let i, j, d = if d > 0 then i, j, d else j, i, -d
this.Lock [i; j] (fun () ->
let d = min d bucket.[i]
bucket.[i] <- bucket.[i] - d
bucket.[j] <- bucket.[j] + d)
member this.Read =
this.Lock [0..n-1] (fun () -> Array.copy bucket)
member this.Print() =
let xs = this.Read
printf "%A = %d\n" xs (Seq.sum xs)
interface System.IDisposable with
member this.Dispose() =
for m in mutex do
(m :> System.IDisposable).Dispose()
let transfers = ref 0
let max_transfers = 1000000
let rand_pair (rand: System.Random) n =
let i, j = rand.Next n, rand.Next(n-1)
i, if j<i then j else j+1
let equalizer (bucket: Buckets) () =
let rand = System.Random()
while System.Threading.Interlocked.Increment transfers < max_transfers do
let i, j = rand_pair rand bucket.Count
let d = (bucket.[i] - bucket.[j]) / 2
if d > 0 then
bucket.Transfer i j d
else
bucket.Transfer j i -d
let randomizer (bucket: Buckets) () =
let rand = System.Random()
while System.Threading.Interlocked.Increment transfers < max_transfers do
let i, j = rand_pair rand bucket.Count
let d = 1 + rand.Next bucket.[i]
bucket.Transfer i j d
do
use bucket = new Buckets(10)
let equalizer = Thread(equalizer bucket)
let randomizer = Thread(randomizer bucket)
bucket.Print()
equalizer.Start()
randomizer.Start()
while !transfers < max_transfers do
Thread.Sleep 100
bucket.Print()
|
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.
| #Dart | Dart |
main() {
var i = 42;
assert( i == 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.
| #Delphi | Delphi | Assert(a = 42); |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #DWScript | DWScript | Assert(a = 42, 'Not 42!'); |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #ActionScript | ActionScript | package
{
public class ArrayCallback
{
public function main():void
{
var nums:Array = new Array(1, 2, 3);
nums.map(function(n:Number, index:int, arr:Array):void { trace(n * n * n); });
// You can also pass a function reference
nums.map(cube);
}
private function cube(n:Number, index:int, arr:Array):void
{
trace(n * n * n);
}
}
} |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Lua | Lua | function mode(tbl) -- returns table of modes and count
assert(type(tbl) == 'table')
local counts = { }
for _, val in pairs(tbl) do
-- see http://lua-users.org/wiki/TernaryOperator
counts[val] = counts[val] and counts[val] + 1 or 1
end
local modes = { }
local modeCount = 0
for key, val in pairs(counts) do
if val > modeCount then
modeCount = val
modes = {key}
elseif val == modeCount then
table.insert(modes, key)
end
end
return modes, modeCount
end
modes, count = mode({1,3,6,6,6,6,7,7,12,12,17})
for _, val in pairs(modes) do io.write(val..' ') end
print("occur(s) ", count, " times")
modes, count = mode({'a', 'a', 'b', 'd', 'd'})
for _, val in pairs(modes) do io.write(val..' ') end
print("occur(s) ", count, " times")
|
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
| #BaCon | BaCon | DECLARE associative ASSOC STRING
associative("abc") = "first three"
associative("mn") = "middle two"
associative("xyz") = "last three"
LOOKUP associative TO keys$ SIZE amount
FOR i = 0 TO amount - 1
PRINT keys$[i], ":", associative(keys$[i])
NEXT |
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]
| #C.2B.2B | C++ | #include <vector>
#include <iostream>
using namespace std;
void Filter(const vector<float> &b, const vector<float> &a, const vector<float> &in, vector<float> &out)
{
out.resize(0);
out.resize(in.size());
for(int i=0; i < in.size(); i++)
{
float tmp = 0.;
int j=0;
out[i] = 0.f;
for(j=0; j < b.size(); j++)
{
if(i - j < 0) continue;
tmp += b[j] * in[i-j];
}
for(j=1; j < a.size(); j++)
{
if(i - j < 0) continue;
tmp -= a[j]*out[i-j];
}
tmp /= a[0];
out[i] = tmp;
}
}
int main()
{
vector<float> sig = {-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};
//Constants for a Butterworth filter (order 3, low pass)
vector<float> a = {1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17};
vector<float> b = {0.16666667, 0.5, 0.5, 0.16666667};
vector<float> result;
Filter(b, a, sig, result);
for(size_t i=0;i<result.size();i++)
cout << result[i] << ",";
cout << endl;
return 0;
} |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Brat | Brat | mean = { list |
true? list.empty?, 0, { list.reduce(0, :+) / list.length }
}
p mean 1.to 10 #Prints 5.5 |
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
| #Burlesque | Burlesque |
blsq ) {1 2 2.718 3 3.142}av
2.372
blsq ) {}av
NaN
|
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
| #jq | jq | julia> dict1 = Dict("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow")
Dict{String,Any} with 3 entries:
"name" => "Rocket Skates"
"price" => 12.75
"color" => "yellow"
julia> dict2 = Dict("price" => 15.25, "color" => "red", "year" => 1974)
Dict{String,Any} with 3 entries:
"price" => 15.25
"year" => 1974
"color" => "red"
julia> merge(dict1, dict2)
Dict{String,Any} with 4 entries:
"name" => "Rocket Skates"
"price" => 15.25
"year" => 1974
"color" => "red"
julia> merge(dict2, dict1)
Dict{String,Any} with 4 entries:
"name" => "Rocket Skates"
"price" => 12.75
"year" => 1974
"color" => "yellow"
julia> union(dict1, dict2)
6-element Array{Pair{String,Any},1}:
"name" => "Rocket Skates"
"price" => 12.75
"color" => "yellow"
"price" => 15.25
"year" => 1974
"color" => "red"
|
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
| #Julia | Julia | julia> dict1 = Dict("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow")
Dict{String,Any} with 3 entries:
"name" => "Rocket Skates"
"price" => 12.75
"color" => "yellow"
julia> dict2 = Dict("price" => 15.25, "color" => "red", "year" => 1974)
Dict{String,Any} with 3 entries:
"price" => 15.25
"year" => 1974
"color" => "red"
julia> merge(dict1, dict2)
Dict{String,Any} with 4 entries:
"name" => "Rocket Skates"
"price" => 15.25
"year" => 1974
"color" => "red"
julia> merge(dict2, dict1)
Dict{String,Any} with 4 entries:
"name" => "Rocket Skates"
"price" => 12.75
"year" => 1974
"color" => "yellow"
julia> union(dict1, dict2)
6-element Array{Pair{String,Any},1}:
"name" => "Rocket Skates"
"price" => 12.75
"color" => "yellow"
"price" => 15.25
"year" => 1974
"color" => "red"
|
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
| #Kotlin | Kotlin |
fun main() {
val base = HashMap<String,String>()
val update = HashMap<String,String>()
base["name"] = "Rocket Skates"
base["price"] = "12.75"
base["color"] = "yellow"
update["price"] = "15.25"
update["color"] = "red"
update["year"] = "1974"
val merged = HashMap(base)
merged.putAll(update)
println("base: $base")
println("update: $update")
println("merged: $merged")
}
|
http://rosettacode.org/wiki/Average_loop_length | Average loop length | Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence.
Task
Write a program or a script that estimates, for each N, the average length until the first such repetition.
Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.
This problem comes from the end of Donald Knuth's Christmas tree lecture 2011.
Example of expected output:
N average analytical (error)
=== ========= ============ =========
1 1.0000 1.0000 ( 0.00%)
2 1.4992 1.5000 ( 0.05%)
3 1.8784 1.8889 ( 0.56%)
4 2.2316 2.2188 ( 0.58%)
5 2.4982 2.5104 ( 0.49%)
6 2.7897 2.7747 ( 0.54%)
7 3.0153 3.0181 ( 0.09%)
8 3.2429 3.2450 ( 0.07%)
9 3.4536 3.4583 ( 0.14%)
10 3.6649 3.6602 ( 0.13%)
11 3.8091 3.8524 ( 1.12%)
12 3.9986 4.0361 ( 0.93%)
13 4.2074 4.2123 ( 0.12%)
14 4.3711 4.3820 ( 0.25%)
15 4.5275 4.5458 ( 0.40%)
16 4.6755 4.7043 ( 0.61%)
17 4.8877 4.8579 ( 0.61%)
18 4.9951 5.0071 ( 0.24%)
19 5.1312 5.1522 ( 0.41%)
20 5.2699 5.2936 ( 0.45%)
| #Liberty_BASIC | Liberty BASIC |
MAXN = 20
TIMES = 10000'00
't0=time$("ms")
FOR n = 1 TO MAXN
avg = FNtest(n, TIMES)
theory = FNanalytical(n)
diff = (avg / theory - 1) * 100
PRINT n, avg, theory, using("##.####",diff); "%"
NEXT
't1=time$("ms")
'print t1-t0; " ms"
END
function FNanalytical(n)
FOR i = 1 TO n
s = s+ FNfactorial(n) / n^i / FNfactorial(n-i)
NEXT
FNanalytical = s
end function
function FNtest(n, times)
FOR i = 1 TO times
x = 1 : b = 0
WHILE (b AND x) = 0
c = c + 1
b = b OR x
x = 2^int(n*RND(1))
WEND
NEXT
FNtest = c / times
end function
function FNfactorial(n)
IF n=1 OR n=0 THEN FNfactorial=1 ELSE FNfactorial= n * FNfactorial(n-1)
end function
|
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%)
| #Lua | Lua | function average(n, reps)
local count = 0
for r = 1, reps do
local f = {}
for i = 1, n do f[i] = math.random(n) end
local seen, x = {}, 1
while not seen[x] do
seen[x], x, count = true, f[x], count+1
end
end
return count / reps
end
function analytical(n)
local s, t = 1, 1
for i = n-1, 1, -1 do t=t*i/n s=s+t end
return s
end
print(" N average analytical (error)")
print("=== ========= ============ =========")
for n = 1, 20 do
local avg, ana = average(n, 1e6), analytical(n)
local err = (avg-ana) / ana * 100
print(string.format("%3d %9.4f %12.4f (%6.3f%%)", n, avg, ana, err))
end |
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period.
It can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA().
The word stateful in the task description refers to the need for SMA() to remember certain information between calls to it:
The period, P
An ordered container of at least the last P numbers from each of its individual calls.
Stateful also means that successive calls to I(), the initializer, should return separate routines that do not share saved state so they could be used on two independent streams of data.
Pseudo-code for an implementation of SMA is:
function SMA(number: N):
stateful integer: P
stateful list: stream
number: average
stream.append_last(N)
if stream.length() > P:
# Only average the last P elements of the stream
stream.delete_first()
if stream.length() == 0:
average = 0
else:
average = sum( stream.values() ) / stream.length()
return average
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Raku | Raku | sub sma-generator (Int $P where * > 0) {
sub ($x) {
state @a = 0 xx $P;
@a.push($x).shift;
@a.sum / $P;
}
}
# Usage:
my &sma = sma-generator 3;
for 1, 2, 3, 2, 7 {
printf "append $_ --> sma = %.2f (with period 3)\n", sma $_;
} |
http://rosettacode.org/wiki/Attractive_numbers | Attractive numbers | A number is an attractive number if the number of its prime factors (whether distinct or not) is also prime.
Example
The number 20, whose prime decomposition is 2 × 2 × 5, is an attractive number because the number of its prime factors (3) is also prime.
Task
Show sequence items up to 120.
Reference
The OEIS entry: A063989: Numbers with a prime number of prime divisors.
| #FreeBASIC | FreeBASIC |
Const limite = 120
Declare Function esPrimo(n As Integer) As Boolean
Declare Function ContandoFactoresPrimos(n As Integer) As Integer
Function esPrimo(n As Integer) As Boolean
If n < 2 Then Return false
If n Mod 2 = 0 Then Return n = 2
If n Mod 3 = 0 Then Return n = 3
Dim As Integer d = 5
While d * d <= n
If n Mod d = 0 Then Return false
d += 2
If n Mod d = 0 Then Return false
d += 4
Wend
Return true
End Function
Function ContandoFactoresPrimos(n As Integer) As Integer
If n = 1 Then Return false
If esPrimo(n) Then Return true
Dim As Integer f = 2, contar = 0
While true
If n Mod f = 0 Then
contar += 1
n = n / f
If n = 1 Then Return contar
If esPrimo(n) Then f = n
Elseif f >= 3 Then
f += 2
Else
f = 3
End If
Wend
End Function
' Mostrar la sucencia de números atractivos hasta 120.
Dim As Integer i = 1, longlinea = 0
Print "Los numeros atractivos hasta e incluyendo"; limite; " son: "
While i <= limite
Dim As Integer n = ContandoFactoresPrimos(i)
If esPrimo(n) Then
Print Using "####"; i;
longlinea += 1: If longlinea Mod 20 = 0 Then Print ""
End If
i += 1
Wend
End
|
http://rosettacode.org/wiki/Averages/Mean_time_of_day | Averages/Mean time of day | Task[edit]
A particular activity of bats occurs at these times of the day:
23:00:17, 23:40:20, 00:12:45, 00:17:19
Using the idea that there are twenty-four hours in a day,
which is analogous to there being 360 degrees in a circle,
map times of day to and from angles;
and using the ideas of Averages/Mean angle
compute and show the average time of the nocturnal activity
to an accuracy of one second of time.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Liberty_BASIC | Liberty BASIC |
global pi
pi = acs(-1)
Print "Average of:"
for i = 1 to 4
read t$
print t$
a=time2angle(t$)
ss=ss+sin(a)
sc=sc+cos(a)
next
a=atan2(ss,sc)
if a<0 then a=a+2*pi
print "is ";angle2time$(a)
end
data "23:00:17", "23:40:20", "00:12:45", "00:17:19"
function nn$(n)
nn$=right$("0";n, 2)
end function
function angle2time$(a)
a=int(a/2/pi*24*60*60)
ss=a mod 60
a=int(a/60)
mm=a mod 60
hh=int(a/60)
angle2time$=nn$(hh);":";nn$(mm);":";nn$(ss)
end function
function time2angle(time$)
hh=val(word$(time$,1,":"))
mm=val(word$(time$,2,":"))
ss=val(word$(time$,3,":"))
time2angle=2*pi*(60*(60*hh+mm)+ss)/24/60/60
end function
function atan2(y, x)
On Error GoTo [DivZero] 'If y is 0 catch division by zero error
atan2 = (2 * (atn((sqr((x * x) + (y * y)) - x)/ y)))
exit function
[DivZero]
atan2 = (y=0)*(x<0)*pi
End Function
|
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.
| #Nim | Nim | #[ AVL tree adapted from Julienne Walker's presentation at
http://eternallyconfuzzled.com/tuts/datastructures/jsw_tut_avl.aspx.
Uses bounded recursive versions for insertion and deletion.
]#
type
# Objects strored in the tree must be comparable.
Comparable = concept x, y
(x == y) is bool
(x < y) is bool
# Direction used to select a child.
Direction = enum Left, Right
# Description of the tree node.
Node[T: Comparable] = ref object
data: T # Payload.
balance: range[-2..2] # Balance factor (bounded).
links: array[Direction, Node[T]] # Children.
# Description of a tree.
AvlTree[T: Comparable] = object
root: Node[T]
#---------------------------------------------------------------------------------------------------
func opp(dir: Direction): Direction {.inline.} =
## Return the opposite of a direction.
Direction(1 - ord(dir))
#---------------------------------------------------------------------------------------------------
func single(root: Node; dir: Direction): Node =
## Single rotation.
result = root.links[opp(dir)]
root.links[opp(dir)] = result.links[dir]
result.links[dir] = root
#---------------------------------------------------------------------------------------------------
func double(root: Node; dir: Direction): Node =
## Double rotation.
let save = root.links[opp(dir)].links[dir]
root.links[opp(dir)].links[dir] = save.links[opp(dir)]
save.links[opp(dir)] = root.links[opp(dir)]
root.links[opp(dir)] = save
result = root.links[opp(dir)]
root.links[opp(dir)] = result.links[dir]
result.links[dir] = root
#---------------------------------------------------------------------------------------------------
func adjustBalance(root: Node; dir: Direction; balance: int) =
## Adjust balance factors after double rotation.
let node1 = root.links[dir]
let node2 = node1.links[opp(dir)]
if node2.balance == 0:
root.balance = 0
node1.balance = 0
elif node2.balance == balance:
root.balance = -balance
node1.balance = 0
else:
root.balance = 0
node1.balance = balance
node2.balance = 0
#---------------------------------------------------------------------------------------------------
func insertBalance(root: Node; dir: Direction): Node =
## Rebalancing after an insertion.
let node = root.links[dir]
let balance = 2 * ord(dir) - 1
if node.balance == balance:
root.balance = 0
node.balance = 0
result = root.single(opp(dir))
else:
root.adjustBalance(dir, balance)
result = root.double(opp(dir))
#---------------------------------------------------------------------------------------------------
func insertR(root: Node; data: root.T): tuple[node: Node, done: bool] =
## Insert data (recursive way).
if root.isNil:
return (Node(data: data), false)
let dir = if root.data < data: Right else: Left
var done: bool
(root.links[dir], done) = root.links[dir].insertR(data)
if done:
return (root, true)
inc root.balance, 2 * ord(dir) - 1
result = case root.balance
of 0: (root, true)
of -1, 1: (root, false)
else: (root.insertBalance(dir), true)
#---------------------------------------------------------------------------------------------------
func removeBalance(root: Node; dir: Direction): tuple[node: Node, done: bool] =
## Rebalancing after a deletion.
let node = root.links[opp(dir)]
let balance = 2 * ord(dir) - 1
if node.balance == -balance:
root.balance = 0
node.balance = 0
result = (root.single(dir), false)
elif node.balance == balance:
root.adjustBalance(opp(dir), -balance)
result = (root.double(dir), false)
else:
root.balance = -balance
node.balance = balance
result = (root.single(dir), true)
#---------------------------------------------------------------------------------------------------
func removeR(root: Node; data: root.T): tuple[node: Node, done: bool] =
## Remove data (recursive way).
if root.isNil:
return (nil, false)
var data = data
if root.data == data:
if root.links[Left].isNil:
return (root.links[Right], false)
if root.links[Right].isNil:
return (root.links[Left], false)
var heir = root.links[Left]
while not heir.links[Right].isNil:
heir = heir.links[Right]
root.data = heir.data
data = heir.data
let dir = if root.data < data: Right else: Left
var done: bool
(root.links[dir], done) = root.links[dir].removeR(data)
if done:
return (root, true)
dec root.balance, 2 * ord(dir) - 1
result = case root.balance
of -1, 1: (root, true)
of 0: (root, false)
else: root.removeBalance(dir)
#---------------------------------------------------------------------------------------------------
func insert(tree: var AvlTree; data: tree.T) =
## Insert data in an AVL tree.
tree.root = tree.root.insertR(data).node
#---------------------------------------------------------------------------------------------------
func remove(tree: var AvlTree; data: tree.T) =
## Remove data from an AVL tree.
tree.root = tree.root.removeR(data).node
#———————————————————————————————————————————————————————————————————————————————————————————————————
import json
var tree: AvlTree[int]
echo pretty(%tree)
echo "Insert test:"
tree.insert(3)
tree.insert(1)
tree.insert(4)
tree.insert(1)
tree.insert(5)
echo pretty(%tree)
echo ""
echo "Remove test:"
tree.remove(3)
tree.remove(1)
echo pretty(%tree) |
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
| #jq | jq | def pi: 4 * (1|atan);
def deg2rad: . * pi / 180;
def rad2deg: if . == null then null else . * 180 / pi end;
# Input: [x,y] (special handling of x==0)
# Output: [r, theta] where theta may be null
def to_polar:
if .[0] == 0
then [1, if .[1] > 5e-14 then pi/2 elif .[1] < -5e-14 then -pi/2 else null end]
else [1, ((.[1]/.[0]) | atan)]
end;
def from_polar: .[1] | [ cos, sin];
def abs: if . < 0 then - . else . end;
def summation(f): map(f) | add; |
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
| #Julia | Julia | using Statistics
meandegrees(degrees) = rad2deg(atan(mean(sind.(degrees)), mean(cosd.(degrees)))) |
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
| #E | E | def median(list) {
def sorted := list.sort()
def count := sorted.size()
def mid1 := count // 2
def mid2 := (count - 1) // 2
if (mid1 == mid2) { # avoid inexact division
return sorted[mid1]
} else {
return (sorted[mid1] + sorted[mid2]) / 2
}
} |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of positive integers.
The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
A
(
x
1
,
…
,
x
n
)
=
x
1
+
⋯
+
x
n
n
{\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}}
The geometric mean is the
n
{\displaystyle n}
th root of the product of the list:
G
(
x
1
,
…
,
x
n
)
=
x
1
⋯
x
n
n
{\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}}
The harmonic mean is
n
{\displaystyle n}
divided by the sum of the reciprocal of each item in the list:
H
(
x
1
,
…
,
x
n
)
=
n
1
x
1
+
⋯
+
1
x
n
{\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #HicEst | HicEst | AGH = ALIAS( A, G, H ) ! named vector elements
AGH = (0, 1, 0)
DO i = 1, 10
A = A + i
G = G * i
H = H + 1/i
ENDDO
AGH = (A/10, G^0.1, 10/H)
WRITE(ClipBoard, Name) AGH, "Result = " // (A>=G) * (G>=H) |
http://rosettacode.org/wiki/Balanced_ternary | Balanced ternary | Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1.
Examples
Decimal 11 = 32 + 31 − 30, thus it can be written as "++−"
Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0"
Task
Implement balanced ternary representation of integers with the following:
Support arbitrarily large integers, both positive and negative;
Provide ways to convert to and from text strings, using digits '+', '-' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5).
Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type is balanced ternary). If your native integers can't support arbitrary length, overflows during conversion must be indicated.
Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do not convert to native integers first.
Make your implementation efficient, with a reasonable definition of "efficient" (and with a reasonable definition of "reasonable").
Test case With balanced ternaries a from string "+-0++0+", b from native integer -436, c "+-++-":
write out a, b and c in decimal notation;
calculate a × (b − c), write out the result in both ternary and decimal notations.
Note: The pages generalised floating point addition and generalised floating point multiplication have code implementing arbitrary precision floating point balanced ternary.
| #Nim | Nim | import strformat
import tables
type
# Trit definition.
Trit = range[-1'i8..1'i8]
# Balanced ternary number as a sequence of trits stored in little endian way.
BTernary = seq[Trit]
const
# Textual representation of trits.
Trits: array[Trit, char] = ['-', '0', '+']
# Symbolic names used for trits.
TN = Trit(-1)
TZ = Trit(0)
TP = Trit(1)
# Table to convert the result of classic addition to balanced ternary numbers.
AddTable = {-2: @[TP, TN], -1: @[TN], 0: @[TZ], 1: @[TP], 2: @[TN, TP]}.toTable()
# Mapping from modulo to trits (used for conversion from int to balanced ternary).
ModTrits: array[-2..2, Trit] = [TP, TN, TZ, TP, TN]
#---------------------------------------------------------------------------------------------------
func normalize(bt: var BTernary) =
## Remove the extra zero trits at head of a BTernary number.
var i = bt.high
while i >= 0 and bt[i] == 0:
dec i
bt.setlen(if i < 0: 1 else: i + 1)
#---------------------------------------------------------------------------------------------------
func `+`*(a, b: BTernary): BTernary =
## Add two BTernary numbers.
# Prepare operands.
var (a, b) = (a, b)
if a.len < b.len:
a.setLen(b.len)
else:
b.setLen(a.len)
# Perform addition trit per trit.
var carry = TZ
for i in 0..<a.len:
var s = AddTable[a[i] + b[i]]
if carry != TZ:
s = s + @[carry]
carry = if s.len > 1: s[1] else: TZ
result.add(s[0])
# Append the carry to the result if it is not null.
if carry != TZ:
result.add(carry)
#---------------------------------------------------------------------------------------------------
func `+=`*(a: var BTernary; b: BTernary) {.inline.} =
## Increment a BTernary number.
a = a + b
#---------------------------------------------------------------------------------------------------
func `-`(a: BTernary): BTernary =
## Negate a BTernary number.
result.setLen(a.len)
for i, t in a:
result[i] = -t
#---------------------------------------------------------------------------------------------------
func `-`*(a, b: BTernary): BTernary {.inline.} =
## Subtract a BTernary number to another.
a + -b
#---------------------------------------------------------------------------------------------------
func `-=`*(a: var BTernary; b: BTernary) {.inline.} =
## Decrement a BTernary number.
a = a + -b
#---------------------------------------------------------------------------------------------------
func `*`*(a, b: BTernary): BTernary =
## Multiply tow BTernary numbers.
var start: BTernary
let na = -a
# Loop on each trit of "b" and add directly a whole row.
for t in b:
case t
of TP: result += start & a
of TZ: discard
of TN: result += start & na
start.add(TZ) # Shift next row.
result.normalize()
#---------------------------------------------------------------------------------------------------
func toTrit*(c: char): Trit =
## Convert a char to a trit.
case c
of '-': -1
of '0': 0
of '+': 1
else:
raise newException(ValueError, fmt"Invalid trit: '{c}'")
#---------------------------------------------------------------------------------------------------
func `$`*(bt: BTernary): string =
## Return the string representation of a BTernary number.
result.setLen(bt.len)
for i, t in bt:
result[^(i + 1)] = Trits[t]
#---------------------------------------------------------------------------------------------------
func toBTernary*(s: string): BTernary =
## Build a BTernary number from its string representation.
result.setLen(s.len)
for i, c in s:
result[^(i + 1)] = c.toTrit()
#---------------------------------------------------------------------------------------------------
func toInt*(bt: BTernary): int =
## Convert a BTernary number to an integer.
## An overflow error is raised if the result cannot fit in an integer.
var m = 1
for t in bt:
result += m * t
m *= 3
#---------------------------------------------------------------------------------------------------
func toBTernary(val: int): BTernary =
## Convert an integer to a BTernary number.
var val = val
while true:
let trit = ModTrits[val mod 3]
result.add(trit)
val = (val - trit) div 3
if val == 0:
break
#———————————————————————————————————————————————————————————————————————————————————————————————————
when isMainModule:
let a = "+-0++0+".toBTernary
let b = -436.toBTernary
let c = "+-++-".toBTernary
echo "Balanced ternary numbers:"
echo fmt"a = {a}"
echo fmt"b = {b}"
echo fmt"c = {c}"
echo ""
echo "Their decimal representation:"
echo fmt"a = {a.toInt: 4d}"
echo fmt"b = {b.toInt: 4d}"
echo fmt"c = {c.toInt: 4d}"
echo ""
let x = a * (b - c)
echo "a × (b - c):"
echo fmt"– in ternary: {x}"
echo fmt"– in decimal: {x.toInt}" |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.