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/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.... | #ATS | ATS | (*------------------------------------------------------------------*)
#define ATS_DYNLOADFLAG 0
#include "share/atspre_staload.hats"
(*------------------------------------------------------------------*)
(*
Persistent AVL trees.
References:
* Niklaus Wirth, 1976. Algorithms + Data Structures =
... |
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 ... | #AWK | AWK | #!/usr/bin/awk -f
{
PI = atan2(0,-1);
x=0.0; y=0.0;
for (i=1; i<=NF; i++) {
p = $i*PI/180.0;
x += sin(p);
y += cos(p);
}
p = atan2(x,y)*180.0/PI;
if (p<0) p += 360;
print p;
} |
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 ... | #BBC_BASIC | BBC BASIC | *FLOAT 64
DIM angles(3)
angles() = 350,10
PRINT FNmeanangle(angles(), 2)
angles() = 90,180,270,360
PRINT FNmeanangle(angles(), 4)
angles() = 10,20,30
PRINT FNmeanangle(angles(), 3)
END
DEF FNmeanangle(angles(), N%)
LOCAL I%, sumsin, sumcos
FOR I%... |
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 ... | #AntLang | AntLang | median[list] |
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 ... | #APL | APL | median←{v←⍵[⍋⍵]⋄.5×v[⌈¯1+.5×⍴v]+v[⌊.5×⍴v]} ⍝ Assumes ⎕IO←0 |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of p... | #Erlang | Erlang | %% Author: Abhay Jain <abhay_1303@yahoo.co.in>
-module(mean_calculator).
-export([find_mean/0]).
find_mean() ->
%% This is function calling. First argument is the the beginning number
%% and second argument is the initial value of sum for AM & HM and initial value of product for GM.
arithmetic_mean(1, 0),
geometr... |
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"
... | #Elixir | Elixir | defmodule Ternary do
def to_string(t), do: ( for x <- t, do: to_char(x) ) |> List.to_string
def from_string(s), do: ( for x <- to_char_list(s), do: from_char(x) )
defp to_char(-1), do: ?-
defp to_char(0), do: ?0
defp to_char(1), do: ?+
defp from_char(?-), do: -1
defp from_char(?0), do: 0
defp from... |
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.... | #MAXScript | MAXScript | -- MAXScript : Babbage problem : N.H.
posInt = 1
while posInt < 1000000 do
(
if (matchPattern((posInt * posInt) as string) pattern: "*269696") then exit
posInt += 1
)
Print "The smallest number whose square ends in 269696 is " + ((posInt) as string)
Print "Its square is " + (((pow posInt 2) as integer) as string)
... |
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) ... | #AutoHotkey | AutoHotkey | ; Generate 10 strings with equal left and right brackets
Loop, 5
{
B = %A_Index%
loop 2
{
String =
Loop % B
String .= "[`n"
Loop % B
String .= "]`n"
Sort, String, Random
StringReplace, String, String,`n,,All
Example .= String " - " IsBalanced(String) "`n"
}
}
MsgBox % Example
return
IsBalanced(... |
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... | #Elena | Elena | import system'routines;
import system'collections;
import extensions;
extension op
{
get Mode()
{
var countMap := Dictionary.new(0);
self.forEach:(item)
{
countMap[item] := countMap[item] + 1
};
countMap := countMap.Values.sort:(p,n => p > n);
va... |
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... | #Elixir | Elixir | defmodule Average do
def mode(list) do
gb = Enum.group_by(list, &(&1))
max = Enum.map(gb, fn {_,val} -> length(val) end) |> Enum.max
for {key,val} <- gb, length(val)==max, do: key
end
end
lists = [[3,1,4,1,5,9,2,6,5,3,5,8,9],
[1, 2, "qwe", "asd", 1, 2, "qwe", "asd", 2, "qwe"]]
Enum.each(lists... |
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... | #OxygenBasic | OxygenBasic | def max 1000
Class MovingAverage
'==================
indexbase 1
double average,invperiod,mdata[max]
sys index,period
method Setup(double a,p)
sys i
Period=p
invPeriod=1/p
index=0
average=a
for i=1 to period
mdata[i]=a
next
end method
method Data(double v) as double
sys i
index++
if index>period then index... |
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.... | #11l | 11l | F is_prime(n)
I n < 2
R 0B
L(i) 2 .. Int(sqrt(n))
I n % i == 0
R 0B
R 1B
F get_pfct(=n)
V i = 2
[Int] factors
L i * i <= n
I n % i
i++
E
n I/= i
factors.append(i)
I n > 1
factors.append(n)
R factors.len
[Int] pool
L(each) 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 ... | #D | D | import std.stdio, std.range, std.algorithm, std.complex, std.math,
std.format, std.conv;
double radians(in double d) pure nothrow @safe @nogc {
return d * PI / 180;
}
double degrees(in double r) pure nothrow @safe @nogc {
return r * 180 / PI;
}
double meanAngle(in double[] deg) pure nothrow @safe @... |
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.... | #C | C |
#include <algorithm>
#include <iostream>
/* AVL node */
template <class T>
class AVLnode {
public:
T key;
int balance;
AVLnode *left, *right, *parent;
AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p),
left(NULL), right(NULL) {}
~AVLnode() {
delete left... |
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 ... | #C | C | #include<math.h>
#include<stdio.h>
double
meanAngle (double *angles, int size)
{
double y_part = 0, x_part = 0;
int i;
for (i = 0; i < size; i++)
{
x_part += cos (angles[i] * M_PI / 180);
y_part += sin (angles[i] * M_PI / 180);
}
return atan2 (y_part / size, x_part / size) * 180 / M_PI... |
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 ... | #AppleScript | AppleScript | set alist to {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0}
set med to medi(alist)
on medi(alist)
set temp to {}
set lcount to count alist
if lcount is equal to 2 then
return ((item 1 of alist) + (item 2 of alist)) / 2
else if lcount is less than 2 then
return item 1 of alist
else --if... |
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... | #ERRE | ERRE |
PROGRAM MEANS
DIM A[9]
PROCEDURE ARITHMETIC_MEAN(A[]->M)
LOCAL S,I%
NEL%=UBOUND(A,1)
S=0
FOR I%=0 TO NEL% DO
S+=A[I%]
END FOR
M=S/(NEL%+1)
END PROCEDURE
PROCEDURE GEOMETRIC_MEAN(A[]->M)
LOCAL S,I%
NEL%=UBOUND(A,1)
S=1
FOR I%=0 TO NEL% DO
... |
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"
... | #Erlang | Erlang |
-module(ternary).
-compile(export_all).
test() ->
AS = "+-0++0+", AT = from_string(AS), A = from_ternary(AT),
B = -436, BT = to_ternary(B), BS = to_string(BT),
CS = "+-++-", CT = from_string(CS), C = from_ternary(CT),
RT = mul(AT,sub(BT,CT)),
R = from_ternary(RT),
RS = to_string(RT),
io:... |
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.... | #Microsoft_Small_Basic | Microsoft Small Basic | ' Babbage problem
' The quote (') means a comment
' The equals sign (=) means assign
n = 500
' 500 is stored in variable n*n
' 500 because 500*500=250000 less than 269696
' The nitty-gritty is in the 3 lines between "While" and "EndWhile".
' So, we start with 500, n is being incremented by 1 at each round
' while its... |
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) ... | #AutoIt | AutoIt |
#include <Array.au3>
Local $Array[1]
_ArrayAdd($Array, "[]")
_ArrayAdd($Array, "[][]")
_ArrayAdd($Array, "[[][]]")
_ArrayAdd($Array, "][")
_ArrayAdd($Array, "][][")
_ArrayAdd($Array, "[]][[]")
For $i = 0 To UBound($Array) -1
Balanced_Brackets($Array[$i])
If @error Then
ConsoleWrite($Array[$i] &" = NOT OK"&@CRLF... |
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... | #Erlang | Erlang |
-module( mode ).
-export( [example/0, values/1] ).
example() ->
Set = [1, 2, "qwe", "asd", 1, 2, "qwe", "asd", 2, "qwe"],
io:fwrite( "In ~p the mode(s) is(are): ~p~n", [Set, values(Set)] ).
values( Set ) ->
Dict = lists:foldl( fun values_count/2, dict:new(), Set ),
[X || {X, _Y} <- dict:fold( fun keep_maxs/3,... |
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... | #0815 | 0815 |
{x{+=<:2:x/%<:d:~$<:01:~><:02:~><:03:~><:04:~><:05:~><:06:~><:07:~><:08:
~><:09:~><:0a:~><:0b:~><:0c:~><:0d:~><:0e:~><:0f:~><:10:~><:11:~><:12:~>
<:13:~><:14:~><:15:~><:16:~><:17:~><:18:~><:19:~><:ffffffffffffffff:~>{x
{+>}:8f:{&={+>{~>&=x<:ffffffffffffffff:/#:8f:{{=<:19:x/%
|
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... | #11l | 11l | F ffactorial(n)
V result = 1.0
L(i) 2..n
result *= i
R result
V MAX_N = 20
V TIMES = 1000000
F analytical(n)
R sum((1..n).map(i -> ffactorial(@n) / pow(Float(@n), Float(i)) / ffactorial(@n - i)))
F test(n, times)
V count = 0
L(i) 0 .< times
V (x, bits) = (1, 0)
L (bits [&] x) =... |
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... | #Oz | Oz | declare
fun {CreateSMA Period}
Xs = {NewCell nil}
in
fun {$ X}
Xs := {List.take X|@Xs Period}
{FoldL @Xs Number.'+' 0.0}
/
{Int.toFloat {Min Period {Length @Xs}}}
end
end
in
for Period in [3 5] do
SMA = {CreateSMA Period}
in
{System.showInfo "\n... |
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.... | #8080_Assembly | 8080 Assembly | ;;; Show attractive numbers up to 120
MAX: equ 120 ; can be up to 255 (8 bit math is used)
;;; CP/M calls
puts: equ 9
bdos: equ 5
org 100h
;;; -- Zero memory ------------------------------------------------
lxi b,fctrs ; page 2
mvi e,2 ; zero out two pages
xra a
mov d,a
zloop: stax b
inx b
dcr d
jnz zloop
... |
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.... | #Action.21 | Action! | INCLUDE "H6:SIEVE.ACT"
BYTE FUNC IsAttractive(BYTE n BYTE ARRAY primes)
BYTE count,f
IF n<=1 THEN
RETURN (0)
ELSEIF primes(n) THEN
RETURN (0)
FI
count=0 f=2
DO
IF n MOD f=0 THEN
count==+1
n==/f
IF n=1 THEN
EXIT
ELSEIF primes(n) THEN
f=n
FI
... |
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 ... | #Delphi | Delphi |
program Averages_Mean_time_of_day;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Math;
const
Inputs: TArray<string> = ['23:00:17', '23:40:20', '00:12:45', '00:17:19'];
function ToTimes(ts: TArray<string>): TArray<TTime>;
begin
SetLength(result, length(ts));
for var i := 0 to High(ts) do
Result... |
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.... | #C.23 | C# |
#include <algorithm>
#include <iostream>
/* AVL node */
template <class T>
class AVLnode {
public:
T key;
int balance;
AVLnode *left, *right, *parent;
AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p),
left(NULL), right(NULL) {}
~AVLnode() {
delete left... |
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 ... | #C.23 | C# | using System;
using System.Linq;
using static System.Math;
class Program
{
static double MeanAngle(double[] angles)
{
var x = angles.Sum(a => Cos(a * PI / 180)) / angles.Length;
var y = angles.Sum(a => Sin(a * PI / 180)) / angles.Length;
return Atan2(y, x) * 180 / PI;
}
static vo... |
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 ... | #Applesoft_BASIC | Applesoft BASIC | 100 REMMEDIAN
110 K = INT(L/2) : GOSUB 150
120 R = X(K)
130 IF L - 2 * INT (L / 2) THEN R = (R + X(K + 1)) / 2
140 RETURN
150 REMQUICK SELECT
160 LT = 0:RT = L - 1
170 FOR J = LT TO RT STEP 0
180 PT = X(K)
190 P1 = K:P2 = RT: GOSUB 300
200 P = LT
210 FOR I = P TO RT - 1
220 IF X(... |
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 ... | #Arturo | Arturo | arr: [1 2 3 4 5 6 7]
arr2: [1 2 3 4 5 6]
print median arr
print median arr2 |
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... | #Euler_Math_Toolbox | Euler Math Toolbox |
>function A(x) := mean(x)
>function G(x) := exp(mean(log(x)))
>function H(x) := 1/mean(1/x)
>x=1:10; A(x), G(x), H(x)
5.5
4.52872868812
3.41417152147
|
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"
... | #Factor | Factor | USING: kernel combinators locals formatting lint literals
sequences assocs strings arrays
math math.functions math.order ;
IN: rosetta-code.bt
CONSTANT: addlookup {
{ 0 CHAR: 0 }
{ 1 CHAR: + }
{ -1 CHAR: - }
}
<PRIVATE
: bt-add-digits ( a b c -- d e )
+ + 3 +
{ { 0 -1 } { 1 -1 } { -1 0 } { ... |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p.... | #MiniScript | MiniScript | // Lines that start with "//" are "comments" that are ignored
// by the computer. We use them to explain the code.
// Start by finding the smallest number that could possibly
// square to 269696. sqrt() returns the square root of a
// number, and floor() truncates any fractional part.
k = floor(sqrt(269696))
// ... |
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.... | #Modula-2 | Modula-2 | MODULE BabbageProblem;
FROM FormatString IMPORT FormatString;
FROM RealMath IMPORT sqrt;
FROM Terminal IMPORT WriteString,ReadChar;
VAR
buf : ARRAY[0..63] OF CHAR;
k : INTEGER;
BEGIN
(* Find the greatest integer less than the square root *)
k := TRUNC(sqrt(269696.0));
(* Odd numbers cannot be so... |
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) ... | #AWK | AWK | #!/usr/bin/awk -f
BEGIN {
print isbb("[]")
print isbb("][")
print isbb("][][")
print isbb("[][]")
print isbb("[][][]")
print isbb("[]][[]")
}
function isbb(x) {
s = 0
for (k=1; k<=length(x); k++) {
c = substr(x,k,1)
if (c=="[") {s++}
else { if (c=="]") s-- }
if (s<0) {return 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... | #ERRE | ERRE | PROGRAM MODE_AVG
!$INTEGER
DIM A[10],B[10],Z[10]
PROCEDURE SORT(Z[],P->Z[])
LOCAL N,FLIPS
FLIPS=TRUE
WHILE FLIPS DO
FLIPS=FALSE
FOR N=0 TO P-1 DO
IF Z[N]>Z[N+1] THEN SWAP(Z[N],Z[N+1]) FLIPS=TRUE
END FOR
END WHILE
END PROCEDURE
PROCEDURE CALC_MODE(Z[],P->MODES$)
LOCAL I,O... |
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... | #Euphoria | Euphoria | include misc.e
function mode(sequence s)
sequence uniques, counts, modes
integer j,max
uniques = {}
counts = {}
for i = 1 to length(s) do
j = find(s[i], uniques)
if j then
counts[j] += 1
else
uniques = append(uniques, s[i])
counts = appe... |
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... | #11l | 11l | F average(x)
R sum(x) / Float(x.len)
print(average([0, 0, 3, 1, 4, 1, 5, 9, 0, 0])) |
http://rosettacode.org/wiki/Average_loop_length | Average loop length | Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Generic_Elementary_Functions;
with Ada.Numerics.Discrete_Random;
procedure Avglen is
package IIO is new Ada.Text_IO.Integer_IO (Positive); use IIO;
package LFIO is new Ada.Text_IO.Float_IO (Long_Float); use LFIO;
subtype FactN is Natural range 0..20;
TEST... |
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... | #PARI.2FGP | PARI/GP | sma_per(n)={
sma_v=vector(n);
sma_i = 0;
n->if(sma_i++>#sma_v,sma_v[sma_i=1]=n;0,sma_v[sma_i]=n;0)+sum(i=1,#sma_v,sma_v[i])/#sma_v
}; |
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.... | #Ada | Ada | with Ada.Text_IO;
procedure Attractive_Numbers is
function Is_Prime (N : in Natural) return Boolean is
D : Natural := 5;
begin
if N < 2 then return False; end if;
if N mod 2 = 0 then return N = 2; end if;
if N mod 3 = 0 then return N = 3; end if;
while D * D <= N 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 ... | #EchoLisp | EchoLisp |
;; string hh:mm:ss to radians
(define (time->radian time)
(define-values (h m s) (map string->number (string-split time ":")))
(+ (* h (/ PI 12)) (* m (/ PI 12 60)) (* s (/ PI 12 3600))))
;; radians to string hh:mm;ss
(define (radian->time rad)
(when (< rad 0) (+= rad (* 2 PI)))
(define t (round (/ (* 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.... | #C.2B.2B | C++ |
#include <algorithm>
#include <iostream>
/* AVL node */
template <class T>
class AVLnode {
public:
T key;
int balance;
AVLnode *left, *right, *parent;
AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p),
left(NULL), right(NULL) {}
~AVLnode() {
delete left... |
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 ... | #C.2B.2B | C++ | #include <iomanip>
#include <iostream>
#include <vector>
#define _USE_MATH_DEFINES
#include <math.h>
template<typename C>
double meanAngle(const C& c) {
auto it = std::cbegin(c);
auto end = std::cend(c);
double x = 0.0;
double y = 0.0;
double len = 0.0;
while (it != end) {
x += cos... |
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 ... | #AutoHotkey | AutoHotkey | seq = 4.1, 7.2, 1.7, 9.3, 4.4, 3.2, 5
MsgBox % median(seq, "`,") ; 4.1
median(seq, delimiter)
{
Sort, seq, ND%delimiter%
StringSplit, seq, seq, % delimiter
median := Floor(seq0 / 2)
Return seq%median%
} |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of p... | #Euphoria | Euphoria | function arithmetic_mean(sequence s)
atom sum
if length(s) = 0 then
return 0
else
sum = 0
for i = 1 to length(s) do
sum += s[i]
end for
return sum/length(s)
end if
end function
function geometric_mean(sequence s)
atom p
p = 1
for i = 1... |
http://rosettacode.org/wiki/Balanced_ternary | Balanced ternary | Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1.
Examples
Decimal 11 = 32 + 31 − 30, thus it can be written as "++−"
Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0"
... | #FreeBASIC | FreeBASIC |
#define MAX(a, b) iif((a) > (b), (a), (b))
Dim Shared As Integer pow, signo
Dim Shared As String t
t = "-0+"
Function deci(cadena As String) As Integer
Dim As Integer i, deci1
Dim As String c1S
pow = 1
For i = Len(cadena) To 1 Step -1
c1S = Mid(cadena,i,1)
signo = Instr(t, c1S)-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.... | #Nanoquery | Nanoquery | n = 0
while not (n ^ 2 % 1000000) = 269696
n += 1
end
println 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.... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary utf8
numeric digits 5000 -- set up numeric precision
babbageNr = babbage() -- call a function to perform the analysis and capture the result
babbageSq = babbageNr ** 2 -- calculate the square of the result
-- display results using a library... |
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) ... | #BaCon | BaCon | FOR len = 0 TO 18 STEP 2
str$ = ""
DOTIMES len
str$ = str$ & CHR$(IIF(RANDOM(2) = 0, 91, 93))
DONE
status = 0
FOR x = 1 TO LEN(str$)
IF MID$(str$, x, 1) = "[" THEN
INCR status
ELSE
DECR status
FI
IF status < 0 THEN BREAK
NEXT
... |
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... | #F.23 | F# | let mode (l:'a seq) =
l
|> Seq.countBy (fun item -> item) // Count individual items
|> Seq.fold // Find max counts
(fun (cp, lst) (item, c) -> // State is (count, list of items with that count)
if c > cp then (c, [item]) ... |
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... | #Factor | Factor | { 11 9 4 9 4 9 } mode ! 9 |
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... | #360_Assembly | 360 Assembly | AVGP CSECT
USING AVGP,12
LR 12,15
SR 3,3 i=0
SR 6,6 sum=0
LOOP CH 3,=AL2(NN-T-1) for i=1 to nn
BH ENDLOOP
L 2,T(3) t(i)
MH 2,=H'100' scaling factor=2
AR ... |
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... | #6502_Assembly | 6502 Assembly | ArithmeticMean: PHA
TYA
PHA ;push accumulator and Y register onto stack
LDA #0
STA Temp
STA Temp+1 ;temporary 16-bit storage for total
LDY NumberInts
BEQ Done ;if NumberInts = 0 then return an average of zero
DEY ;start with NumberInts-1
AddLoop: LDA (ArrayPtr),Y
CLC
ADC Temp
... |
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... | #BBC_BASIC | BBC BASIC | @% = &2040A
MAX_N = 20
TIMES = 1000000
FOR n = 1 TO MAX_N
avg = FNtest(n, TIMES)
theory = FNanalytical(n)
diff = (avg / theory - 1) * 100
PRINT STR$(n), avg, theory, diff "%"
NEXT
END
DEF FNanalytical(n)
LOCAL i, s
FOR i = 1 TO n
... |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define MAX_N 20
#define TIMES 1000000
double factorial(int n) {
double f = 1;
int i;
for (i = 1; i <= n; i++) f *= i;
return f;
}
double expected(int n) {
double sum = 0;
int i;
for (i = 1; i <= n; i++)
sum += factorial(n) / pow(... |
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... | #Pascal | Pascal | program sma;
type
tsma = record
smaValue : array of double;
smaAverage,
smaSumOld,
smaSumNew,
smaRezActLength : double;
smaActLength,
smaLength,
smaPos :NativeInt;
smaIsntFull: boolean;
end;
proced... |
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.... | #ALGOL_68 | ALGOL 68 | BEGIN # find some attractive numbers - numbers whose prime factor counts are #
# prime, n must be > 1 #
PR read "primes.incl.a68" PR
# find the attractive numbers #
INT max number = 120;
[]BOOL sieve =... |
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 ... | #Erlang | Erlang |
-module( mean_time_of_day ).
-export( [from_times/1, task/0] ).
from_times( Times ) ->
Seconds = [seconds_from_time(X) || X <- Times],
Degrees = [degrees_from_seconds(X) || X <- Seconds],
Average = mean_angle:from_degrees( Degrees ),
time_from_seconds( seconds_from_degrees(Average) ).
task() ->
Times = ["23:... |
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.... | #C.2B.2B.2FCLI | C++/CLI | (defpackage :avl-tree
(:use :cl)
(:export
:avl-tree
:make-avl-tree
:avl-tree-count
:avl-tree-p
:avl-tree-key<=
:gettree
:remtree
:clrtree
:dfs-maptree
:bfs-maptree))
(in-package :avl-tree)
(defstruct %tree
key
value
(height 0 :type fixnum)
left
right)
(defstruct (avl-tr... |
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 ... | #Clojure | Clojure | (defn mean-fn
[k coll]
(let [n (count coll)
trig (get {:sin #(Math/sin %) :cos #(Math/cos %)} k)]
(* (/ 1 n) (reduce + (map trig coll)))))
(defn mean-angle
[degrees]
(let [radians (map #(Math/toRadians %) degrees)
a (mean-fn :sin radians)
b (mean-fn :cos radians)]
(Math/toDegre... |
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 ... | #Common_Lisp | Common Lisp | (defun average (list)
(/ (reduce #'+ list) (length list)))
(defun radians (angle)
(* pi 1/180 angle))
(defun degrees (angle)
(* (/ 180 pi) angle))
(defun mean-angle (angles)
(let* ((angles (map 'list #'radians angles))
(cosines (map 'list #'cos angles))
(sines (map 'list #'sin angles)))
(degrees (... |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches ... | #AWK | AWK | #!/usr/bin/awk -f
BEGIN {
d[1] = 3.0
d[2] = 4.0
d[3] = 1.0
d[4] = -8.4
d[5] = 7.2
d[6] = 4.0
d[7] = 1.0
d[8] = 1.2
showD("Before: ")
gnomeSortD()
showD("Sorted: ")
printf "Median: %f\n", medianD()
exit
}
function medianD( len, mid) {
len = length(d)
mi... |
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... | #Excel | Excel |
=AVERAGE(1;2;3;4;5;6;7;8;9;10)
=GEOMEAN(1;2;3;4;5;6;7;8;9;10)
=HARMEAN(1;2;3;4;5;6;7;8;9;10)
|
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"
... | #Glagol | Glagol | ОТДЕЛ Сетунь+;
ИСПОЛЬЗУЕТ
Параметр ИЗ "...\Отделы\Обмен\",
Текст ИЗ "...\Отделы\Числа\",
Вывод ИЗ "...\Отделы\Обмен\";
ПЕР
зч: РЯД 10 ИЗ ЗНАК;
счпоз: ЦЕЛ;
число: ЦЕЛ;
память: ДОСТУП К НАБОР
ячейки: РЯД 20 ИЗ ЦЕЛ;
размер: УЗКЦЕЛ;
отрицательное: КЛЮЧ
КОН;
ЗАДАЧА СоздатьПамять;
УКА... |
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.... | #NewLisp | NewLisp |
;;; Start by assigning n the integer square root of 269696
;;; minus 1 to be even
(setq n 518)
;;; Increment n by 2 till the last 6 digits of its square are 269696
(while (!= (% (* n n) 1000000) 269696)
(++ n 2))
;;; Show the result and its square
(println n "^2 = " (* n n))
|
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) ... | #BASIC | BASIC | DECLARE FUNCTION checkBrackets% (brackets AS STRING)
DECLARE FUNCTION generator$ (length AS INTEGER)
RANDOMIZE TIMER
DO
x$ = generator$ (10)
PRINT x$,
IF checkBrackets(x$) THEN
PRINT "OK"
ELSE
PRINT "NOT OK"
END IF
LOOP WHILE LEN(x$)
FUNCTION checkBrackets% (brackets AS STRING)... |
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... | #Fortran | Fortran | program mode_test
use Qsort_Module only Qsort => sort
implicit none
integer, parameter :: S = 10
integer, dimension(S) :: a1 = (/ -1, 7, 7, 2, 2, 2, -1, 7, -3, -3 /)
integer, dimension(S) :: a2 = (/ 1, 1, 1, 1, 1, 0, 2, 2, 2, 2 /)
integer, dimension(S) :: a3 = (/ 0, 0, -1, -1, 9, 9, 3, 3, 7, 7 /)
... |
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... | #8th | 8th |
: avg \ a -- avg(a)
dup ' n:+ 0 a:reduce
swap a:len nip n:/ ;
\ test:
[ 1.0, 2.3, 1.1, 5.0, 3, 2.8, 2.01, 3.14159 ] avg . cr
[ ] avg . cr
[ 10 ] avg . cr
bye
|
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... | #ACL2 | ACL2 | (defun mean-r (xs)
(if (endp xs)
(mv 0 0)
(mv-let (m j)
(mean-r (rest xs))
(mv (+ (first xs) m) (+ j 1)))))
(defun mean (xs)
(if (endp xs)
0
(mv-let (n d)
(mean-r xs)
(/ n d)))) |
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... | #11l | 11l | V base = [‘name’ = ‘Rocket Skates’, ‘price’ = ‘12.75’, ‘color’ = ‘yellow’]
V update = [‘price’ = ‘15.25’, ‘color’ = ‘red’, ‘year’ = ‘1974’]
V result = copy(base)
result.update(update)
print(result) |
http://rosettacode.org/wiki/Average_loop_length | Average loop length | Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t... | #C.23 | C# | public class AverageLoopLength {
private static int N = 100000;
private static double analytical(int n) {
double[] factorial = new double[n + 1];
double[] powers = new double[n + 1];
powers[0] = 1.0;
factorial[0] = 1.0;
for (int i = 1; i <= n; i++) {
factorial[i] = factorial[i - 1] * i;
powers[i] = ... |
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... | #Perl | Perl | sub sma_generator {
my $period = shift;
my (@list, $sum);
return sub {
my $number = shift;
push @list, $number;
$sum += $number;
$sum -= shift @list if @list > $period;
return $sum / @list;
}
}
# Usage:
my $sma = sma_generator(3);
for (1, 2, 3, 2, 7) {
pri... |
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.... | #ALGOL_W | ALGOL W | % find some attractive numbers - numbers whose prime factor count is prime %
begin
% implements the sieve of Eratosthenes %
% s(i) is set to true if i is prime, false otherwise %
% algol W doesn't have a upb operator, so we pass the size of the ... |
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.... | #AppleScript | AppleScript | on isPrime(n)
if (n < 4) then return (n > 1)
if ((n mod 2 is 0) or (n mod 3 is 0)) then return false
repeat with i from 5 to (n ^ 0.5) div 1 by 6
if ((n mod i is 0) or (n mod (i + 2) is 0)) then return false
end repeat
return true
end isPrime
on primeFactorCount(n)
set x to n
set... |
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 ... | #Euphoria | Euphoria |
include std/console.e
include std/math.e
include std/mathcons.e
include std/sequence.e
include std/get.e
function T2D(sequence TimeSeq)
return (360 * TimeSeq[1] / 24 + 360 * TimeSeq[2] / (24 * 60) +
360 * TimeSeq[3] / (24 * 3600))
end function
function D2T(atom angle)
sequence TimeSeq = {0,0,0}
atom seconds... |
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.... | #Common_Lisp | Common Lisp | (defpackage :avl-tree
(:use :cl)
(:export
:avl-tree
:make-avl-tree
:avl-tree-count
:avl-tree-p
:avl-tree-key<=
:gettree
:remtree
:clrtree
:dfs-maptree
:bfs-maptree))
(in-package :avl-tree)
(defstruct %tree
key
value
(height 0 :type fixnum)
left
right)
(defstruct (avl-tr... |
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 ... | #D | D | import std.stdio, std.algorithm, std.complex;
import std.math: PI;
auto radians(T)(in T d) pure nothrow @nogc { return d * PI / 180; }
auto degrees(T)(in T r) pure nothrow @nogc { return r * 180 / PI; }
real meanAngle(T)(in T[] D) pure nothrow @nogc {
immutable t = reduce!((a, d) => a + d.radians.expi)(0.comple... |
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 ... | #BaCon | BaCon | DECLARE a[] = { 4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2 } TYPE FLOATING
DECLARE b[] = { 4.1, 7.2, 1.7, 9.3, 4.4, 3.2 } TYPE FLOATING
DEF FN Dim(x) = SIZEOF(x) / SIZEOF(double)
DEF FN Median(x) = IIF(ODD(Dim(x)), x[(Dim(x)-1)/2], (x[Dim(x)/2-1]+x[Dim(x)/2])/2 )
SORT a
PRINT "Median of a: ", Median(a)
SORT b
PRINT "Med... |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of p... | #F.23 | F# | let P = [1.0; 2.0; 3.0; 4.0; 5.0; 6.0; 7.0; 8.0; 9.0; 10.0]
let arithmeticMean (x : float list) =
x |> List.sum
|> (fun acc -> acc / float (List.length(x)))
let geometricMean (x: float list) =
x |> List.reduce (*)
|> (fun acc -> Math.Pow(acc, 1.0 / (float (List.length(x)))))
let harmonicMean ... |
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"
... | #Go | Go | package main
import (
"fmt"
"strings"
)
// R1: representation is a slice of int8 digits of -1, 0, or 1.
// digit at index 0 is least significant. zero value of type is
// representation of the number 0.
type bt []int8
// R2: string conversion:
// btString is a constructor. valid input is a string of a... |
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.... | #Nim | Nim |
var n : int = 0
while n*n mod 1_000_000 != 269_696:
inc(n)
echo 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.... | #Objeck | Objeck | class Babbage {
function : Main(args : String[]) ~ Nil {
cur := 0;
do {
cur++;
}
while(cur * cur % 1000000 <> 269696);
cur_sqr := cur * cur;
"The square of {$cur} is {$cur_sqr}!"->PrintLine();
}
}
|
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) ... | #BASIC256 | BASIC256 | s$ = "[[]][]"
print s$; " = ";
if not check_brackets(s$) then print "not ";
print "ok"
end
function check_brackets(s$)
level = 0
for i = 1 to length(s$)
c$ = mid(s$, i, 1)
begin case
case c$ = "["
level = level + 1
case c$ = "]"
level = level - 1
if level < 0 then exi... |
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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Sub quicksort(a() As Integer, first As Integer, last As Integer)
Dim As Integer length = last - first + 1
If length < 2 Then Return
Dim pivot As Integer = a(first + length\ 2)
Dim lft As Integer = first
Dim rgt As Integer = last
While lft <= rgt
While a(lft) < pivot
lft +=1
... |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin... | #Action.21 | Action! | INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
PROC Mean(INT ARRAY a INT count REAL POINTER result)
INT i
REAL x,sum,tmp
IntToReal(0,sum)
FOR i=0 TO count-1
DO
IntToReal(a(i),x)
RealAdd(sum,x,tmp)
RealAssign(tmp,sum)
OD
IntToReal(count,tmp)
RealDiv(sum,tmp,result)
RETURN
PROC Test(IN... |
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... | #ActionScript | ActionScript | function mean(vector:Vector.<Number>):Number
{
var sum:Number = 0;
for(var i:uint = 0; i < vector.length; i++)
sum += vector[i];
return vector.length == 0 ? 0 : sum / vector.length;
} |
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... | #Ada | Ada | with Ada.Text_Io;
with Ada.Containers.Indefinite_Ordered_Maps;
procedure Merge_Maps is
use Ada.Text_Io;
type Key_Type is new String;
type Value_Type is new String;
package Maps is
new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => Key_Type,
... |
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... | #ALGOL_68 | ALGOL 68 | # associative array merging #
# the modes allowed as associative array element values - change to suit #
MODE AAVALUE = UNION( STRING, INT, REAL );
# the modes allowed as associative array element keys - change to suit #
MODE AAKEY = STRING;
# initial value... |
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... | #C.2B.2B | C++ | #include <random>
#include <vector>
#include <iostream>
#define MAX_N 20
#define TIMES 1000000
/**
* Used to generate a uniform random distribution
*/
static std::random_device rd; //Will be used to obtain a seed for the random number engine
static std::mt19937 gen(rd()); //Standard mersenne_twister_engine seede... |
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... | #Phix | Phix | with javascript_semantics
sequence sma = {} -- ((period,history,circnxt)) (private to sma.e)
integer sma_free = 0
global function new_sma(integer period)
integer res
if sma_free then
res = sma_free
sma_free = sma[sma_free]
sma[res] = {period,{},0}
else
sma = append(sma,{... |
http://rosettacode.org/wiki/Attractive_numbers | Attractive numbers | A number is an attractive number if the number of its prime factors (whether distinct or not) is also prime.
Example
The number 20, whose prime decomposition is 2 × 2 × 5, is an attractive number because the number of its prime factors (3) is also prime.
Task
Show sequence items up to 120.... | #Arturo | Arturo | attractive?: function [x] -> prime? size factors.prime x
print select 1..120 => attractive? |
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.... | #AWK | AWK |
# syntax: GAWK -f ATTRACTIVE_NUMBERS.AWK
# converted from C
BEGIN {
limit = 120
printf("attractive numbers from 1-%d:\n",limit)
for (i=1; i<=limit; i++) {
n = count_prime_factors(i)
if (is_prime(n)) {
printf("%d ",i)
}
}
printf("\n")
exit(0)
}
function count_prime_fac... |
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 ... | #F.23 | F# | open System
open System.Numerics
let deg2rad d = d * Math.PI / 180.
let rad2deg r = r * 180. / Math.PI
let makeComplex = fun r -> Complex.FromPolarCoordinates(1., r)
// 1 msec = 10000 ticks
let time2deg = TimeSpan.Parse >> (fun ts -> ts.Ticks) >> (float) >> (*) (10e-9/24.)
let deg2time = (*) (24. * 10e7) >> (int64) ... |
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.... | #D | D | import std.stdio, std.algorithm;
class AVLtree {
private Node* root;
private static struct Node {
private int key, balance;
private Node* left, right, parent;
this(in int k, Node* p) pure nothrow @safe @nogc {
key = k;
parent = p;
}
}
publi... |
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 ... | #Delphi | Delphi |
(define-syntax-rule (deg->radian deg) (* deg 1/180 PI))
(define-syntax-rule (radian->deg rad) (* 180 (/ PI) rad))
(define (mean-angles angles)
(radian->deg
(angle
(for/sum ((a angles)) (make-polar 1 (deg->radian a))))))
(mean-angles '( 350 10))
→ -0
(mean-angles '[90 180 270 360])
→ -9... |
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 ... | #EchoLisp | EchoLisp |
(define-syntax-rule (deg->radian deg) (* deg 1/180 PI))
(define-syntax-rule (radian->deg rad) (* 180 (/ PI) rad))
(define (mean-angles angles)
(radian->deg
(angle
(for/sum ((a angles)) (make-polar 1 (deg->radian a))))))
(mean-angles '( 350 10))
→ -0
(mean-angles '[90 180 270 360])
→ -9... |
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 ... | #BASIC | BASIC | DECLARE FUNCTION median! (vector() AS SINGLE)
DIM vec1(10) AS SINGLE, vec2(11) AS SINGLE, n AS INTEGER
RANDOMIZE TIMER
FOR n = 0 TO 10
vec1(n) = RND * 100
vec2(n) = RND * 100
NEXT
vec2(11) = RND * 100
PRINT median(vec1())
PRINT median(vec2())
FUNCTION median! (vector() AS SINGLE)
DIM lb AS INTEGER... |
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.