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 p... | #Factor | Factor | : a-mean ( seq -- mean )
[ sum ] [ length ] bi / ;
: g-mean ( seq -- mean )
[ product ] [ length recip ] bi ^ ;
: h-mean ( seq -- mean )
[ length ] [ [ recip ] map-sum ] bi / ; |
http://rosettacode.org/wiki/Balanced_ternary | Balanced ternary | Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1.
Examples
Decimal 11 = 32 + 31 − 30, thus it can be written as "++−"
Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0"
... | #Groovy | Groovy | enum T {
m('-', -1), z('0', 0), p('+', 1)
final String symbol
final int value
private T(String symbol, int value) {
this.symbol = symbol
this.value = value
}
static T get(Object key) {
switch (key) {
case [m.value, m.symbol] : return m
case [... |
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.... | #OCaml | OCaml |
let rec f a=
if (a*a) mod 1000000 != 269696
then f(a+1)
else a
in
let a= f 1 in
Printf.printf "smallest positive integer whose square ends in the digits 269696 is %d\n" a
|
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) ... | #Batch_File | Batch File | :: Balanced Brackets Task from Rosetta Code
:: Batch File Implementation
@echo off
setlocal enabledelayedexpansion
set "num_pairs=10"
set "num_strings=10"
:: the main thing
for /l %%s in (1, 1, %num_strings%) do (
call :generate
call :check
)
echo(
pause
exit /b 0
:: generate strings of brackets
:generate... |
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... | #GAP | GAP | mode := function(v)
local c, m;
c := Collected(SortedList(v));
m := Maximum(List(c, x -> x[2]));
return List(Filtered(c, x -> x[2] = m), y -> y[1]);
end;
mode([ 7, 5, 6, 1, 5, 5, 7, 12, 17, 6, 6, 5, 12, 3, 6 ]);
# [ 5, 6 ] |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin... | #Ada | Ada | with Ada.Float_Text_Io; use Ada.Float_Text_Io;
with Ada.Text_IO; use Ada.Text_IO;
procedure Mean_Main is
type Vector is array (Positive range <>) of Float;
function Mean (Item : Vector) return float with pre => Item'length > 0;
function Mean (Item : Vector) return Float is
Sum : Float := 0.0;
begin
... |
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 associativ... | #AppleScript | AppleScript | set baseRecord to {|name|:"Rocket Skates", price:12.75, |color|:"yellow"}
set updateRecord to {price:15.25, |color|:"red", |year|:1974}
set mergedRecord to updateRecord & baseRecord
return mergedRecord |
http://rosettacode.org/wiki/Associative_array/Merging | Associative array/Merging | Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Merge these into a new associativ... | #Arturo | Arturo | details: #[name: "Rocket Skates" price: 12.75 colour: 'yellow]
newDetails: extend details #[price: 15.25 colour: 'red year: 1974]
print newDetails |
http://rosettacode.org/wiki/Associative_array/Merging | Associative array/Merging | Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Merge these into a new associativ... | #AutoHotkey | AutoHotkey | merge(base, update){
Merged := {}
for k, v in base
Merged[k] := v
for k, v in update
Merged[k] := v
return Merged
} |
http://rosettacode.org/wiki/Average_loop_length | Average loop length | Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t... | #Clojure | Clojure | (ns cyclelengths
(:gen-class))
(defn factorial [n]
" n! "
(apply *' (range 1 (inc n)))) ; Use *' (vs. *) to allow arbitrary length arithmetic
(defn pow [n i]
" n^i"
(apply *' (repeat i n)))
(defn analytical [n]
" Analytical Computation "
(->>(range 1 (inc n))
(map #(/ (factorial n)... |
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... | #Picat | Picat | main =>
L=[1, 2, 3, 4, 5, 5, 4, 3, 2, 1],
Map3 = new_map([p=3]),
Map5 = new_map([p=5]),
foreach(N in L)
printf("n: %-2d sma3: %-17w sma5: %-17w\n",N, sma(N,Map3), sma(N,Map5))
end.
sma(N,Map) = Average =>
Stream = Map.get(stream,[]) ++ [N],
if Stream.len > Map.get(p) then
Stream := Stream.tail
... |
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.... | #BASIC | BASIC | 10 DEFINT A-Z
20 M=120
30 DIM C(M): C(0)=-1: C(1)=-1
40 FOR I=2 TO SQR(M)
50 IF NOT C(I) THEN FOR J=I+I TO M STEP I: C(J)=-1: NEXT
60 NEXT
70 FOR I=2 TO M
80 N=I: C=0
90 FOR J=2 TO M
100 IF NOT C(J) THEN IF N MOD J=0 THEN N=N\J: C=C+1: GOTO 100
110 NEXT
120 IF NOT C(C) THEN PRINT I,
130 NEXT |
http://rosettacode.org/wiki/Attractive_numbers | Attractive numbers | A number is an attractive number if the number of its prime factors (whether distinct or not) is also prime.
Example
The number 20, whose prime decomposition is 2 × 2 × 5, is an attractive number because the number of its prime factors (3) is also prime.
Task
Show sequence items up to 120.... | #BCPL | BCPL | get "libhdr"
manifest $( MAXIMUM = 120 $)
let sieve(prime, max) be
$( for i=0 to max do i!prime := i>=2
for i=2 to max>>1 if i!prime
$( let j = i<<1
while j <= max do
$( j!prime := false
j := j+i
$)
$)
$)
let factors(n, prime, max) = valof
$( let count = 0
fo... |
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 ... | #Factor | Factor | USING: arrays formatting kernel math math.combinators
math.functions math.libm math.parser math.trig qw sequences
splitting ;
IN: rosetta-code.mean-time
CONSTANT: input qw{ 23:00:17 23:40:20 00:12:45 00:17:19 }
: time>deg ( hh:mm:ss -- x )
":" split [ string>number ] map first3
[ 15 * ] [ 1/4 * ] [ 1/240 * ... |
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 ... | #Fortran | Fortran |
program mean_time_of_day
implicit none
integer(kind=4), parameter :: dp = kind(0.0d0)
type time_t
integer(kind=4) :: hours, minutes, seconds
end type
character(len=8), dimension(4), parameter :: times = &
(/ '23:00:17', '23:40:20', '00:12:45', '00:17:19' /)
real(kind=dp), dimension(size(times)... |
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.... | #Fortran | Fortran | module avl_trees
!
! References:
!
! * Niklaus Wirth, 1976. Algorithms + Data Structures =
! Programs. Prentice-Hall, Englewood Cliffs, New Jersey.
!
! * Niklaus Wirth, 2004. Algorithms and Data Structures. Updated
! by Fyodor Tkachov, 2014.
!
implicit none
private
! The type for... |
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 ... | #Elixir | Elixir |
defmodule MeanAngle do
def mean_angle(angles) do
rad_angles = Enum.map(angles, °_to_rad/1)
sines = rad_angles |> Enum.map(&:math.sin/1) |> Enum.sum
cosines = rad_angles |> Enum.map(&:math.cos/1) |> Enum.sum
rad_to_deg(:math.atan2(sines, cosines))
end
defp deg_to_rad(a) do
(:math.pi/18... |
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 ... | #Erlang | Erlang |
-module( mean_angle ).
-export( [from_degrees/1, task/0] ).
from_degrees( Angles ) ->
Radians = [radians(X) || X <- Angles],
Sines = [math:sin(X) || X <- Radians],
Coses = [math:cos(X) || X <- Radians],
degrees( math:atan2( average(Sines), average(Coses) ) ).
task() ->
Angles = [[350, 10], [90, 180, 270, 360... |
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 ... | #BBC_BASIC | BBC BASIC | INSTALL @lib$+"SORTLIB"
Sort% = FN_sortinit(0,0)
DIM a(6), b(5)
a() = 4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2
b() = 4.1, 7.2, 1.7, 9.3, 4.4, 3.2
PRINT "Median of a() is " ; FNmedian(a())
PRINT "Median of b() is " ; FNmedian(b())
END
DEF FNmedian(a())
LOCAL C%
... |
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... | #Fantom | Fantom |
class Main
{
static Float arithmeticMean (Int[] nums)
{
if (nums.size == 0) return 0.0f
sum := 0
nums.each |n| { sum += n }
return sum.toFloat / nums.size
}
static Float geometricMean (Int[] nums)
{
if (nums.size == 0) return 0.0f
product := 1
nums.each |n| { product *= n }
... |
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"
... | #Haskell | Haskell | data BalancedTernary = Bt [Int]
zeroTrim a = if null s then [0] else s where
s = fst $ foldl f ([],[]) a
f (x,y) 0 = (x, y++[0])
f (x,y) z = (x++y++[z], [])
btList (Bt a) = a
instance Eq BalancedTernary where
(==) a b = btList a == btList b
btNormalize = listBt . _carry 0 where
_carry c [] = if c == 0 then... |
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.... | #Ol | Ol |
(print
(let loop ((i 2))
(if (eq? (mod (* i i) 1000000) 269696)
i
(loop (+ i 1)))))
|
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) ... | #BBC_BASIC | BBC BASIC | FOR x%=1 TO 10
test$=FNgenerate(RND(10))
PRINT "Bracket string ";test$;" is ";FNvalid(test$)
NEXT x%
END
:
DEFFNgenerate(n%)
LOCAL l%,r%,t%,output$
WHILE l%<n% AND r%<n%
CASE RND(2) OF
WHEN 1:
l%+=1
output$+="["
WHEN 2:
r%+=1
output$+="]"
ENDCASE
ENDWHILE
IF l%=n% THEN output$+=STR... |
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 t... | #8th | 8th | var bucket
var bucket-size
\ The 'bucket' will be a simple array of some values:
: genbucket \ n --
a:new swap
(
\ make a random int up to 1000
rand-pcg n:abs 1000 n:mod
a:push
) swap times
bucket ! ;
\ display bucket and its total:
: .bucket
bucket lock @
dup . space
' n:+ 0 a:redu... |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #11l | 11l | V a = 5
assert(a == 42)
assert(a == 42, ‘Error message’) |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat... | #Go | Go | package main
import "fmt"
func main() {
fmt.Println(mode([]int{2, 7, 1, 8, 2}))
fmt.Println(mode([]int{2, 7, 1, 8, 2, 8}))
}
func mode(a []int) []int {
m := make(map[int]int)
for _, v := range a {
m[v]++
}
var mode []int
var n int
for k, v := range m {
switch {
... |
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 conveyin... | #Aime | Aime | real
mean(list l)
{
real sum, x;
sum = 0;
for (, x in l) {
sum += x;
}
sum / ~l;
}
integer
main(void)
{
o_form("%f\n", mean(list(4.5, 7.25, 5r, 5.75)));
0;
} |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin... | #ALGOL_68 | ALGOL 68 | PROC mean = (REF[]REAL p)REAL:
# Calculates the mean of qty REALs beginning at p. #
IF LWB p > UPB p THEN 0.0
ELSE
REAL total := 0.0;
FOR i FROM LWB p TO UPB p DO total +:= p[i] OD;
total / (UPB p - LWB p + 1)
FI;
main:(
[6]REAL test := (1.0, 2.0, 5.0, -5.0, 9.5, 3.14159);
print((mean(test),new... |
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 associativ... | #AWK | AWK |
# syntax: GAWK -f ASSOCIATIVE_ARRAY_MERGING.AWK
#
# sorting:
# PROCINFO["sorted_in"] is used by GAWK
# SORTTYPE is used by Thompson Automation's TAWK
#
BEGIN {
PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 1
arr1["name"] = "Rocket Skates"
arr1["price"] = "12.75"
arr1["color"] = "yellow"
... |
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 associativ... | #B4X | B4X | Dim m1 As Map = CreateMap("name": "Rocket Skates", "price": 12.75, "color": "yellow")
Dim m2 As Map = CreateMap("price": 15.25, "color": "red", "year": 1974)
Dim merged As Map
merged.Initialize
For Each m As Map In Array(m1, m2)
For Each key As Object In m.Keys
merged.Put(key, m.Get(key))
Next
Next
Log(merged) |
http://rosettacode.org/wiki/Average_loop_length | Average loop length | Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t... | #D | D | import std.stdio, std.random, std.math, std.algorithm, std.range, std.format;
real analytical(in int n) pure nothrow @safe /*@nogc*/ {
enum aux = (int k) => reduce!q{a * b}(1.0L, iota(n - k + 1, n + 1));
return iota(1, n + 1)
.map!(k => (aux(k) * k ^^ 2) / (real(n) ^^ (k + 1)))
.sum;
}
... |
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... | #PicoLisp | PicoLisp | (de sma (@Len)
(curry (@Len (Data)) (N)
(push 'Data N)
(and (nth Data @Len) (con @)) # Truncate
(*/ (apply + Data) (length Data)) ) ) |
http://rosettacode.org/wiki/Attractive_numbers | Attractive numbers | A number is an attractive number if the number of its prime factors (whether distinct or not) is also prime.
Example
The number 20, whose prime decomposition is 2 × 2 × 5, is an attractive number because the number of its prime factors (3) is also prime.
Task
Show sequence items up to 120.... | #C | C | #include <stdio.h>
#define TRUE 1
#define FALSE 0
#define MAX 120
typedef int bool;
bool is_prime(int n) {
int d = 5;
if (n < 2) return FALSE;
if (!(n % 2)) return n == 2;
if (!(n % 3)) return n == 3;
while (d *d <= n) {
if (!(n % d)) return FALSE;
d += 2;
if (!(n % d))... |
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 ... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Const pi As Double = 3.1415926535897932
Function meanAngle(angles() As Double) As Double
Dim As Integer length = Ubound(angles) - Lbound(angles) + 1
Dim As Double sinSum = 0.0
Dim As Double cosSum = 0.0
For i As Integer = LBound(angles) To UBound(angles)
sinSum += Sin(angles(i) * pi / ... |
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.... | #Generic | Generic |
space system
{
enum state
{
header
balanced
left_high
right_high
}
enum direction
{
from_left
from_right
}
class node
{
left
right
parent
balance
data
node()
{
left = this
right = this
balance = state.header
parent = null
data... |
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 ... | #Euler_Math_Toolbox | Euler Math Toolbox | >function meanangle (a) ...
$ z=sum(exp(rad(a)*I));
$ if z~=0 then error("Not meaningful");
$ else return deg(arg(z))
$ endfunction
>meanangle([350,10])
0
>meanangle([90,180,270,360])
Error : Not meaningful
Error generated by error() command
Error in function meanangle in line
if z~=0 then error("Not meani... |
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 ... | #Euphoria | Euphoria |
include std/console.e
include std/mathcons.e
sequence AngleList = {{350,10},{90,180,270,360},{10,20,30}}
function atan2(atom y, atom x)
return 2*arctan((sqrt(power(x,2)+power(y,2)) - x)/y)
end function
function MeanAngle(sequence angles)
atom x = 0, y = 0
integer l = length(angles)
for i = 1 to length(ang... |
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 ... | #BQN | BQN | Median ← (+´÷≠)∧⊏˜2⌊∘÷˜¯1‿0+≠
Median 5.961475‿2.025856‿7.262835‿1.814272‿2.281911‿4.854716 |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches ... | #Bracmat | Bracmat | (median=
begin decimals end int list med med1 med2 num number
. 0:?list
& whl
' ( @( !arg
: ?
((%@:~" ":~",") ?:?number)
((" "|",") ?arg|:?arg)
)
& @( !number
: ( #?int "." [?begin #?decimals [?end
& !int+!decimals*10^(!begin+-1*!en... |
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... | #Forth | Forth | : famean ( faddr n -- f )
0e
tuck floats bounds do
i f@ f+
float +loop
0 d>f f/ ;
: fgmean ( faddr n -- f )
1e
tuck floats bounds do
i f@ f*
float +loop
0 d>f 1/f f** ;
: fhmean ( faddr n -- f )
dup 0 d>f 0e
floats bounds do
i f@ 1/f f+
float +loop
f/ ;
create test 1e f, 2e f,... |
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"
... | #Icon_and_Unicon | Icon and Unicon | procedure main()
a := "+-0++0+"
write("a = +-0++0+"," = ",cvtFromBT("+-0++0+"))
write("b = -436 = ",b := cvtToBT(-436))
c := "+-++-"
write("c = +-++- = ",cvtFromBT("+-++-"))
d := mul(a,sub(b,c))
write("a(b-c) = ",d," = ",cvtFromBT(d))
end
procedure bTrim(s)
return s[upto('+-',s):0] | "... |
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.... | #PARI.2FGP | PARI/GP | m=269696;
k=1000000;
{for(n=1,99736,
\\ Try each number in this range, from 1 to 99736
if(denominator((n^2-m)/k)==1, \\ Check if n squared, minus m, is divisible by k
return(n) \\ If so, return this number and STOP.
)
)} |
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) ... | #Befunge | Befunge | v > "KO TON" ,,,,,, v
> ~ : 25*- #v_ $ | > 25*, @
> "KO" ,, ^
> : 1991+*+- #v_ v
> \ : 1991+*+- #v_v
\ $
^ < <$< |
http://rosettacode.org/wiki/Atomic_updates | Atomic updates |
Task
Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to:
get the current value of any bucket
remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the t... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
procedure Test_Updates is
type Bucket_Index is range 1..13;
package Random_Index is new Ada.Numerics.Discrete_Random (Bucket_Index);
use Random_Index;
type Buckets is array (Bucket_Index) of Natural;
protected type Safe_Buckets ... |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #68000_Assembly | 68000 Assembly | CMP.L #42,D0
BEQ continue
ILLEGAL ;jumps to Trap 4. Alternatively, other trap numbers could have been chosen with the "TRAP #" command.
continue:
; rest of program |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Ada | Ada | pragma Assert (A = 42, "Oops!"); |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Aime | Aime | integer x;
x = 41;
if (x != 42) {
error("x is not 42");
} |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat... | #Groovy | Groovy | def mode(Iterable col) {
assert col
def m = [:]
col.each {
m[it] = m[it] == null ? 1 : m[it] + 1
}
def keys = m.keySet().sort { -m[it] }
keys.findAll { m[it] == m[keys[0]] }
} |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin... | #ALGOL_W | ALGOL W | begin
% procedure to find the mean of the elements of a vector. %
% As the procedure can't find the bounds of the array for itself, %
% we pass them in lb and ub %
real procedure mean ( real array vector ( * )
; integer value lb
... |
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 conveyin... | #AmigaE | AmigaE | PROC mean(l:PTR TO LONG)
DEF m, i, ll
ll := ListLen(l)
IF ll = 0 THEN RETURN 0.0
m := 0.0
FOR i := 0 TO ll-1 DO m := !m + l[i]
m := !m / (ll!)
ENDPROC m
PROC main()
DEF s[20] : STRING
WriteF('mean \s\n',
RealF(s,mean([1.0, 2.0, 3.0, 4.0, 5.0]), 2))
ENDPROC |
http://rosettacode.org/wiki/Associative_array/Merging | Associative array/Merging | Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Merge these into a new associativ... | #BaCon | BaCon | DECLARE base$, update$, merge$ ASSOC STRING
base$("name") = "Rocket Skates"
base$("price") = "12.75"
base$("color") = "yellow"
PRINT "Base array"
FOR x$ IN OBTAIN$(base$)
PRINT x$, " : ", base$(x$)
NEXT
update$("price") = "15.25"
update$("color") = "red"
update$("year") = "1974"
PRINT NL$, "Update array"
FO... |
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 associativ... | #C.2B.2B | C++ | #include <iostream>
#include <string>
#include <map>
template<typename map_type>
map_type merge(const map_type& original, const map_type& update) {
map_type result(update);
result.insert(original.begin(), original.end());
return result;
}
int main() {
typedef std::map<std::string, std::string> map;
... |
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 t... | #Delphi | Delphi |
program Average_loop_length;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Math;
const
MAX_N = 20;
TIMES = 1000000;
function Factorial(const n: Double): Double;
begin
Result := 1;
if n > 1 then
Result := n * Factorial(n - 1);
end;
function Expected(const n: Integer): Double;
var
i: Integ... |
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... | #PL.2FI | PL/I | SMA: procedure (N) returns (float byaddr);
declare N fixed;
declare A(*) fixed controlled,
(p, q) fixed binary static initial (0);
if allocation(A) = 0 then signal error;
p = p + 1; if q < 20 then q = q + 1;
if p > hbound(A, 1) then p = 1;
A(p) = N;
return (sum(float(A))/q);
I: ENT... |
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.... | #C.23 | C# | using System;
namespace AttractiveNumbers {
class Program {
const int MAX = 120;
static bool IsPrime(int n) {
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
if (n % 3 == 0) return n == 3;
int d = 5;
while (d * d <= n) {
... |
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 ... | #Go | Go | package main
import (
"errors"
"fmt"
"log"
"math"
"time"
)
var inputs = []string{"23:00:17", "23:40:20", "00:12:45", "00:17:19"}
func main() {
tList := make([]time.Time, len(inputs))
const clockFmt = "15:04:05"
var err error
for i, s := range inputs {
tList[i], err = ti... |
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.... | #Go | Go | package avl
// AVL tree adapted from Julienne Walker's presentation at
// http://eternallyconfuzzled.com/tuts/datastructures/jsw_tut_avl.aspx.
// This port uses similar indentifier names.
// The Key interface must be supported by data stored in the AVL tree.
type Key interface {
Less(Key) bool
Eq(Key) bool
... |
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 ... | #F.23 | F# | open System
open System.Numerics
let deg2rad d = d * Math.PI / 180.
let rad2deg r = r * 180. / Math.PI
[<EntryPoint>]
let main argv =
let makeComplex = fun r -> Complex.FromPolarCoordinates(1., r)
argv
|> Seq.map (Double.Parse >> deg2rad >> makeComplex)
|> Seq.fold (fun x y -> Complex.Add(x,y)) Com... |
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 ... | #Factor | Factor | USING: formatting kernel math math.functions math.libm math.trig
sequences ;
: mean-angle ( seq -- x )
[ deg>rad ] map [ [ sin ] map-sum ] [ [ cos ] map-sum ]
[ length ] tri recip [ * ] curry bi@ fatan2 rad>deg ;
: show ( seq -- )
dup mean-angle "The mean angle of %u is: %f°\n" printf ;
{ { 350 10 } {... |
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 ... | #C | C | #include <stdio.h>
#include <stdlib.h>
typedef struct floatList {
float *list;
int size;
} *FloatList;
int floatcmp( const void *a, const void *b) {
if (*(const float *)a < *(const float *)b) return -1;
else return *(const float *)a > *(const float *)b;
}
float median( FloatList fl )
{
qsort... |
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... | #Fortran | Fortran | program Mean
real :: a(10) = (/ (i, i=1,10) /)
real :: amean, gmean, hmean
amean = sum(a) / size(a)
gmean = product(a)**(1.0/size(a))
hmean = size(a) / sum(1.0/a)
if ((amean < gmean) .or. (gmean < hmean)) then
print*, "Error!"
else
print*, amean, gmean, hmean
end if
end program Mean |
http://rosettacode.org/wiki/Balanced_ternary | Balanced ternary | Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1.
Examples
Decimal 11 = 32 + 31 − 30, thus it can be written as "++−"
Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0"
... | #J | J | trigits=: 1+3 <.@^. 2 * 1&>.@|
trinOfN=: |.@((_1 + ] #: #.&1@] + [) #&3@trigits) :. nOfTrin
nOfTrin=: p.&3 :. trinOfN
trinOfStr=: 0 1 _1 {~ '0+-'&i.@|. :. strOfTrin
strOfTrin=: {&'0+-'@|. :. trinOfStr
carry=: +//.@:(trinOfN"0)^:_
trimLead0=: (}.~ i.&1@:~:&0)&.|.
add=: carry@(+/@,:)
neg=: -
mul=: trimLead0@carry@(+/... |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p.... | #Pascal | Pascal | program BabbageProblem;
(* Anything bracketed off like this is an explanatory comment. *)
var n : longint; (* The VARiable n can hold a 'long', ie large, INTeger. *)
begin
n := 2; (* Start with n equal to 2. *)
repeat
n := n + 2 (* Increase n by 2. *)
until (n * n) mod 1000000 = 269696;
(* 'n * n' m... |
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 8t... | #Ada | Ada |
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Generic_Elementary_Functions;
procedure Main is
type Real is digits 18;
package Real_Funcs is new Ada.Numerics.Generic_Elementary_Functions(Real);
use Real_Funcs;
package Real_IO is new Ada.Text_IO.Float_IO(Real);
use Real_IO;
function Approx_... |
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) ... | #BQN | BQN | ⟨l, r | l·r = e⟩ |
http://rosettacode.org/wiki/Atomic_updates | Atomic updates |
Task
Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to:
get the current value of any bucket
remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the t... | #AutoHotkey | AutoHotkey | Bucket := [], Buckets := 10, Originaltotal = 0
loop, %Buckets% {
Random, rnd, 0,50
Bucket[A_Index] := rnd, Originaltotal += rnd
}
loop 100
{
total := 0
Randomize(B1, B2, Buckets)
temp := (Bucket[B1] + Bucket[B2]) /2
Bucket[B1] := floor(temp), Bucket[B2] := Ceil(temp) ; values closer to equal
Randomize(B1, B... |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #ALGOL_68 | ALGOL 68 | INT a, b; read((a, b)) PR ASSERT a >= 0 & b > 0 PR;
|
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #ALGOL_W | ALGOL W | begin
integer a;
a := 43;
assert a = 42;
write( "this won't appear" )
end. |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Apex | Apex |
String myStr = 'test;
System.assert(myStr == 'something else', 'Assertion Failed Message');
|
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat... | #Haskell | Haskell | import Prelude (foldr, maximum, (==), (+))
import Data.Map (insertWith', empty, filter, elems, keys)
mode :: (Ord a) => [a] -> [a]
mode xs = keys (filter (== maximum (elems counts)) counts)
where counts = foldr (\x -> insertWith' (+) x 1) empty xs |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin... | #AntLang | AntLang | avg[list] |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin... | #APL | APL | X←3 1 4 1 5 9
(+/X)÷⍴X
3.833333333 |
http://rosettacode.org/wiki/Associative_array/Merging | Associative array/Merging | Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Merge these into a new associativ... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main() {
var baseData = new Dictionary<string, object> {
["name"] = "Rocket Skates",
["price"] = 12.75,
["color"] = "yellow"
};
var updateData = ... |
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 t... | #EchoLisp | EchoLisp |
(lib 'math) ;; Σ aka (sigma f(n) nfrom nto)
(define (f-count N (times 100000))
(define count 0)
(for ((i times))
;; new random f mapping from 0..N-1 to 0..N-1
;; (f n) is NOT (random N)
;; because each call (f n) must return the same value
(define f (build-vector N (lambda(i) (ran... |
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... | #Pony | Pony |
class MovingAverage
let period: USize
let _arr: Array[I32] // circular buffer
var _curr: USize // index of pointer position
var _total: I32 // cache the total so far
new create(period': USize) =>
period = period'
_arr = Array[I32](period) // preallocate space
_curr = 0
_total = 0
fu... |
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.... | #C.2B.2B | C++ | #include <iostream>
#include <iomanip>
#define MAX 120
using namespace std;
bool is_prime(int n) {
if (n < 2) return false;
if (!(n % 2)) return n == 2;
if (!(n % 3)) return n == 3;
int d = 5;
while (d *d <= n) {
if (!(n % d)) return false;
d += 2;
if (!(n % d)) retu... |
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 ... | #Groovy | Groovy | import static java.lang.Math.*
final format = 'HH:mm:ss', clock = PI / 12, millisPerHr = 3600*1000
final tzOffset = new Date(0).timezoneOffset / 60
def parseTime = { time -> (Date.parse(format, time).time / millisPerHr) - tzOffset }
def formatTime = { time -> new Date((time + tzOffset) * millisPerHr as int).format(... |
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.... | #Haskell | Haskell | data Tree a
= Leaf
| Node
Int
(Tree a)
a
(Tree a)
deriving (Show, Eq)
foldTree :: Ord a => [a] -> Tree a
foldTree = foldr insert Leaf
height :: Tree a -> Int
height Leaf = -1
height (Node h _ _ _) = h
depth :: Tree a -> Tree a -> Int
depth a b = succ (max (height a) (height b))
ins... |
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 ... | #Fortran | Fortran |
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Mon Jun 3 18:07:59
!
!a=./f && make $a && OMP_NUM_THREADS=2 $a
!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f
! -7.80250048E-06 350 10
! 90.0000000 90 1... |
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 ... | #C.23 | C# | using System;
using System.Linq;
namespace Test
{
class Program
{
static void Main()
{
double[] myArr = new double[] { 1, 5, 3, 6, 4, 2 };
myArr = myArr.OrderBy(i => i).ToArray();
// or Array.Sort(myArr) for in-place sort
int mid = myArr.Leng... |
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... | #FreeBASIC | FreeBASIC |
' FB 1.05.0 Win64
Function ArithmeticMean(array() As Double) As Double
Dim length As Integer = Ubound(array) - Lbound(array) + 1
Dim As Double sum = 0.0
For i As Integer = LBound(array) To UBound(array)
sum += array(i)
Next
Return sum/length
End Function
Function GeometricMean(array() As Double) As ... |
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"
... | #Java | Java |
/*
* Test case
* With balanced ternaries a from string "+-0++0+", b from native integer -436, c "+-++-":
* Write out a, b and c in decimal notation;
* Calculate a × (b − c), write out the result in both ternary and decimal notations.
*/
public class BalancedTernary
{
public static void main(String[] args)
{... |
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.... | #Perl | Perl | #!/usr/bin/perl
use strict ;
use warnings ;
my $current = 0 ;
while ( ($current ** 2 ) % 1000000 != 269696 ) {
$current++ ;
}
print "The square of $current is " . ($current * $current) . " !\n" ; |
http://rosettacode.org/wiki/Approximate_equality | Approximate equality | Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the
difference in floating point calculations between different language implementations becomes significant.
For example, a difference between 32 bit and 64 bit floating point calculations may appear by
about the 8t... | #ALGOL_68 | ALGOL 68 | BEGIN # test REAL values for approximate equality #
# returns TRUE if value is approximately equal to other, FALSE otherwide #
PROC approx equals = ( REAL value, REAL other, REAL epsilon )BOOL: ABS ( value - other ) < epsilon;
# shows the result of testing a for approximate equality with b #
PROC test =... |
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 8t... | #AWK | AWK |
# syntax: GAWK -f APPROXIMATE_EQUALITY.AWK
# converted from C#
BEGIN {
epsilon = 1
while (1 + epsilon != 1) {
epsilon /= 2
}
printf("epsilon = %18.16g\n\n",epsilon)
main("100000000000000.01","100000000000000.011")
main("100.01","100.011")
main("10000000000000.001"/"10000.0","10000000... |
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) ... | #Bracmat | Bracmat | ( (bal=|"[" !bal "]" !bal)
& ( generate
= a j m n z N S someNumber
. !arg:<1&
| 11^123+13^666+17^321:?someNumber
& (!arg:?n)+1:?N
& :?S
& whl
' (!n+-1:~<0:?n&"[" "]" !S:?S)
& whl
' ( !someNumber:>0
& mod$(!someNumber.!N):?j
... |
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 t... | #BBC_BASIC | BBC BASIC | INSTALL @lib$+"TIMERLIB"
DIM Buckets%(100)
FOR i% = 1 TO 100 : Buckets%(i%) = RND(10) : NEXT
tid0% = FN_ontimer(10, PROCdisplay, 1)
tid1% = FN_ontimer(11, PROCflatten, 1)
tid2% = FN_ontimer(12, PROCroughen, 1)
ON ERROR PROCcleanup : REPORT : PRINT : END
ON CLOSE PRO... |
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 t... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#include <time.h>
#include <pthread.h>
#define N_BUCKETS 15
pthread_mutex_t bucket_mutex[N_BUCKETS];
int buckets[N_BUCKETS];
pthread_t equalizer;
pthread_t randomizer;
void transfer_value(int from, int to, int howmuch)
{
bool swap... |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Arturo | Arturo | a: 42
ensure [a = 42] |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #AutoHotkey | AutoHotkey | a := 42
Assert(a > 10)
Assert(a < 42) ; throws exception
Assert(bool){
If !bool
throw Exception("Expression false", -1)
} |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #AWK | AWK |
BEGIN {
meaning = 6 * 7
assert(meaning == 42, "Integer mathematics failed")
assert(meaning == 42)
meaning = strtonum("42 also known as forty-two")
assert(meaning == 42, "Built-in function failed")
meaning = "42"
assert(meaning == 42, "Dynamic type conversion failed")
meaning = 6 * 9
assert(meaning == 42, "Fo... |
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... | #Icon_and_Unicon | Icon and Unicon | procedure main(args)
every write(!mode(args))
end
procedure mode(A)
hist := table(0)
every hist[!A] +:= 1
hist := sort(hist, 2)
modeCnt := hist[*hist][2]
every modeP := hist[*hist to 1 by -1] do {
if modeCnt = modeP[2] then suspend modeP[1]
else fail
}
end |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked ... | #11l | 11l | V d = [‘key1’ = ‘value1’, ‘key2’ = ‘value2’]
L(key, value) d
print(key‘ = ’value)
L(key) d.keys()
print(key)
L(value) d.values()
print(value) |
http://rosettacode.org/wiki/Apply_a_digital_filter_(direct_form_II_transposed) | Apply a digital filter (direct form II transposed) | Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [1]
Task
Filt... | #11l | 11l | F apply_filter(a, b, signal)
V result = [0.0] * signal.len
L(i) 0 .< signal.len
V tmp = 0.0
L(j) 0 .< min(i + 1, b.len)
tmp += b[j] * signal[i - j]
L(j) 1 .< min(i + 1, a.len)
tmp -= a[j] * result[i - j]
tmp /= a[0]
result[i] = tmp
R result
V a = [1.00000000, -... |
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 conveyin... | #AppleScript | AppleScript | on average(listOfNumbers)
set len to (count listOfNumbers)
if (len is 0) then return missing value
set sum to 0
repeat with thisNumber in listOfNumbers
set sum to sum + thisNumber
end repeat
return sum / len
end average
average({2500, 2700, 2400, 2300, 2550, 2650, 2750, 2450, 2600,... |
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 conveyin... | #Applesoft_BASIC | Applesoft BASIC | REM COLLECTION IN DATA STATEMENTS, EMPTY DATA IS THE END OF THE COLLECTION
0 READ V$
1 IF LEN(V$) = 0 THEN END
2 N = 0
3 S = 0
4 FOR I = 0 TO 1 STEP 0
5 S = S + VAL(V$)
6 N = N + 1
7 READ V$
8 IF LEN(V$) THEN NEXT
9 PRINT S / N
10000 DATA1,2,2.718,3,3.142
63999 DA... |
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 associativ... | #Clojure | Clojure |
(defn update-map [base update]
(merge base update))
(update-map {"name" "Rocket Skates"
"price" "12.75"
"color" "yellow"}
{"price" "15.25"
"color" "red"
"year" "1974"})
|
http://rosettacode.org/wiki/Associative_array/Merging | Associative array/Merging | Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Merge these into a new associativ... | #Crystal | Crystal | base = {"name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"}
update = { "price" => 15.25, "color" => "red", "year" => 1974 }
puts base.merge(update) |
http://rosettacode.org/wiki/Associative_array/Merging | Associative array/Merging | Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Merge these into a new associativ... | #Common_Lisp | Common Lisp |
(append list2 list1)
|
http://rosettacode.org/wiki/Average_loop_length | Average loop length | Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t... | #Elixir | Elixir | defmodule RC do
def factorial(0), do: 1
def factorial(n), do: Enum.reduce(1..n, 1, &(&1 * &2))
def loop_length(n), do: loop_length(n, MapSet.new)
defp loop_length(n, set) do
r = :rand.uniform(n)
if r in set, do: MapSet.size(set), else: loop_length(n, MapSet.put(set, r))
end
def task(runs) do
... |
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.