task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Averages/Mean_time_of_day | Averages/Mean time of day | Task[edit]
A particular activity of bats occurs at these times of the day:
23:00:17, 23:40:20, 00:12:45, 00:17:19
Using the idea that there are twenty-four hours in a day,
which is analogous to there being 360 degrees in a circle,
map times of day to and from angles;
and using the ideas of Averages/Mean angle
compute ... | #Oberon-2 | Oberon-2 |
MODULE AvgTimeOfDay;
IMPORT
M := LRealMath,
T := NPCT:Tools,
Out := NPCT:Console;
CONST
secsDay = 86400;
secsHour = 3600;
secsMin = 60;
toRads = M.pi / 180;
VAR
h,m,s: LONGINT;
data: ARRAY 4 OF LONGREAL;
PROCEDURE TimeToDeg(time: STRING): LONGREAL;
VAR
parts: ARRAY 3 OF STRING;
h,m,s: LO... |
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.... | #Phix | Phix | with javascript_semantics
enum KEY = 0,
LEFT,
HEIGHT, -- (NB +/-1 gives LEFT or RIGHT)
RIGHT
sequence tree = {}
integer freelist = 0
function newNode(object key)
integer node
if freelist=0 then
node = length(tree)+1
tree &= {key,NULL,1,NULL}
else
node = freelist
... |
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 ... | #Maple | Maple | > [ 350, 10 ] *~ Unit(arcdeg);
[350 [arcdeg], 10 [arcdeg]] |
http://rosettacode.org/wiki/Averages/Mean_angle | Averages/Mean angle | When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle.
If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the ... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | meanAngle[data_List] := N@Arg[Mean[Exp[I data Degree]]]/Degree |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches ... | #Erlang | Erlang | -module(median).
-import(lists, [nth/2, sort/1]).
-compile(export_all).
test(MaxInt,ListSize,TimesToRun) ->
test(MaxInt,ListSize,TimesToRun,[[],[]]).
test(_,_,0,[GMAcc, OMAcc]) ->
Len = length(GMAcc),
{GMT,GMV} = lists:foldl(fun({T, V}, {AT,AV}) -> {AT + T, AV + V} end, {0,0}, GMAcc),
{OMT,OMV} = ... |
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... | #J | J | amean=: +/ % #
gmean=: # %: */
hmean=: amean&.:% |
http://rosettacode.org/wiki/Balanced_ternary | Balanced ternary | Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1.
Examples
Decimal 11 = 32 + 31 − 30, thus it can be written as "++−"
Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0"
... | #Phix | Phix | with javascript_semantics
function bt2dec(string bt)
integer res = 0
for i=1 to length(bt) do
res = 3*res+(bt[i]='+')-(bt[i]='-')
end for
return res
end function
function negate(string bt)
for i=1 to length(bt) do
if bt[i]!='0' then
bt[i] = '+'+'-'-bt[i]
end if
... |
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.... | #Python | Python |
# Lines that start by # are a comments:
# they will be ignored by the machine
n=0 # n is a variable and its value is 0
# we will increase its value by one until
# its square ends in 269,696
while n**2 % 1000000 != 269696:
# n**2 -> n squared
# % -> 'modulo' or remainer after division
# != -> ... |
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... | #Lobster | Lobster |
// Return whether the two numbers `a` and `b` are close.
// Closeness is determined by the `epsilon` parameter -
// the numbers are considered close if the difference between them
// is no more than epsilon * max(abs(a), abs(b)).
//
def isclose(a, b, epsilon):
return abs(a - b) <= max(abs(a), abs(b)) * epsilon
... |
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... | #Lua | Lua | function approxEquals(value, other, epsilon)
return math.abs(value - other) < epsilon
end
function test(a, b)
local epsilon = 1e-18
print(string.format("%f, %f => %s", a, b, tostring(approxEquals(a, b, epsilon))))
end
function main()
test(100000000000000.01, 100000000000000.011);
test(100.01, 10... |
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) ... | #Common_Lisp | Common Lisp |
(defun string-of-brackets (n)
(let* ((len (* 2 n))
(res (make-string len))
(opening (/ len 2))
(closing (/ len 2)))
(dotimes (i len res)
(setf (aref res i)
(cond ((zerop opening) #\])
((zerop closing) #\[)
(t (if (= (random 2) 0)
... |
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file | Append a record to the end of a text file | Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment.
This feature is most useful in the case of log files,... | #COBOL | COBOL |
*> Tectonics:
*> cobc -xj append.cob
*> cobc -xjd -DDEBUG append.cob
*> ***************************************************************
identification division.
program-id. append.
environment division.
configuration section.
repository.
func... |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element ins... | #Apex | Apex | // Cannot / Do not need to instantiate the algorithm implementation (e.g, HashMap).
Map<String, String> strMap = new Map<String, String>();
strMap.put('a', 'aval');
strMap.put('b', 'bval');
System.assert( strMap.containsKey('a') );
System.assertEquals( 'bval', strMap.get('b') );
// String keys are case-sensitive
Syst... |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #APL | APL | f←{⍸≠⌈\(⍴∘∪⊢∨⍳)¨⍳⍵} |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI or android with termux */
/* program antiprime.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes ... |
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... | #Haskell | Haskell | module AtomicUpdates (main) where
import Control.Concurrent (forkIO, threadDelay)
import Control.Concurrent.MVar (MVar, newMVar, readMVar, modifyMVar_)
import Control.Monad (forever, forM_)
import Data.IntMap (IntMap, (!), toAscList, fromList, adjust)
import System.Random (randomRIO)
import Text.Printf (printf)
---... |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Euphoria | Euphoria | type fourty_two(integer i)
return i = 42
end type
fourty_two i
i = 41 -- type-check failure |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #F.23 | F# | let test x =
assert (x = 42)
test 43 |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Factor | Factor | USING: kernel ;
42 assert= |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #AppleScript | AppleScript | on callback for arg
-- Returns a string like "arc has 3 letters"
arg & " has " & (count arg) & " letters"
end callback
set alist to {"arc", "be", "circle"}
repeat with aref in alist
-- Passes a reference to some item in alist
-- to callback, then speaks the return value.
say (callback for aref)
en... |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Arturo | Arturo | arr: [1 2 3 4 5]
print map arr => [2*] |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
run_samples()
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method mode(lvector = java.util.List) public static returns java.util.List
seen = 0
modes = ''
modeMax = 0
loop v_ = 0 to lv... |
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 ... | #C.23 | C# | using System;
using System.Collections.Generic;
namespace AssocArrays
{
class Program
{
static void Main(string[] args)
{
Dictionary<string,int> assocArray = new Dictionary<string,int>();
assocArray["Hello"] = 1;
assocArray.Add("World", 2);
a... |
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... | #Groovy | Groovy | class DigitalFilter {
private static double[] filter(double[] a, double[] b, double[] signal) {
double[] result = new double[signal.length]
for (int i = 0; i < signal.length; ++i) {
double tmp = 0.0
for (int j = 0; j < b.length; ++j) {
if (i - j < 0) continue
... |
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... | #COBOL | COBOL | FUNCTION MEAN(some-table (ALL)) |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin... | #Cobra | Cobra |
class Rosetta
def mean(ns as List<of number>) as number
if ns.count == 0
return 0
else
sum = 0.0
for n in ns
sum += n
return sum / ns.count
def main
print "mean of [[]] is [.mean(List<of number>())]"
print "mean of [[1,2,3,4]] is [.mean([1.0,2.0,3.0,4.0])]"
|
http://rosettacode.org/wiki/Associative_array/Merging | Associative array/Merging | Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Merge these into a new associativ... | #Phix | Phix | with javascript_semantics
integer d1 = new_dict({{"name","Rocket Skates"},{"price",12.75},{"color","yellow"}}),
d2 = new_dict({{"price",15.25},{"color","red"},{"year",1974}}),
d3 = new_dict(d1)
function merger(object key, data, /*user_data*/) setd(key,data,d3) return 1 end function
traverse_dict(merger,... |
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... | #Phixmonti | Phixmonti | include ..\Utilitys.pmt
def scand /# dict key -- dict n #/
0 var flag
var ikey
len for
var i
i 1 2 tolist sget
ikey == if i var flag exitfor endif
endfor
flag
enddef
def getd /# dict key -- dict data #/
scand
dup if get 2 get nip else drop "Unfound" endif
e... |
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... | #PHP | PHP | <?
$base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
$update = array("price" => 15.25, "color" => "red", "year" => 1974);
$result = $update + $base; // Notice that the order is reversed
print_r($result);
?> |
http://rosettacode.org/wiki/Average_loop_length | Average loop length | Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t... | #Phixmonti | Phixmonti | include ..\Utilitys.pmt
20 var MAX
100000 var ITER
def factorial 1 swap for * endfor enddef
def expected /# n -- n #/
>ps
0
tps for var i
tps factorial tps i power / tps i - factorial / +
endfor
ps> drop
enddef
def condition over over bitand not enddef
def test /# n -- n #/
... |
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... | #PicoLisp | PicoLisp | (scl 4)
(seed (in "/dev/urandom" (rd 8)))
(de fact (N)
(if (=0 N) 1 (apply * (range 1 N))) )
(de analytical (N)
(sum
'((I)
(/
(* (fact N) 1.0)
(** N I)
(fact (- N I)) ) )
(range 1 N) ) )
(de testing (N)
(let (C 0 N (dec N) X 0 B 0 I 1000000)... |
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... | #Run_Basic | Run Basic | data 1,2,3,4,5,5,4,3,2,1
dim sd(10) ' series data
global sd ' make it global so we all see it
for i = 1 to 10:read sd(i): next i
x = sma(3) ' simple moving average for 3 periods
x = sma(5) ' simple moving average for... |
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.... | #J | J |
echo (#~ (1 p: ])@#@q:) >:i.120
|
http://rosettacode.org/wiki/Attractive_numbers | Attractive numbers | A number is an attractive number if the number of its prime factors (whether distinct or not) is also prime.
Example
The number 20, whose prime decomposition is 2 × 2 × 5, is an attractive number because the number of its prime factors (3) is also prime.
Task
Show sequence items up to 120.... | #JavaScript | JavaScript | (() => {
'use strict';
// attractiveNumbers :: () -> Gen [Int]
const attractiveNumbers = () =>
// An infinite series of attractive numbers.
filter(
compose(isPrime, length, primeFactors)
)(enumFrom(1));
// ----------------------- TEST -----------------------
... |
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 ... | #OCaml | OCaml | let pi_twice = 2.0 *. 3.14159_26535_89793_23846_2643
let day = float (24 * 60 * 60)
let rad_of_time t =
t *. pi_twice /. day
let time_of_rad r =
r *. day /. pi_twice
let mean_angle angles =
let sum_sin = List.fold_left (fun sum a -> sum +. sin a) 0.0 angles
and sum_cos = List.fold_left (fun sum a -> sum +... |
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.... | #Picat | Picat | main =>
T = nil,
foreach (X in 1..10)
T := insert(X,T)
end,
output(T,0).
insert(X, nil) = {1,nil,X,nil}.
insert(X, T@{H,L,V,R}) = Res =>
if X < V then
Res = rotate({H, insert(X,L) ,V,R})
elseif X > V then
Res = rotate({H,L,V, insert(X,R)})
else
Res = T
e... |
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 ... | #MATLAB_.2F_Octave | MATLAB / Octave | function u = mean_angle(phi)
u = angle(mean(exp(i*pi*phi/180)))*180/pi;
end |
http://rosettacode.org/wiki/Averages/Mean_angle | Averages/Mean angle | When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle.
If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the ... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
numeric digits 80
runSample(arg)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method getMeanAngle(angles) private static binary
x_component = double 0.0
y_component = double 0.0
aK = int 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 ... | #ERRE | ERRE |
PROGRAM MEDIAN
DIM X[10]
PROCEDURE QUICK_SELECT
LT=0 RT=L-1
J=LT
REPEAT
PT=X[K]
SWAP(X[K],X[RT])
P=LT
FOR I=P TO RT-1 DO
IF X[I]<PT THEN SWAP(X[I],X[P]) P=P+1 END IF
END FOR
SWAP(X[RT],X[P])
IF P=K THEN EXIT PROCEDURE END IF
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 ... | #Euler_Math_Toolbox | Euler Math Toolbox |
>type median
function median (x, v: none, p)
## Default for v : none
## Default for p : 0.5
m=rows(x);
if m>1 then
y=zeros(m,1);
loop 1 to m;
y[#]=median(x[#],v,p);
end;
return y;
else
if v<>none then
{xs,i}=sort(x); vsh=v[i]... |
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... | #Java | Java | import java.util.Arrays;
import java.util.List;
public class PythagoreanMeans {
public static double arithmeticMean(List<Double> numbers) {
if (numbers.isEmpty()) return Double.NaN;
double mean = 0.0;
for (Double number : numbers) {
mean += number;
}
return mean... |
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"
... | #PicoLisp | PicoLisp | (seed (in "/dev/urandom" (rd 8)))
(setq *G '((0 -1) (1 -1) (-1 0) (0 0) (1 0) (-1 1) (0 1)))
# For humans
(de negh (L)
(mapcar
'((I)
(case I
(- '+)
(+ '-)
(T 0) ) )
L ) )
(de trih (X)
(if (num? X)
(let (S (lt0 X) X (abs X) R NIL)
(if ... |
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.... | #Quackery | Quackery | ( . . . . . . . . . . . . . . . . . . )
( The computer will ignore anything between parentheses, providing there is
a space or carriage return on either side of each parenthesis. )
( . . . . . . . . . . . . . . . . . . )
( 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.... | #R | R |
babbage_function=function(){
n=0
while (n**2%%1000000!=269696) {
n=n+1
}
return(n)
}
babbage_function()[length(babbage_function())]
|
http://rosettacode.org/wiki/Approximate_equality | Approximate equality | Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the
difference in floating point calculations between different language implementations becomes significant.
For example, a difference between 32 bit and 64 bit floating point calculations may appear by
about the 8t... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[CloseEnough]
CloseEnough[a_, b_, tol_] := Chop[a - b, tol] == 0
numbers = {
{100000000000000.01, 100000000000000.011},
{100.01, 100.011},
{10000000000000.001/10000.0, 1000000000.0000001000},
{0.001, 0.0010000001},
{0.000000000000000000000101, 0.0},
{Sqrt[2.0] Sqrt[2.0], 2.0}, {-Sqrt[2.0] Sqrt... |
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... | #Nim | Nim | from math import sqrt
import strformat
import strutils
const Tolerance = 1e-10
proc `~=`(a, b: float): bool =
## Check if "a" and "b" are close.
## We use a relative tolerance to compare the values.
result = abs(a - b) < max(abs(a), abs(b)) * Tolerance
proc compare(a, b: string) =
## Compare "a" and "b" t... |
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... | #OCaml | OCaml | let approx_eq v1 v2 epsilon =
Float.abs (v1 -. v2) < epsilon
let test a b =
let epsilon = 1e-18 in
Printf.printf "%g, %g => %b\n" a b (approx_eq a b epsilon)
let () =
test 100000000000000.01 100000000000000.011;
test 100.01 100.011;
test (10000000000000.001 /. 10000.0) 1000000000.0000001000;
test 0.00... |
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) ... | #Component_Pascal | Component Pascal |
MODULE Brackets;
IMPORT StdLog, Args, Stacks (* See Task Stacks *);
TYPE
Character = POINTER TO RECORD (Stacks.Object)
c: CHAR
END;
PROCEDURE NewCharacter(c: CHAR): Character;
VAR
n: Character;
BEGIN
NEW(n);n.c:= c;RETURN n
END NewCharacter;
PROCEDURE (c: Character) Show*;
BEGIN
StdLog.String("Character(... |
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file | Append a record to the end of a text file | Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment.
This feature is most useful in the case of log files,... | #Common_Lisp | Common Lisp | (defvar *initial_data*
(list
(list "jsmith" "x" 1001 1000
(list "Joe Smith" "Room 1007" "(234)555-8917" "(234)555-0077" "jsmith@rosettacode.org")
"/home/jsmith" "/bin/bash")
(list "jdoe" "x" 1002 1000
(list "Jane Doe" "Room 1004" "(234)555-8914" "(234)555-0044" "jdoe@rosettacode.org")
... |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element ins... | #APL | APL | ⍝ Create a namespace ("hash")
X←⎕NS ⍬
⍝ Assign some names
X.this←'that'
X.foo←88
⍝ Access the names
X.this
that
⍝ Or do it the array way
X.(foo this)
88 that
⍝ Namespaces are first class objects
sales ← ⎕NS ⍬
sales.(prices quantities) ← (10... |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #Arturo | Arturo | found: 0
i: 1
maxDiv: 0
while [found<20][
fac: size factors i
if fac > maxDiv [
print i
maxDiv: fac
found: found + 1
]
i: i + 1
] |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #AWK | AWK | # syntax: GAWK -f ANTI-PRIMES.AWK
BEGIN {
print("The first 20 anti-primes are:")
while (count < 20) {
d = count_divisors(++n)
if (d > max_divisors) {
printf("%d ",n)
max_divisors = d
count++
}
}
printf("\n")
exit(0)
}
function count_divisors(n, count,i) {
... |
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... | #Icon_and_Unicon | Icon and Unicon | global mtx
procedure main(A)
nBuckets := integer(A[1]) | 10
nShows := integer(A[2]) | 4
showBuckets := A[3]
mtx := mutex()
every !(buckets := list(nBuckets)) := ?100
thread repeat {
every (b1|b2) := ?nBuckets # OK if same!
critical mtx: xfer((buckets[b1] - buckets[b2])/2, 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.
| #FBSL | FBSL | #APPTYPE CONSOLE
DECLARE asserter
FUNCTION Assert(expression)
DIM cmd AS STRING = "DIM asserter AS INTEGER = (" & expression & ")"
EXECLINE(cmd, 1)
IF asserter = 0 THEN PRINT "Assertion: ", expression, " failed"
END FUNCTION
Assert("1<2")
Assert("1>2")
PAUSE |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Forth | Forth | variable a
: assert a @ 42 <> throw ;
41 a ! assert |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
' requires compilation with -g switch
Dim a As Integer = 5
Assert(a = 6)
'The rest of the code will not be executed
Print a
Sleep |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #AutoHotkey | AutoHotkey | map("callback", "3,4,5")
callback(array){
Loop, Parse, array, `,
MsgBox % (2 * A_LoopField)
}
map(callback, array){
%callback%(array)
} |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #AWK | AWK | $ awk 'func psqr(x){print x,x*x}BEGIN{split("1 2 3 4 5",a);for(i in a)psqr(a[i])}'
4 16
5 25
1 1
2 4
3 9 |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat... | #Nim | Nim | import tables
proc modes[T](xs: openArray[T]): T =
var count = initCountTable[T]()
for x in xs:
count.inc(x)
largest(count).key
echo modes(@[1,3,6,6,6,6,7,7,12,12,17])
echo modes(@[1,1,2,4,4]) |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat... | #Oberon-2 | Oberon-2 |
MODULE Mode;
IMPORT
Object:Boxed,
ADT:Dictionary,
ADT:LinkedList,
Out := NPCT:Console;
TYPE
Key = Boxed.LongInt;
Val = Boxed.LongInt;
VAR
x: ARRAY 11 OF LONGINT;
y: ARRAY 5 OF LONGINT;
z: ARRAY 8 OF LONGINT;
PROCEDURE Show(ll: LinkedList.LinkedList(Key));
VAR
iter: LinkedList.Iterato... |
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 ... | #C.2B.2B | C++ | #include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> dict {
{"One", 1},
{"Two", 2},
{"Three", 7}
};
dict["Three"] = 3;
std::cout << "One: " << dict["One"] << std::endl;
std::cout << "Key/Value pairs: " << std::endl;
for(auto& kv: dict) {
std::cou... |
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... | #Haskell | Haskell | import Data.List (tails)
-- lazy convolution of a list by given kernel
conv :: Num a => [a] -> [a] -> [a]
conv ker = map (dot (reverse ker)) . tails . pad
where
pad v = replicate (length ker - 1) 0 ++ v
dot v = sum . zipWith (*) v
-- The lazy digital filter
dFilter :: [Double] -> [Double] -> [Double] -> ... |
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... | #J | J | Butter=: {{
t=. (#n) +/ .*&(|.n)\(}.n*0),y
A=.|.}.m
for_i.}.i.#y do.
t=. t i}~ (i{t) - (i{.t) +/ .* (-i){.A
end.
t%{.m
}}
sig=: ". rplc&('-_') {{)n
-0.917843918645, 0.141984778794, 1.20536903482,
0.190286794412,-0.662370894973,-1.00700480494,
-0.404707073677, 0.800482325044, 0.743500089861,
... |
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... | #CoffeeScript | CoffeeScript |
mean = (array) ->
return 0 if array.length is 0
sum = array.reduce (s,i,0) -> s += i
sum / array.length
alert mean [1]
|
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin... | #Common_Lisp | Common Lisp | (defun mean (&rest sequence)
(if (null sequence)
nil
(/ (reduce #'+ sequence) (length sequence)))) |
http://rosettacode.org/wiki/Associative_array/Merging | Associative array/Merging | Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Merge these into a new associativ... | #PureBasic | PureBasic | NewMap m1.s()
NewMap m2.s()
NewMap m3.s()
m1("name")="Rocket Skates"
m1("price")="12.75"
m1("color")="yellow"
m2("price")="15.25"
m2("color")="red"
m2("year")="1974"
CopyMap(m1(),m3())
ForEach m2()
m3(MapKey(m2()))=m2()
Next
ForEach m3()
Debug MapKey(m3())+" : "+m3()
Next |
http://rosettacode.org/wiki/Associative_array/Merging | Associative array/Merging | Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Merge these into a new associativ... | #Python | Python | base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
result = {**base, **update}
print(result) |
http://rosettacode.org/wiki/Associative_array/Merging | Associative array/Merging | Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Merge these into a new associativ... | #Racket | Racket | #lang racket/base
(require racket/hash)
(module+ test
(require rackunit)
(define base-data (hash "name" "Rocket Skates"
"price" 12.75
"color" "yellow"))
(define update-data (hash "price" 15.25
"color" "red"
... |
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... | #PowerShell | PowerShell |
function Get-AnalyticalLoopAverage ( [int]$N )
{
# Expected loop average = sum from i = 1 to N of N! / (N-i)! / N^(N-i+1)
# Equivalently, Expected loop average = sum from i = 1 to N of F(i)
# where F(N) = 1, and F(i) = F(i+1)*i/N
$LoopAverage = $Fi = 1
If ( $N -eq 1 ) { return $LoopAv... |
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... | #Rust | Rust | struct SimpleMovingAverage {
period: usize,
numbers: Vec<usize>
}
impl SimpleMovingAverage {
fn new(p: usize) -> SimpleMovingAverage {
SimpleMovingAverage {
period: p,
numbers: Vec::new()
}
}
fn add_number(&mut self, number: usize) -> f64 {
self.nu... |
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.... | #Java | Java | public class Attractive {
static boolean is_prime(int n) {
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
if (n % 3 == 0) return n == 3;
int d = 5;
while (d *d <= n) {
if (n % d == 0) return false;
d += 2;
if (n % d == 0) return ... |
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 ... | #ooRexx | ooRexx | /* REXX ---------------------------------------------------------------
* 25.06.2014 Walter Pachl
*--------------------------------------------------------------------*/
times='23:00:17 23:40:20 00:12:45 00:17:19'
sum=0
day=86400
x=0
y=0
Do i=1 To words(times) /* loop over times */
time.i=w... |
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.... | #Python | Python |
# Module: calculus.py
import enum
class entry_not_found(Exception):
"""Raised when an entry is not found in a collection"""
pass
class entry_already_exists(Exception):
"""Raised when an entry already exists in a collection"""
pass
class state(enum.Enum):
header = 0
left_high = 1
right_hig... |
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 ... | #Nim | Nim | import math, complex
proc meanAngle(deg: openArray[float]): float =
var c: Complex[float]
for d in deg:
c += rect(1.0, degToRad(d))
radToDeg(phase(c / float(deg.len)))
echo "The 1st mean angle is: ", meanAngle([350.0, 10.0]), " degrees"
echo "The 2nd mean angle is: ", meanAngle([90.0, 180.0, 270.0, 360.0]... |
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 ... | #Oberon-2 | Oberon-2 |
MODULE MeanAngle;
IMPORT
M := LRealMath,
Out;
CONST
toRads = M.pi / 180;
toDegs = 180 / M.pi;
VAR
grades: ARRAY 64 OF LONGREAL;
PROCEDURE Mean(g: ARRAY OF LONGREAL): LONGREAL;
VAR
i: INTEGER;
sumSin, sumCos: LONGREAL;
BEGIN
i := 0;sumSin := 0.0;sumCos := 0.0;
WHILE g[i] # 0.0 DO
sumSin := sumS... |
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 ... | #Euphoria | Euphoria | function median(sequence s)
atom min,k
-- Selection sort of half+1
for i = 1 to length(s)/2+1 do
min = s[i]
k = 0
for j = i+1 to length(s) do
if s[j] < min then
min = s[j]
k = j
end if
end for
if k then
... |
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... | #JavaScript | JavaScript | (function () {
'use strict';
// arithmetic_mean :: [Number] -> Number
function arithmetic_mean(ns) {
return (
ns.reduce( // sum
function (sum, n) {
return (sum + n);
},
0
) / ns.length
);
}
... |
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"
... | #Prolog | Prolog | :- module('bt_convert.pl', [bt_convert/2,
op(950, xfx, btconv),
btconv/2]).
:- use_module(library(clpfd)).
:- op(950, xfx, btconv).
X btconv Y :-
bt_convert(X, Y).
% bt_convert(?X, ?L)
bt_convert(X, L) :-
( (nonvar(L), \+is_list(L)) ->string_to_list(L, L1); L1 = L),
convert(X, L1),
( var(... |
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.... | #Racket | Racket | ;; Text from a semicolon to the end of a line is ignored
;; This lets the racket engine know it is running racket
#lang racket
;; “define” defines a function in the engine
;; we can use an English name for the function
;; a number ends in 269696 when its remainder when
;; divided by 1000000 is 269696 (we omit commas ... |
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.... | #Raku | Raku | # For all positives integers from 1 to Infinity
for 1 .. Inf -> $integer {
# calculate the square of the integer
my $square = $integer²;
# print the integer and square and exit if the square modulo 1000000 is equal to 269696
print "{$integer}² equals $square" and exit if $square mod 1000000 == 26969... |
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... | #Pascal | Pascal | program approximateEqual(output);
{
\brief determines whether two `real` values are approximately equal
\param x a reference value
\param y the value to compare with \param x
\return true if \param x is equal or approximately equal to \param y
}
function equal(protected x, y: real): Boolean;
function approximate... |
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) ... | #Crystal | Crystal | def generate(n : Int)
(['[',']'] * n).shuffle.join # Implicit return
end
def is_balanced(str : String)
count = 0
str.each_char do |ch|
case ch
when '['
count += 1
when ']'
count -= 1
if count < 0
return false
end
else
return false
end
end
count == 0... |
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file | Append a record to the end of a text file | Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment.
This feature is most useful in the case of log files,... | #D | D | class Record {
private const string account;
private const string password;
private const int uid;
private const int gid;
private const string[] gecos;
private const string directory;
private const string shell;
public this(string account, string password, int uid, int gid, string[] ge... |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element ins... | #App_Inventor | App Inventor |
/* ARM assembly Raspberry PI or android 32 bits */
/* program hashmap.s */
/* */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for con... |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #BASIC | BASIC | 10 DEFINT A-Z
20 N=1
30 IF S>=20 THEN END ELSE F=1
40 IF N<2 GOTO 70 ELSE FOR I=1 TO N\2
50 IF N MOD I=0 THEN F=F+1
60 NEXT
70 IF F<=M GOTO 110
80 PRINT N,
90 M=F
100 S=S+1
110 N=N+1
120 GOTO 30 |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #BASIC256 | BASIC256 |
Dim Results(20)
Candidate = 1
max_divisors = 0
Print "Los primeros 20 anti-primos son:"
For j = 0 To 19
Do
divisors = count_divisors(Candidate)
If max_divisors < divisors Then
Results[j] = Candidate
max_divisors = divisors
Exit Do
End If
Candidate += 1
Until false
Print Results[j];" ";
Next j
... |
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... | #Java | Java | import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;
public class AtomicUpdates {
private static final int NUM_BUCKETS = 10;
public static class Buckets {
private final int[] data;
public Buckets(int[] data) {
this.data = data.clone();
}
p... |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #GAP | GAP | # See section 7.5 of reference manual
# GAP has assertions levels. An assertion is tested if its level
# is less then the global level.
# Set global level
SetAssertionLevel(10);
a := 1;
Assert(20, a > 1, "a should be greater than one");
# nothing happens
a := 1;
Assert(4, a > 1, "a should be greater than one");... |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Go | Go | package main
func main() {
x := 43
if x != 42 {
panic(42)
}
} |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Groovy | Groovy | def checkTheAnswer = {
assert it == 42 : "This: " + it + " is not the answer!"
} |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Babel | Babel | sq { dup * } < |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #BBC_BASIC | BBC BASIC | DIM a(4)
a() = 1, 2, 3, 4, 5
PROCmap(a(), FNsqrt())
FOR i = 0 TO 4
PRINT a(i)
NEXT
END
DEF FNsqrt(n) = SQR(n)
DEF PROCmap(array(), RETURN func%)
LOCAL I%
FOR I% = 0 TO DIM(array(),1)
array(I%) = FN(^func%)(array(I%))
NEXT
ENDPRO... |
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... | #Objeck | Objeck |
use Collection;
class Mode {
function : Main(args : String[]) ~ Nil {
Print(Mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]));
Print(Mode([1, 2, 4, 4, 1]));
}
function : Mode(coll : Int[]) ~ IntVector {
seen := IntMap->New();
max := 0;
maxElems := IntVector->New();
each(i : coll) {
... |
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 ... | #Ceylon | Ceylon | shared void run() {
value myMap = map {
"foo" -> 5,
"bar" -> 10,
"baz" -> 15
};
for(key in myMap.keys) {
print(key);
}
for(item in myMap.items) {
print(item);
}
for(key->item in myMap) {
print("``key`` maps to ``item``");
}
} |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked ... | #Chapel | Chapel | var A = [ "H2O" => "water", "NaCl" => "salt", "O2" => "oxygen" ];
for k in A.domain do
writeln("have key: ", k);
for v in A do
writeln("have value: ", v);
for (k,v) in zip(A.domain, A) do
writeln("have element: ", k, " -> ", v); |
http://rosettacode.org/wiki/Apply_a_digital_filter_(direct_form_II_transposed) | Apply a digital filter (direct form II transposed) | Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [1]
Task
Filt... | #Java | Java | public class DigitalFilter {
private static double[] filter(double[] a, double[] b, double[] signal) {
double[] result = new double[signal.length];
for (int i = 0; i < signal.length; ++i) {
double tmp = 0.0;
for (int j = 0; j < b.length; ++j) {
if (i - j < 0) ... |
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... | #Crystal | Crystal | # Crystal will return NaN if an empty array is passed
def mean(arr) : Float64
arr.sum / arr.size.to_f
end |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin... | #D | D | real mean(Range)(Range r) pure nothrow @nogc {
real sum = 0.0;
int count;
foreach (item; r) {
sum += item;
count++;
}
if (count == 0)
return 0.0;
else
return sum / count;
}
void main() {
import std.stdio;
int[] data;
writeln("Mean: ", data.mean... |
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... | #Raku | Raku | # Show original hashes
say my %base = :name('Rocket Skates'), :price<12.75>, :color<yellow>;
say my %update = :price<15.25>, :color<red>, :year<1974>;
# Need to assign to anonymous hash to get the desired results and avoid mutating
# TIMTOWTDI
say "\nUpdate:\n", join "\n", sort %=%base, %update;
# Same
say "\nUpdat... |
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... | #REXX | REXX | /*REXX program merges two associative arrays (requiring an external list of indices). */
$.= /*define default value(s) for arrays. */
@.wAAn= 21; @.wKey= 7; @.wVal= 7 /*max widths of: AAname, keys, values.*/
call defAA 'base', "name Rocket Skates", ... |
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.