task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Barnsley_fern | Barnsley fern |
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
Task
Create this fractal fern, using the following transformations:
ƒ1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
ƒ2 (chosen 85% of the time)
... | #Yabasic | Yabasic | 10 REM Fractal Fern
20 LET wid = 800 : LET hei = 600 : open window wid, hei : window origin "cb"
25 backcolor 0, 0, 0 : color 0, 255, 0 : clear window
30 LET maxpoints=wid*hei/2: LET x=0: LET y=0
40 FOR n=1 TO maxpoints
50 LET p=RAN(100)
60 IF p<=1 LET nx=0: LET ny=0.16*y: GOTO 100
70 IF p<=8 LET nx=0.2*x-0.26*y: LET n... |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p.... | #Gambas | Gambas | Public Sub Main()
Dim iNum As Long
For iNum = 1 To 100000
If Str(iNum * iNum) Ends "269696" Then Break
Next
Print "The lowest number squared that ends in '269696' is " & Str(iNum)
End |
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) ... | #360_Assembly | 360 Assembly | * Balanced brackets 28/04/2016
BALANCE CSECT
USING BALANCE,R13 base register and savearea pointer
SAVEAREA B STM-SAVEAREA(R15)
DC 17F'0'
STM STM R14,R12,12(R13)
ST R13,4(R15)
ST R15,8(R13)
LR R13,R15 establish a... |
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 appropriat... | #AWK | AWK | #!/usr/bin/gawk -f
{
# compute histogram
histo[$1] += 1;
};
function mode(HIS) {
# Computes the mode from Histogram A
max = 0;
n = 0;
for (k in HIS) {
val = HIS[k];
if (HIS[k] > max) {
max = HIS[k];
n = 1;
List[n] = k;
} else if (HIS[k] == max) {
List[++n] = k;
}... |
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 avera... | #Lua | Lua | function sma(period)
local t = {}
function sum(a, ...)
if a then return a+sum(...) else return 0 end
end
function average(n)
if #t == period then table.remove(t, 1) end
t[#t + 1] = n
return sum(unpack(t)) / #t
end
return average
end
sma5 = sma(5)
sma10 = sma(10)
print("SMA 5")
for v=1,15 do print(sma5(v... |
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 p... | #C | C | #include <stdio.h>
#include <stdlib.h> // atoi()
#include <math.h> // pow()
int main(int argc, char* argv[])
{
int i, count=0;
double f, sum=0.0, prod=1.0, resum=0.0;
for (i=1; i<argc; ++i) {
f = atof(argv[i]);
count++;
sum += f;
prod *= f;
resum += (1.0/f);
}
//printf(" c:%d\n s:%f\n ... |
http://rosettacode.org/wiki/Barnsley_fern | Barnsley fern |
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
Task
Create this fractal fern, using the following transformations:
ƒ1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
ƒ2 (chosen 85% of the time)
... | #zkl | zkl | fcn barnsleyFern(){
w,h:=640,640;
bitmap:=PPM(w+1,h+1,0xFF|FF|FF); // White background
x,y, nx,ny:=0.0, 0.0, 0.0, 0.0;
do(0d100_000){
r:=(0).random(100); // [0..100)%
if (r<= 1) nx,ny= 0, 0.16*y;
else if(r<= 8) nx,ny= 0.2*x - 0.26*y, 0.23*x + 0.22*y + 1.6;
else if(r... |
http://rosettacode.org/wiki/Barnsley_fern | Barnsley fern |
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
Task
Create this fractal fern, using the following transformations:
ƒ1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
ƒ2 (chosen 85% of the time)
... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 REM Fractal Fern
20 PAPER 7: BORDER 7: BRIGHT 1: INK 4: CLS
30 LET maxpoints=20000: LET x=0: LET y=0
40 FOR n=1 TO maxpoints
50 LET p=RND*100
60 IF p<=1 THEN LET nx=0: LET ny=0.16*y: GO TO 100
70 IF p<=8 THEN LET nx=0.2*x-0.26*y: LET ny=0.23*x+0.22*y+1.6: GO TO 100
80 IF p<=15 THEN LET nx=-0.15*x+0.28*y: LET ny=0.2... |
http://rosettacode.org/wiki/Balanced_ternary | Balanced ternary | Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1.
Examples
Decimal 11 = 32 + 31 − 30, thus it can be written as "++−"
Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0"
... | #11l | 11l | F py_idiv(a, b)
I a >= 0
R a I/ b
R (a - b + 1) I/ b
F BalancedTernary_int2ternary(n)
I n == 0
R [Int]()
V n3 = ((n % 3) + 3) % 3
I n3 == 0 {R [0] [+] BalancedTernary_int2ternary(py_idiv(n, 3))}
I n3 == 1 {R [1] [+] BalancedTernary_int2ternary(py_idiv(n, 3))}
I n3 == 2 {R [-1] [+] Bal... |
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.... | #Go | Go | package main
import "fmt"
func main() {
const (
target = 269696
modulus = 1000000
)
for n := 1; ; n++ { // Repeat with n=1, n=2, n=3, ...
square := n * n
ending := square % modulus
if ending == target {
fmt.Println("The smallest number whose square ends with",
target, "is", n,
)
return
... |
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) ... | #ABAP | ABAP |
CLASS lcl_balanced_brackets DEFINITION.
PUBLIC SECTION.
CLASS-METHODS:
class_constructor,
are_brackets_balanced
IMPORTING
seq TYPE string
RETURNING
VALUE(r_are_brackets_balanced) TYPE abap_bool,
get_random_brackets_seq
... |
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 appropriat... | #BBC_BASIC | BBC BASIC | DIM a(10), b(4)
a() = 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17
b() = 1, 2, 4, 4, 1
DIM modes(10)
PRINT "Mode(s) of a() = " ;
FOR i% = 1 TO FNmodes(a(), modes())
PRINT ; modes(i%) " " ;
NEXT
PRINT
PRINT "Mode(s) of b() = " ;
FOR i% = 1 TO FNmodes(b(), modes... |
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 appropriat... | #BQN | BQN | Mode1 ← ⌈´⊸=∘⊒⊸/
Mode2 ← ⊏∘⊑˘·(⌈´⊸=≠¨)⊸/⊐⊸⊔
arr ← 1‿1‿1‿1‿2‿2‿2‿3‿3‿3‿3‿4‿4‿3‿2‿4‿4‿4‿5‿5‿5‿5‿5
•Show Mode1 arr
•Show Mode2 arr |
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an avera... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | MA[x_List, r_] := Join[Table[Mean[x[[1;;y]]],{y,r-1}], MovingAverage[x,r]] |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of p... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace PythMean
{
static class Program
{
static void Main(string[] args) {
var nums = from n in Enumerable.Range(1, 10) select (double)n;
var a = nums.Average();
var g ... |
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"
... | #Ada | Ada | with Ada.Finalization;
package BT is
type Balanced_Ternary is private;
-- conversions
function To_Balanced_Ternary (Num : Integer) return Balanced_Ternary;
function To_Balanced_Ternary (Str : String) return Balanced_Ternary;
function To_Integer (Num : Balanced_Ternary) return Integer;
function... |
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.... | #Groovy | Groovy |
int n=104; ///starting point
while( (n**2)%1000000 != 269696 )
{ if (n%10==4) n=n+2;
if (n%10==6) n=n+8;
}
println n+"^2== "+n**2 ;
|
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) ... | #Action.21 | Action! | PROC Generate(BYTE size CHAR ARRAY s)
BYTE i,half
s(0)=size
half=size RSH 1
FOR i=1 TO half
DO s(i)='[ OD
FOR i=half+1 TO size
DO s(i)='] OD
RETURN
PROC Shuffle(CHAR ARRAY s)
BYTE i,j,k,n,len,tmp
len=s(0)
n=Rand(len+1)
FOR k=1 TO n
DO
i=Rand(len)+1
j=Rand(len)+1
tmp=s(i)
... |
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 appropriat... | #C | C | #include <stdio.h>
#include <stdlib.h>
typedef struct { double v; int c; } vcount;
int cmp_dbl(const void *a, const void *b)
{
double x = *(const double*)a - *(const double*)b;
return x < 0 ? -1 : x > 0;
}
int vc_cmp(const void *a, const void *b)
{
return ((const vcount*)b)->c - ((const vcount*)a)->c;
}
int ... |
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 avera... | #MATLAB_.2F_Octave | MATLAB / Octave | [m,z] = filter(ones(1,P),P,x); |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of p... | #C.2B.2B | C++ | #include <vector>
#include <iostream>
#include <numeric>
#include <cmath>
#include <algorithm>
double toInverse ( int i ) {
return 1.0 / i ;
}
int main( ) {
std::vector<int> numbers ;
for ( int i = 1 ; i < 11 ; i++ )
numbers.push_back( i ) ;
double arithmetic_mean = std::accumulate( numbers.beg... |
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"
... | #ALGOL_68 | ALGOL 68 | -- Build a balanced ternary, as text, from an integer value or acceptable AppleScript substitute.
on BTFromInteger(n)
try
if (n mod 1 is not 0) then error (n as text) & " isn't an integer value"
set n to n as integer
on error errMsg
display alert "BTFromInteger handler: parameter error" ... |
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.... | #Haskell | Haskell | --Calculate squares, testing for the last 6 digits
findBabbageNumber :: Integer
findBabbageNumber =
head (filter ((269696 ==) . flip mod 1000000 . (^ 2)) [1 ..])
main :: IO ()
main =
(putStrLn . unwords)
(zipWith
(++)
(show <$> ([id, (^ 2)] <*> [findBabbageNumber]))
[" ^ 2 equals", " !"]) |
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) ... | #Acurity_Architect | Acurity Architect | Using #HASH-OFF
|
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat... | #C.23 | C# | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Test
{
class Program
{
static void Main(string[] args)
{
/*
* We Use Linq To Determine The Mode
*/
List<int> myList = new List<int>() { 1, ... |
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 avera... | #Mercury | Mercury | % state(period, list of floats from [newest, ..., oldest])
:- type state ---> state(int, list(float)).
:- func init(int) = state.
init(Period) = state(Period, []).
:- pred sma(float::in, float::out, state::in, state::out) is det.
sma(N, Average, state(P, L0), state(P, L)) :-
take_upto(P, [N|L0], L),
... |
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 p... | #Clojure | Clojure | (use '[clojure.contrib.math :only (expt)])
(defn a-mean [coll]
(/ (apply + coll) (count coll)))
(defn g-mean [coll]
(expt (apply * coll) (/ (count coll))))
(defn h-mean [coll]
(/ (count coll) (apply + (map / coll))))
(let [numbers (range 1 11)
a (a-mean numbers) g (g-mean numbers) h (h-mean numbers)... |
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"
... | #AppleScript | AppleScript | -- Build a balanced ternary, as text, from an integer value or acceptable AppleScript substitute.
on BTFromInteger(n)
try
if (n mod 1 is not 0) then error (n as text) & " isn't an integer value"
set n to n as integer
on error errMsg
display alert "BTFromInteger handler: parameter error" ... |
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.... | #J | J | square=: ^&2
modulo1e6=: 1000000&|
trythese=: i. 1000000 NB. first million nonnegative integers
which=: I. NB. position of true values
which 269696=modulo1e6 square trythese NB. right to left <-
25264 99736 150264 224736 275264 349736 400264 474736 525264 5... |
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) ... | #Ada | Ada | with Ada.Numerics.Discrete_Random;
with Ada.Text_IO;
with Ada.Strings.Fixed;
procedure Brackets is
package Random_Positive is new Ada.Numerics.Discrete_Random (Positive);
Positive_Generator : Random_Positive.Generator;
procedure Swap (Left, Right : in out Character) is
Temp : constant Character := Left;
... |
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 appropriat... | #C.2B.2B | C++ | #include <iterator>
#include <utility>
#include <algorithm>
#include <list>
#include <iostream>
// helper struct
template<typename T> struct referring
{
referring(T const& t): value(t) {}
template<typename Iter>
bool operator()(std::pair<Iter, int> const& p) const
{
return *p.first == value;
}
T cons... |
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 avera... | #MiniScript | MiniScript | SMA = {}
SMA.P = 5 // (a default; may be overridden)
SMA.buffer = null
SMA.next = function(n)
if self.buffer == null then self.buffer = []
self.buffer.push n
if self.buffer.len > self.P then self.buffer.pull
return self.buffer.sum / self.buffer.len
end function
sma3 = new SMA
sma3.P = 3
sma5 = new SM... |
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 ... | #11l | 11l | F mean_angle(angles)
V x = sum(angles.map(a -> cos(radians(a)))) / angles.len
V y = sum(angles.map(a -> sin(radians(a)))) / angles.len
R degrees(atan2(y, x))
F mean_time(times)
V t = (times.map(time -> time.split(‘:’)))
V seconds = (t.map(hms -> (Float(hms[2]) + Int(hms[1]) * 60 + Int(hms[0]) * 3600)))... |
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 p... | #CoffeeScript | CoffeeScript | a = [ 1..10 ]
arithmetic_mean = (a) -> a.reduce(((s, x) -> s + x), 0) / a.length
geometic_mean = (a) -> Math.pow(a.reduce(((s, x) -> s * x), 1), (1 / a.length))
harmonic_mean = (a) -> a.length / a.reduce(((s, x) -> s + 1 / x), 0)
A = arithmetic_mean a
G = geometic_mean a
H = harmonic_mean a
console.log "A = ", A, "... |
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"
... | #ATS | ATS |
(*
** This one is
** translated into ATS from the Ocaml entry
*)
(* ****** ****** *)
//
// How to compile:
// patscc -DATS_MEMALLOC_LIBC -o bternary bternary.dats
//
(* ****** ****** *)
#include
"share/atspre_staload.hats"
(* ****** ****** *)
datatype btd = P | Z | N; typedef btern = List0(btd)
(* ****** **... |
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.... | #Java | Java | public class Test {
public static void main(String[] args) {
// let n be zero
int n = 0;
// repeat the following action
do {
// increase n by 1
n++;
// while the modulo of n times n is not equal to 269696
} while (n * n % 1000_000 != ... |
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) ... | #Aime | Aime | unbalanced(data s)
{
integer b, i;
b = i = 0;
while (i + ~s && -1 < b) {
b += s[i -= 1] == '[' ? -1 : 1;
}
b;
}
generate(data b, integer d)
{
if (d) {
d.times(l_bill, list(), -1, '[', ']').l_rand().ucall(b_append, 1, b);
}
}
main(void)
{
integer i;
i = 0;
... |
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 appropriat... | #Clojure | Clojure | (defn modes [coll]
(let [distrib (frequencies coll)
[value freq] [first second] ; name the key/value pairs in the distrib (map) entries
sorted (sort-by (comp - freq) distrib)
maxfq (freq (first sorted))]
(map value (take-while #(= maxfq (freq %)) sorted)))) |
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an avera... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
numeric digits 20
class RAvgSimpleMoving public
properties private
window = java.util.Queue
period
sum
properties constant
exMsg = 'Period must be a positive integer'
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... |
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 ... | #Action.21 | Action! | INCLUDE "H6:REALMATH.ACT"
DEFINE PTR="CARD"
TYPE Time=[BYTE s,m,h]
REAL r60
PROC PrintB2(BYTE b)
IF b<10 THEN Put('0) FI
PrintB(b)
RETURN
PROC PrintTime(Time POINTER t)
PrintB2(t.h) Put(':)
PrintB2(t.m) Put(':)
PrintB2(t.s)
RETURN
PROC Decode(CHAR ARRAY st Time POINTER t)
CHAR ARRAY tmp
IF st(0)... |
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 ... | #Ada | Ada | with Ada.Calendar.Formatting;
with Ada.Command_Line;
with Ada.Numerics.Elementary_Functions;
with Ada.Strings.Fixed;
with Ada.Text_IO;
procedure Mean_Time_Of_Day is
subtype Time is Ada.Calendar.Time;
subtype Time_Of_Day is Ada.Calendar.Day_Duration;
subtype Time_String is String (1 .. 8); -- "HH:M... |
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 p... | #Common_Lisp | Common Lisp | (defun generic-mean (nums reduce-op final-op)
(funcall final-op (reduce reduce-op nums)))
(defun a-mean (nums)
(generic-mean nums #'+ (lambda (x) (/ x (length nums)))))
(defun g-mean (nums)
(generic-mean nums #'* (lambda (x) (expt x (/ 1 (length nums))))))
(defun h-mean (nums)
(generic-mean nums
... |
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"
... | #AutoHotkey | AutoHotkey | BalancedTernary(n){
k = 0
if abs(n)<2
return n=1?"+":n=0?"0":"-"
if n<1
negative := true, n:= -1*n
while !break {
d := Mod(n, 3**(k+1)) / 3**k
d := d=2?-1:d
n := n - (d * 3**k)
r := (d=-1?"-":d=1?"+":0) . r
k++
if (n = 3**k)
r := "+" . r , break := true
}
if negative {
StringReplace, r, r, -,... |
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.... | #JavaScript | JavaScript | // Every line starting with a double slash will be ignored by the processing machine,
// just like these two.
//
// Since the square root of 269,696 is approximately 519, we create a variable named "n"
// and give it this value.
n = 519
// The while-condition is in parentheses
// * is for multiplication
// % is for... |
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) ... | #ALGOL_68 | ALGOL 68 | # generates a string of random opening and closing brackets. The number of #
# each type of brackets is speccified in length #
PROC get brackets = ( INT length ) STRING:
BEGIN
INT result length = length * 2;
[ 1 : result length ]CHAR result;
# initialise th... |
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 appropriat... | #CoffeeScript | CoffeeScript | mode = (arr) ->
# returns an array with the modes of arr, i.e. the
# elements that appear most often in arr
counts = {}
for elem in arr
counts[elem] ||= 0
counts[elem] += 1
max = 0
for key, cnt of counts
max = cnt if cnt > max
(key for key, cnt of counts when cnt == max)
console.log mode [1,... |
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 avera... | #Nim | Nim | import deques
proc simplemovingaverage(period: int): auto =
assert period > 0
var
summ, n = 0.0
values: Deque[float]
for i in 1..period:
values.addLast(0)
proc sma(x: float): float =
values.addLast(x)
summ += x - values.popFirst()
n = min(n+1, float(period))
result = summ / n
... |
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 ... | #AutoHotkey | AutoHotkey | MsgBox, % "The mean time is: " MeanTime(["23:00:17", "23:40:20", "00:12:45", "00:17:19"])
MeanTime(t, x=0, y=0) {
static c := ATan(1) / 45
for k, v in t {
n := StrSplit(v, ":")
r := c * (n[1] * 3600 + n[2] * 60 + n[3]) / 240
x += Cos(r)
y += Sin(r)
}
r := atan2(x, y) / c
r := (r < 0 ? r + 360 : r) / 15
... |
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 p... | #D | D | import std.stdio, std.algorithm, std.range, std.functional;
auto aMean(T)(T data) pure nothrow @nogc {
return data.sum / data.length;
}
auto gMean(T)(T data) pure /*@nogc*/ {
return data.reduce!q{a * b} ^^ (1.0 / data.length);
}
auto hMean(T)(T data) pure /*@nogc*/ {
return data.length / data.reduce!q... |
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"
... | #C | C | #include <stdio.h>
#include <string.h>
void reverse(char *p) {
size_t len = strlen(p);
char *r = p + len - 1;
while (p < r) {
*p ^= *r;
*r ^= *p;
*p++ ^= *r--;
}
}
void to_bt(int n, char *b) {
static char d[] = { '0', '+', '-' };
static int v[] = { 0, 1, -1 };
c... |
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.... | #jq | jq | $ jq -n '1 | until( .*. | tostring | test("269696$"); .+1)'
25264 |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p.... | #Julia | Julia |
function babbage(x::Integer)
i = big(0)
d = floor(log10(x)) + 1
while i ^ 2 % 10 ^ d != x
i += 1
end
return i
end
|
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) ... | #ANTLR | ANTLR |
grammar balancedBrackets ;
options {
language = Java;
}
bb : {System.out.print("input is: ");} (balancedBrackets {System.out.print($balancedBrackets.text);})* NEWLINE {System.out.println();}
;
balancedBrackets
: OpenBracket balancedBrackets* CloseBracket
;
OpenBracket
: '['
;
CloseBracket
: ']'
;
NEWLINE ... |
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 appropriat... | #Common_Lisp | Common Lisp | (defun mode (sequence &rest hash-table-options)
(let ((frequencies (apply #'make-hash-table hash-table-options)))
(map nil (lambda (element)
(incf (gethash element frequencies 0)))
sequence)
(let ((modes '())
(hifreq 0 ))
(maphash (lambda (element frequency)
... |
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 avera... | #Objeck | Objeck |
use Collection;
class MovingAverage {
@window : FloatQueue;
@period : Int;
@sum : Float;
New(period : Int) {
@window := FloatQueue->New();
@period := period;
}
method : NewNum(num : Float) ~ Nil {
@sum += num;
@window->Add(num);
if(@window->Size() > @period) {
@sum -= @win... |
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 ... | #AWK | AWK | #!/usr/bin/awk -f
{
c = atan2(0,-1)/(12*60*60);
x=0.0; y=0.0;
for (i=1; i<=NF; i++) {
split($i,a,":");
p = (a[1]*3600+a[2]*60+a[3])*c;
x += sin(p);
y += cos(p);
}
p = atan2(x,y)/c;
if (p<0) p += 24*60*60;
print strftime("%T",p,1);
} |
http://rosettacode.org/wiki/AVL_tree | AVL tree |
This page uses content from Wikipedia. The original article was at AVL tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In computer science, an AVL tree is a self-balancing binary search tree.... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program avltree64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM6... |
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 ... | #11l | 11l | F mean_angle(angles)
V x = sum(angles.map(a -> cos(radians(a)))) / angles.len
V y = sum(angles.map(a -> sin(radians(a)))) / angles.len
R degrees(atan2(y, x))
print(mean_angle([350, 10]))
print(mean_angle([90, 180, 270, 360]))
print(mean_angle([10, 20, 30])) |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches ... | #11l | 11l | F median(aray)
V srtd = sorted(aray)
V alen = srtd.len
R 0.5 * (srtd[(alen - 1) I/ 2] + srtd[alen I/ 2])
print(median([4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2]))
print(median([4.1, 7.2, 1.7, 9.3, 4.4, 3.2])) |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of p... | #Delphi | Delphi | program AveragesPythagoreanMeans;
{$APPTYPE CONSOLE}
uses Types, Math;
function ArithmeticMean(aArray: TDoubleDynArray): Double;
var
lValue: Double;
begin
Result := 0;
for lValue in aArray do
Result := Result + lValue;
if Result > 0 then
Result := Result / Length(aArray);
end;
function Geometric... |
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"
... | #C.23 | C# | using System;
using System.Text;
using System.Collections.Generic;
public class BalancedTernary
{
public static void Main()
{
BalancedTernary a = new BalancedTernary("+-0++0+");
System.Console.WriteLine("a: " + a + " = " + a.ToLong());
BalancedTernary b = new BalancedTernary(-436);
System.Console.WriteLine(... |
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.... | #Kotlin | Kotlin | fun main(args: Array<String>) {
var number = 520L
var square = 520 * 520L
while (true) {
val last6 = square.toString().takeLast(6)
if (last6 == "269696") {
println("The smallest number is $number whose square is $square")
return
}
number += 2
... |
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) ... | #APL | APL | gen ← (⊂+?+)⍨ ⌷ ('[]'/⍨⊢)
bal ← (((|≡⊢)+\) ∧ 0=+/)(+⌿1 ¯1×[1]'[]'∘.=⊢) |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat... | #D | D | import std.stdio, std.algorithm, std.array;
auto mode(T)(T[] items) pure /*nothrow @safe*/ {
int[T] aa;
foreach (item; items)
aa[item]++;
immutable m = aa.byValue.reduce!max;
return aa.byKey.filter!(k => aa[k] == m);
}
void main() /*@safe*/ {
auto data = [1, 2, 3, 1, 2, 4, 2, 5, 3, 3, 1,... |
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 avera... | #Objective-C | Objective-C | #import <Foundation/Foundation.h>
@interface MovingAverage : NSObject {
unsigned int period;
NSMutableArray *window;
double sum;
}
- (instancetype)initWithPeriod:(unsigned int)thePeriod;
@end
@implementation MovingAverage
// init with default period
- (instancetype)init {
self = [super init];
if(self) {
pe... |
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 ... | #BBC_BASIC | BBC BASIC | nTimes% = 4
DATA 23:00:17, 23:40:20, 00:12:45, 00:17:19
DIM angles(nTimes%-1)
FOR N% = 0 TO nTimes%-1
READ tim$
angles(N%) = FNtimetoangle(tim$)
NEXT
PRINT "Mean time is " FNangletotime(FNmeanangle(angles(), nTimes%))
END
DEF FNtimetoangle(t$)
LO... |
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 ... | #C | C | #include<stdlib.h>
#include<math.h>
#include<stdio.h>
typedef struct
{
int hour, minute, second;
} digitime;
double
timeToDegrees (digitime time)
{
return (360 * time.hour / 24.0 + 360 * time.minute / (24 * 60.0) +
360 * time.second / (24 * 3600.0));
}
digitime
timeFromDegrees (double angle)
{
dig... |
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.... | #Ada | Ada |
with Ada.Text_IO, Ada.Finalization, Ada.Unchecked_Deallocation;
procedure Main is
generic
type Key_Type is private;
with function "<"(a, b : Key_Type) return Boolean is <>;
with function "="(a, b : Key_Type) return Boolean is <>;
with function "<="(a, b : Key_Type) return Boolean is <>;... |
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 ... | #Ada | Ada | with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions;
procedure Mean_Angles is
type X_Real is digits 4; -- or more digits for improved precision
subtype Real is X_Real range 0.0 .. 360.0; -- the range of interest
type Angles is array(Positive range <>) of Real;
procedure Put(R: Real) is
... |
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 ... | #Action.21 | Action! | INCLUDE "H6:REALMATH.ACT"
DEFINE PTR="CARD"
PROC Sort(PTR ARRAY a INT count)
INT i,j,minpos
REAL POINTER tmp
FOR i=0 TO count-2
DO
minpos=i
FOR j=i+1 TO count-1
DO
IF RealGreaterOrEqual(a(minpos),a(j)) THEN
minpos=j
FI
OD
IF minpos#i THEN
tmp=a(i)
a(i)... |
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 p... | #E | E | def makeMean(base, include, finish) {
return def mean(numbers) {
var count := 0
var acc := base
for x in numbers {
acc := include(acc, x)
count += 1
}
return finish(acc, count)
}
}
def A := makeMean(0, fn b,x { b+x }, fn acc,n { acc / n })... |
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"
... | #C.2B.2B | C++ | #include <iostream>
#include <string>
#include <climits>
using namespace std;
class BalancedTernary {
protected:
// Store the value as a reversed string of +, 0 and - characters
string value;
// Helper function to change a balanced ternary character to an integer
int charToInt(char c) const {
if (c == '0')
... |
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.... | #Liberty_BASIC | Liberty BASIC |
[start]
if right$(str$(n*n),6)="269696" then
print "n = "; using("###,###", n);
print " n*n = "; using("###,###,###,###", n*n)
end if
if n<100000 then n=n+1: goto [start]
print "Program complete."
|
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) ... | #AppleScript | AppleScript | -- CHECK NESTING OF SQUARE BRACKET SEQUENCES ---------------------------------
-- Zero-based index of the first problem (-1 if none found):
-- imbalance :: String -> Integer
on imbalance(strBrackets)
script
on errorIndex(xs, iDepth, iIndex)
set lngChars to length of xs
if lngChar... |
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 appropriat... | #Delphi | Delphi |
program AveragesMode;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Generics.Collections,
System.Generics.Defaults;
type
TCounts = TDictionary<Integer, Integer>;
TPair = record
value, count: Integer;
constructor Create(value, count: Integer);
end;
TPairs = TArray<TPair>;
var
dict... |
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 avera... | #OCaml | OCaml | let sma (n, s, q) x =
let l = Queue.length q and s = s +. x in
Queue.push x q;
if l < n then
(n, s, q), s /. float (l + 1)
else (
let s = s -. Queue.pop q in
(n, s, q), s /. float l
)
let _ =
let periodLst = [ 3; 5 ] in
let series = [ 1.; 2.; 3.; 4.; 5.; 5.; 4.; 3.; 2.; 1. ] in
List.ite... |
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 ... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RosettaCode
{
class Program
{
static void Main(string[] args)
{
Func<TimeSpan, double> TimeToDegrees = (time) =>
360 * time.Hours / 24.0 +
360 * time.Min... |
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.... | #Agda | Agda |
module Avl where
-- The Peano naturals
data Nat : Set where
z : Nat
s : Nat -> Nat
-- An AVL tree's type is indexed by a natural.
-- Avl N is the type of AVL trees of depth N. There arj 3 different
-- node constructors:
-- Left: The left subtree is one level deeper than the right
-- Balanced: The subtrees h... |
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 ... | #Aime | Aime | real
mean(list l)
{
integer i;
real x, y;
x = y = 0;
i = 0;
while (i < l_length(l)) {
x += Gcos(l[i]);
y += Gsin(l[i]);
i += 1;
}
return Gatan2(y / l_length(l), x / l_length(l));
}
integer
main(void)
{
o_form("mean of 1st set: /d6/\n", mean(l_effect(350, 1... |
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 ... | #ALGOL_68 | ALGOL 68 | #!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #
PROC mean angle = ([]#LONG# REAL angles)#LONG# REAL:
(
INT size = UPB angles - LWB angles + 1;
#LONG# REAL y part := 0, x part := 0;
FOR i FROM LWB angles TO UPB angles DO
x part +:= #long# cos (angles[i] * #long# pi / 180);
y part +:= #long# sin ... |
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 ... | #Ada | Ada | with Ada.Text_IO, Ada.Float_Text_IO;
procedure FindMedian is
f: array(1..10) of float := ( 4.4, 2.3, -1.7, 7.5, 6.6, 0.0, 1.9, 8.2, 9.3, 4.5 );
min_idx: integer;
min_val, median_val, swap: float;
begin
for i in f'range loop
min_idx := i;
min_val := f(i);
for j in i+1 .. f'l... |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of p... | #EchoLisp | EchoLisp |
(define (A xs) (// (for/sum ((x xs)) x) (length xs)))
(define (G xs) (expt (for/product ((x xs)) x) (// (length xs))))
(define (H xs) (// (length xs) (for/sum ((x xs)) (// x))))
(define xs (range 1 11))
(and (>= (A xs) (G xs)) (>= (G xs) (H xs)))
→ #t
|
http://rosettacode.org/wiki/Balanced_ternary | Balanced ternary | Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1.
Examples
Decimal 11 = 32 + 31 − 30, thus it can be written as "++−"
Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0"
... | #Common_Lisp | Common Lisp | ;;; balanced ternary
;;; represented as a list of 0, 1 or -1s, with least significant digit first
;;; convert ternary to integer
(defun bt-integer (b)
(reduce (lambda (x y) (+ x (* 3 y))) b :from-end t :initial-value 0))
;;; convert integer to ternary
(defun integer-bt (n)
(if (zerop n) nil
(case (mod n 3)
... |
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.... | #Limbo | Limbo | implement Babbage;
include "sys.m";
sys: Sys;
print: import sys;
include "draw.m";
draw: Draw;
Babbage : module
{
init : fn(ctxt : ref Draw->Context, args : list of string);
};
init (ctxt: ref Draw->Context, args: list of string)
{
sys = load Sys Sys->PATH;
current := 0;
while ((current * current) % 100000... |
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.... | #Lua | Lua | -- get smallest number <= sqrt(269696)
k = math.floor(math.sqrt(269696))
-- if root is odd -> make it even
if k % 2 == 1 then
k = k - 1
end
-- cycle through numbers
while not ((k * k) % 1000000 == 269696) do
k = k + 2
end
io.write(string.format("%d * %d = %d\n", k, k, k * k)) |
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) ... | #ARM_Assembly | ARM Assembly |
.data
balanced_message:
.ascii "OK\n"
unbalanced_message:
.ascii "NOT OK\n"
.text
.equ balanced_msg_len, 3
.equ unbalanced_msg_len, 7
BalancedBrackets:
mov r1, #0
mov r2, #0
mov r3, #0
process_bracket:
ldrb r2, [r0, r1]
cmp r2, #0
beq evaluate_balance
cmp r2, #'['
... |
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 appropriat... | #E | E | pragma.enable("accumulator")
def mode(values) {
def counts := [].asMap().diverge()
var maxCount := 0
for v in values {
maxCount max= (counts[v] := counts.fetch(v, fn{0}) + 1)
}
return accum [].asSet() for v => ==maxCount in counts { _.with(v) }
} |
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an avera... | #Oforth | Oforth | import: parallel
: createSMA(period)
| ch |
Channel new [ ] over send drop ->ch
#[ ch receive + left(period) dup avg swap ch send drop ] ; |
http://rosettacode.org/wiki/Averages/Mean_time_of_day | Averages/Mean time of day | Task[edit]
A particular activity of bats occurs at these times of the day:
23:00:17, 23:40:20, 00:12:45, 00:17:19
Using the idea that there are twenty-four hours in a day,
which is analogous to there being 360 degrees in a circle,
map times of day to and from angles;
and using the ideas of Averages/Mean angle
compute ... | #C.2B.2B | C++ | #include <iomanip>
#include <iostream>
#include <vector>
#define _USE_MATH_DEFINES
#include <math.h>
struct Time {
int hour, minute, second;
friend std::ostream &operator<<(std::ostream &, const Time &);
};
std::ostream &operator<<(std::ostream &os, const Time &t) {
return os << std::setfill('0')
... |
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.... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program avltree2.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/***************************************... |
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 ... | #AutoHotkey | AutoHotkey | Angles := [[350, 10], [90, 180, 270, 360], [10, 20, 30]]
MsgBox, % MeanAngle(Angles[1]) "`n"
. MeanAngle(Angles[2]) "`n"
. MeanAngle(Angles[3])
MeanAngle(a, x=0, y=0) {
static c := ATan(1) / 45
for k, v in a {
x += Cos(v * c) / a.MaxIndex()
y += Sin(v * c) / a.MaxIndex()
}
return atan2(x, y) / c
}
atan... |
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 ... | #ALGOL_68 | ALGOL 68 | INT max_elements = 1000000;
# Return the k-th smallest item in array x of length len #
PROC quick_select = (INT k, REF[]REAL x) REAL:
BEGIN
PROC swap = (INT a, b) VOID:
BEGIN
REAL t = x[a];
x[a] := x[b]; x[b] := t
END;
INT left := 1, right := UPB x;
INT pos, i;
... |
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 p... | #Elixir | Elixir | defmodule Means do
def arithmetic(list) do
Enum.sum(list) / length(list)
end
def geometric(list) do
:math.pow(Enum.reduce(list, &(*/2)), 1 / length(list))
end
def harmonic(list) do
1 / arithmetic(Enum.map(list, &(1 / &1)))
end
end
list = Enum.to_list(1..10)
IO.puts "Arithmetic mean: #{am = ... |
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"
... | #D | D | import std.stdio, std.bigint, std.range, std.algorithm;
struct BalancedTernary {
// Represented as a list of 0, 1 or -1s,
// with least significant digit first.
enum Dig : byte { N=-1, Z=0, P=+1 } // Digit.
const Dig[] digits;
// This could also be a BalancedTernary template argument.
static... |
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.... | #M2000_Interpreter | M2000 Interpreter | Def Long k=1000000, T=269696, n
n=Sqrt(269696)
For n=n to k {
If n^2 mod k = T Then Exit
}
Report format$("The smallest number whose square ends in {0} is {1}, Its square is {2}", T, n, n**2)
|
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p.... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Solve[Mod[x^2, 10^6] == 269696 && 0 <= x <= 99736, x, Integers] |
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) ... | #Arturo | Arturo | isBalanced: function [s][
cnt: 0
loop split s [ch][
if? ch="]" [
cnt: cnt-1
if cnt<0 -> return false
]
else [
if ch="[" -> cnt: cnt+1
]
]
cnt=0
]
loop 1..10 'i [
str: join map 0..(2*i)-1 [x][ sample ["[" "]"]]
prints str
if? isBalanced str -> print " OK"
else -> print " Not... |
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 appropriat... | #EchoLisp | EchoLisp |
(define (modes L)
(define G (group* L)) ;; sorts and group equal items
(define cardmax (for/max [(g G)] (length g)))
(map first (filter (lambda(g) (= cardmax (length g))) G)))
(modes '( a b c a d e f))
→ (a)
(modes (iota 6))
→ (0 1 2 3 4 5)
(modes '(x))
→ (x)
(modes '(🎾 🏉 ☕️ 🎾 🎲 🎯 🎺 ☕️ 🎲 🎸 🎻... |
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 avera... | #ooRexx | ooRexx |
testdata = .array~of(1, 2, 3, 4, 5, 5, 4, 3, 2, 1)
-- run with different period sizes
loop period over .array~of(3, 5)
say "Period size =" period
say
movingaverage = .movingaverage~new(period)
loop number over testdata
average = movingaverage~addnumber(number)
say " Next number =" ... |
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 ... | #Common_Lisp | Common Lisp | ;; * Loading the split-sequence library
(eval-when (:compile-toplevel :load-toplevel :execute)
(ql:quickload '("split-sequence")))
;; * The package definition
(defpackage :mean-time-of-day
(:use :common-lisp :iterate :split-sequence))
(in-package :mean-time-of-day)
;; * The data
(defparameter *time-values*
'(... |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.