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/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....
#Processing
Processing
// Lines that begin with two slashes, thus, are comments: they // will be ignored by the machine.   // First we must declare a variable, n, suitable to store an integer:   int n;   // Each statement we address to the machine must end with a semicolon.   // To begin with, the value of n will be zero:   n = 0;   // Now w...
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...
#Groovy
Groovy
class Approximate { private static boolean approxEquals(double value, double other, double epsilon) { return Math.abs(value - other) < epsilon }   private static void test(double a, double b) { double epsilon = 1e-18 System.out.printf("%f, %f => %s\n", a, b, approxEquals(a, b, epsilo...
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...
#Haskell
Haskell
class (Num a, Ord a, Eq a) => AlmostEq a where eps :: a   infix 4 ~= (~=) :: AlmostEq a => a -> a -> Bool a ~= b = or [ a == b , abs (a - b) < eps * abs(a + b) , abs (a - b) < eps ]   instance AlmostEq Int where eps = 0 instance AlmostEq Integer where eps = 0 instance AlmostEq Double where eps...
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) ...
#CLU
CLU
% This program needs the random number generator from % "misc.lib" that comes with PCLU.   shuffle = proc [T: type] (a: array[t]) aT = array[t] for i: int in int$from_to_by(aT$size(a)-1,0,-1) do x: int := aT$low(a) + i y: int := aT$low(a) + random$next(i+1) temp: T := a[x] a[x] ...
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,...
#Batch_File
Batch File
  @echo off   ( echo jsmith:x:1001:1000:Joe Smith,Room 1007,^(234^)555-8917,^(234^)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash echo jdoe:x:1002:1000:Jane Doe,Room 1004,^(234^)555-8914,^(234^)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash ) > append.txt   echo Current contents of append.txt: type appe...
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,...
#C
C
#include <stdio.h> #include <string.h> /* note that UID & GID are of type "int" */ typedef const char *STRING; typedef struct{STRING fullname, office, extension, homephone, email; } gecos_t; typedef struct{STRING account, password; int uid, gid; gecos_t gecos; STRING directory, shell; } passwd_t;   #define GECOS_FMT "%...
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...
#Aikido
Aikido
  var names = {} // empty map names["foo"] = "bar" names[3] = 4   // initialized map var names2 = {"foo": bar, 3:4}   // lookup map var name = names["foo"] if (typeof(name) == "none") { println ("not found") } else { println (name) }   // remove from map delete names["foo"]      
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
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program antiprime64.s */   /************************************/ /* Constantes */ /************************************/ .include "../includeConstantesARM64.inc"   .equ NMAXI, 20 .equ MAXLINE, 5 /*********************************/ /* In...
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
#Action.21
Action!
BYTE FUNC CountDivisors(INT a) INT i BYTE prod,count   prod=1 count=0 WHILE a MOD 2=0 DO count==+1 a==/2 OD prod==*(1+count)   i=3 WHILE i*i<=a DO count=0 WHILE a MOD i=0 DO count==+1 a==/i OD prod==*(1+count) i==+2 OD   IF a>2 THEN prod==*2 FI R...
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...
#FreeBASIC
FreeBASIC
Randomize Timer Dim Shared As Uinteger cubo(1 To 10), a, i For i As Uinteger = 1 To 10 cubo(i) = Int(Rnd * 90) Next i   Function Display(cadena As String) As Uinteger Dim As Uinteger valor Print cadena; Spc(2); For i As Uinteger = 1 To 10 valor += cubo(i) Print Using "###"; cubo(i); ...
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.
#Dyalect
Dyalect
var x = 42 assert(42, x)
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.
#E
E
require(a == 42) # default message, "Required condition failed"   require(a == 42, "The Answer is Wrong.") # supplied message   require(a == 42, fn { `Off by ${a - 42}.` }) # computed only on 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.
#EchoLisp
EchoLisp
  (assert (integer? 42)) → #t ;; success returns true   ;; error and return to top level if not true; (assert (integer? 'quarante-deux)) ⛔ error: assert : assertion failed : (#integer? 'quarante-deux)   ;; assertion with message (optional) (assert (integer? 'quarante-deux) "☝️ expression must evaluate to the integer 42...
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Ada
Ada
with Ada.Text_Io; with Ada.Integer_text_IO;   procedure Call_Back_Example is -- Purpose: Apply a callback to an array -- Output: Prints the squares of an integer array to the console   -- Define the callback procedure procedure Display(Location : Positive; Value : Integer) is begin Ada.Text...
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...
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { \\ find mode Function GetMode { Inventory N Inventory ALLMODES m=1 While not empty { if islet then { Read A$ if Exist(N, A$) then { k=Eval(N) ...
http://rosettacode.org/wiki/Averages/Mode
Averages/Mode
Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat...
#Maple
Maple
Statistics:-Mode([1, 2.1, 2.1, 3]); Statistics:-Mode([1, 2.1, 2.1, 3.2, 3.2, 5]);
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 ...
#BASIC256
BASIC256
REM Store some values with their keys: PROCputdict(mydict$, "FF0000", "red") PROCputdict(mydict$, "00FF00", "green") PROCputdict(mydict$, "0000FF", "blue")   REM Iterate through the dictionary: i% = 1 REPEAT i% = FNdict(mydict$, i%, v$, k$) PRINT v$, k$ UN...
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 ...
#BBC_BASIC
BBC BASIC
REM Store some values with their keys: PROCputdict(mydict$, "FF0000", "red") PROCputdict(mydict$, "00FF00", "green") PROCputdict(mydict$, "0000FF", "blue")   REM Iterate through the dictionary: i% = 1 REPEAT i% = FNdict(mydict$, i%, v$, k$) PRINT v$, k$ UN...
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...
#Common_Lisp
Common Lisp
(defparameter a #(1.00000000L0 -2.77555756L-16 3.33333333L-01 -1.85037171L-17)) (defparameter b #(0.16666667L0 0.50000000L0 0.50000000L0 0.16666667L0)) (defparameter s #(-0.917843918645 0.141984778794 1.20536903482 0.190286794412 -0.662370894973 -1.00700480494 -0.404707073677 0.800482325044 0.74...
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...
#D
D
import std.stdio;   alias T = real; alias AT = T[];   AT filter(const AT a, const AT b, const AT signal) { AT result = new T[signal.length];   foreach (int i; 0..signal.length) { T tmp = 0.0; foreach (int j; 0..b.length) { if (i-j<0) continue; tmp += b[j] * signal[i-j]; ...
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...
#BQN
BQN
Avg ← +´÷≠   Avg 1‿2‿3‿4
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...
#C
C
#include <stdio.h>   double mean(double *v, int len) { double sum = 0; int i; for (i = 0; i < len; i++) sum += v[i]; return sum / len; }   int main(void) { double v[] = {1, 2, 2.718, 3, 3.142}; int i, len; for (len = 5; len >= 0; len--) { printf("mean["); for (i = 0; i < len; i++) printf(i ? ", %g" : "%...
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...
#Lua
Lua
base = {name="Rocket Skates", price=12.75, color="yellow"} update = {price=15.25, color="red", year=1974}   --[[ clone the base data ]]-- result = {} for key,val in pairs(base) do result[key] = val end   --[[ copy in the update data ]]-- for key,val in pairs(update) do result[key] = val end   --[[ print the res...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
a1 = <|"name" -> "Rocket Skates", "price" -> 12.75, "color" -> "yellow"|>; a2 = <|"price" -> 15.25, "color" -> "red", "year" -> 1974|>; Merge[{a1, a2}, Last]
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...
#MiniScript
MiniScript
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/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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Grid@Prepend[ Table[{n, #[[1]], #[[2]], Row[{Round[10000 Abs[#[[1]] - #[[2]]]/#[[2]]]/100., "%"}]} &@ N[{Mean[Array[ Length@NestWhileList[#, 1, UnsameQ[##] &, All] - 1 &[# /. MapIndexed[#2[[1]] -> #1 &, RandomInteger[{1, n}, n]] &] &, 10000]], Sum[n! n^(n - k - 1)/...
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...
#Nim
Nim
import random, math, strformat randomize()   const maxN = 20 times = 1_000_000   proc factorial(n: int): float = result = 1 for i in 1 .. n: result *= i.float   proc expected(n: int): float = for i in 1 .. n: result += factorial(n) / pow(n.float, i.float) / factorial(n - i)   proc test(n, times: int):...
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...
#Oberon-2
Oberon-2
  MODULE AvgLoopLen; (* Oxford Oberon-2 *) IMPORT Random, Out;   PROCEDURE Fac(n: INTEGER; f: REAL): REAL; BEGIN IF n = 0 THEN RETURN f ELSE RETURN Fac(n - 1,n*f) END END Fac;   PROCEDURE Power(n,i: INTEGER): REAL; VAR p: REAL; BEGIN p := 1.0; WHILE i > 0 DO p := p * n; DEC(i) END; RETURN p END Power;   PROC...
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...
#REXX
REXX
/*REXX program illustrates and displays a simple moving average using a constructed list*/ parse arg p q n . /*obtain optional arguments from the CL*/ if p=='' | p=="," then p= 3 /*Not specified? Then use the default.*/ if q=='' | q=="," then q= 5 ...
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....
#Go
Go
package main   import "fmt"   func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false } ...
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 ...
#Lua
Lua
  local times = {"23:00:17","23:40:20","00:12:45","00:17:19"}   -- returns time converted to a radian format local function timeToAngle(str) local h,m,s = str:match("(..):(..):(..)") return (h + m / 60 + s / 3600)/12 * math.pi end   -- computes the mean of the angles inside a list local function meanAngle(angles) 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....
#Objeck
Objeck
class AVLNode { @key : Int; @balance : Int; @height : Int; @left : AVLNode; @right : AVLNode; @above : AVLNode;   New(key : Int, above : AVLNode) { @key := key; @above := above; }   method : public : GetKey() ~ Int { return @key; }   method : public : GetLeft() ~ AVLNode { return @...
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 ...
#Kotlin
Kotlin
// version 1.0.5-2   fun meanAngle(angles: DoubleArray): Double { val sinSum = angles.sumByDouble { Math.sin(it * Math.PI / 180.0) } val cosSum = angles.sumByDouble { Math.cos(it * Math.PI / 180.0) } return Math.atan2(sinSum / angles.size, cosSum / angles.size) * 180.0 / Math.PI }   fun main(args: Array<S...
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 ...
#Liberty_BASIC
Liberty BASIC
global Pi Pi =3.1415926535   print "Mean Angle( "; chr$( 34); "350,10"; chr$( 34); ") = "; using( "###.#", meanAngle( "350,10")); " degrees." ' 0 print "Mean Angle( "; chr$( 34); "90,180,270,360"; chr$( 34); ") = "; using( "###.#", meanAngle( "90,180,270,360")); " degrees." ' -90 pr...
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 ...
#EasyLang
EasyLang
func quickselect k . list[] res . # subr partition swap list[(left + right) / 2] list[left] mid = left for i = left + 1 to right if list[i] < list[left] mid += 1 swap list[i] list[mid] . . swap list[left] list[mid] . left = 0 right = len list[] - 1 while left...
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 ...
#EchoLisp
EchoLisp
  (define (median L) ;; O(n log(n)) (set! L (vector-sort! < (list->vector L))) (define dim (// (vector-length L) 2)) (if (integer? dim) (// (+ [L dim] [L (1- dim)]) 2) [L (floor dim)]))   (median '( 3 4 5)) → 4 (median '(6 5 4 3)) → 4.5 (median (iota 10000)) → 4999.5 (median (iota 10001)) → 5000  
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...
#Icon_and_Unicon
Icon and Unicon
link numbers # for a/g/h means   procedure main() every put(x := [], 1 to 10) writes("x := [ "); every writes(!x," "); write("]")   write("Arithmetic mean:", a := amean!x) write("Geometric mean:",g := gmean!x) write("Harmonic mean:", h := hmean!x) write(" a >= g >= h is ", if a >= g >= h then "true" else "false") e...
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" ...
#OCaml
OCaml
type btdigit = Pos | Zero | Neg type btern = btdigit list   let to_string n = String.concat "" (List.rev_map (function Pos -> "+" | Zero -> "0" | Neg -> "-") n)   let from_string s = let sl = ref [] in let digit = function '+' -> Pos | '-' -> Neg | '0' -> Zero | _ -> failwith "invalid digit" in ...
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....
#Prolog
Prolog
:- use_module(library(clpfd)).   babbage_(B, B, Sq) :- B * B #= Sq, number_chars(Sq, R), append(_, ['2','6','9','6','9','6'], R). babbage_(B, R, Sq) :- N #= B + 1, babbage_(N, R, Sq).   babbage :- once(babbage_(1, Num, Square)), format('lowest number is ~p which squared becomes ~p~n', [Num, Square]).
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...
#J
J
  NB. default comparison tolerance matches the python result ".;._2]0 :0 100000000000000.01 = 100000000000000.011 100.01 = 100.011 (10000000000000.001 % 10000.0) = 1000000000.0000001000 0.001 = 0.0010000001 0.000000000000000000000101 = 0.0 (= (...
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...
#Java
Java
public class Approximate { private static boolean approxEquals(double value, double other, double epsilon) { return Math.abs(value - other) < epsilon; }   private static void test(double a, double b) { double epsilon = 1e-18; System.out.printf("%f, %f => %s\n", a, b, approxEquals(a, ...
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) ...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. test-balanced-brackets.   DATA DIVISION. WORKING-STORAGE SECTION. 01 True-Val CONSTANT 0. 01 False-Val CONSTANT 1.   LOCAL-STORAGE SECTION. 01 current-time PIC 9(10).   01 bracket-type PIC 9. ...
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,...
#C.23
C#
using System; using System.IO;   namespace AppendPwdRosetta { class PasswordRecord { public string account, password, fullname, office, extension, homephone, email, directory, shell; public int UID, GID; public PasswordRecord(string account, string password, int UID, int GID, string full...
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...
#Aime
Aime
record r;
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
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Antiprimes is   function Count_Divisors (N : Integer) return Integer is Count : Integer := 1; begin for i in 1 .. N / 2 loop if N mod i = 0 then Count := Count + 1; end if; end loop; return Count; end Count_Div...
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
#ALGOL_68
ALGOL 68
BEGIN # find some anti-primes: numbers with more divisors than the # # previous numbers # INT max number := 10 000; INT max divisors := 0; # construct a table of the divisor counts # [ 1 : max number ]INT ndc; FOR i FROM ...
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...
#Go
Go
package main   import ( "fmt" "math/rand" "sync" "time" )   const nBuckets = 10   type bucketList struct { b [nBuckets]int // bucket data specified by task   // transfer counts for each updater, not strictly required by task but // useful to show that the two updaters get fair chances to run...
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.
#ECL
ECL
  ASSERT(a = 42,'A is not 42!',FAIL);
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.
#Eiffel
Eiffel
class MAIN creation main feature main is local test: TEST; do create test;   io.read_integer; test.assert(io.last_integer); end end
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Elixir
Elixir
ExUnit.start   defmodule AssertionTest do use ExUnit.Case   def return_5, do: 5   test "not equal" do assert 42 == return_5 end end
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.
#Aime
Aime
void map(list l, void (*fp)(object)) { l.ucall(fp, 0); }   void out(object o) { o_(o, "\n"); }   integer main(void) { list(0, 1, 2, 3).map(out);   return 0; }
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.
#ALGOL_68
ALGOL 68
PROC call back proc = (INT location, INT value)VOID: ( printf(($"array["g"] = "gl$, location, value)) );   PROC map = (REF[]INT array, PROC (INT,INT)VOID call back)VOID: ( FOR i FROM LWB array TO UPB array DO call back(i, array[i]) OD );   main: ( [4]INT array := ( 1, 4, 9, 16 ); map(array,...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Commonest[{b, a, c, 2, a, b, 1, 2, 3}] Commonest[{1, 3, 2, 3}]
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...
#MATLAB
MATLAB
function modeValue = findmode(setOfValues) modeValue = mode(setOfValues); end
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Bracmat
Bracmat
( new$hash:?myhash & (myhash..insert)$(title."Some title") & (myhash..insert)$(formula.a+b+x^7) & (myhash..insert)$(fruit.apples oranges kiwis) & (myhash..insert)$(meat.) & (myhash..insert)$(fruit.melons bananas) & (myhash..remove)$formula & (myhash..insert)$(formula.x^2+y^2) & (myhash..forall) $ ( = key va...
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 ...
#Brat
Brat
h = [ hello: 1 world: 2 :! : 3]   #Iterate over key, value pairs h.each { k, v | p "Key: #{k} Value: #{v}" }   #Iterate over keys h.each_key { k | p "Key: #{k}" }   #Iterate over values h.each_value { v | p "Value: #{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...
#FreeBASIC
FreeBASIC
Sub Filtro(a() As Double, b() As Double, senal() As Double, resultado() As Double) Dim As Integer j, k Dim As Double tmp   For j = 0 To Ubound(senal) tmp = 0 For k = 0 To Ubound(b) If (j-k < 0) Then Continue For tmp = tmp + b(k) * senal(j-k) Next k For...
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...
#C.23
C#
using System; using System.Linq;   class Program { static void Main() { Console.WriteLine(new[] { 1, 2, 3 }.Average()); } }
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...
#C.2B.2B
C++
#include <vector>   double mean(const std::vector<double>& numbers) { if (numbers.size() == 0) return 0;   double sum = 0; for (std::vector<double>::iterator i = numbers.begin(); i != numbers.end(); i++) sum += *i; return sum / numbers.size(); }
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...
#Nim
Nim
import tables   let t1 = {"name": "Rocket Skates", "price": "12.75", "color": "yellow"}.toTable let t2 = {"price": "15.25", "color": "red", "year": "1974"}.toTable   var t3 = t1 # Makes a copy. for key, value in t2.pairs: t3[key] = value   echo t3
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...
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   int main(void) { @autoreleasepool { NSDictionary *base = @{@"name": @"Rocket Skates", @"price": @12.75, @"color": @"yellow"}; NSDictionary *update = @{@"price": @15.25, @"color": @"red", @"year": @1974};   NSMutableDictionary *result = [[NSMutableDictionary alloc] initW...
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...
#OCaml
OCaml
  type ty = | TFloat of float | TInt of int | TString of string   type key = string type assoc = string * ty   let string_of_ty : ty -> string = function | TFloat x -> string_of_float x | TInt i -> string_of_int i | TString s -> s   let print_pair key el = Printf.printf "%s: %s\n" key (stri...
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...
#PARI.2FGP
PARI/GP
expected(n)=sum(i=1,n,n!/(n-i)!/n^i,0.); test(n, times)={ my(ct); for(i=1,times, my(x=1,bits); while(!bitand(bits,x),ct++; bits=bitor(bits,x); x = 1<<random(n)) ); ct }; TIMES=1000000; {for(n=1,20, my(cnt=test(n, TIMES),avg=cnt/TIMES,ex=expected(n),diff=(avg/ex-1)*100.); print(n"\t"avg*1."\t"ex*1."\t"...
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...
#Perl
Perl
use List::Util qw(sum reduce);   sub find_loop { my($n) = @_; my($r,@seen); while () { $seen[$r] = $seen[($r = int(1+rand $n))] ? return sum @seen : 1 } }   print " N empiric theoric (error)\n"; print "=== ========= ============ =========\n";   my $MAX = 20; my $TRIALS = 1000;   for my $n...
http://rosettacode.org/wiki/Averages/Simple_moving_average
Averages/Simple moving average
Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is a method for computing an avera...
#Ring
Ring
  load "stdlib.ring" decimals(8) maxperiod = 20 nums = newlist(maxperiod,maxperiod) accum = list(maxperiod) index = list(maxperiod) window = list(maxperiod) for i = 1 to maxperiod index[i] = 1 accum[i] = 0 window[i] = 0 next for i = 1 to maxperiod for j = 1 to maxperiod nums[i][j] = 0 next 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....
#Groovy
Groovy
class AttractiveNumbers { static boolean isPrime(int n) { if (n < 2) return false if (n % 2 == 0) return n == 2 if (n % 3 == 0) return n == 3 int d = 5 while (d * d <= n) { if (n % d == 0) return false d += 2 if (n % d == 0) return false ...
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 ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
meanTime[list_] := StringJoin@ Riffle[ToString /@ Floor@{Mod[24 #, 24], Mod[24*60 #, 60], Mod[24*60*60 #, 60]} &[ Arg[Mean[ Exp[FromDigits[ToExpression@StringSplit[#, ":"], 60] & /@ list/(24*60*60) 2 Pi I]]]/(2 Pi)], ":"]; meanTime[{"23:00:17", "23:40:20", "00:12:45", "00:17:19"}...
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 ...
#MATLAB_.2F_Octave
MATLAB / Octave
function t = mean_time_of_day(t) c = pi/(12*60*60); for k=1:length(t) a = sscanf(t{k},'%d:%d:%d'); phi(k) = (a(1)*3600+a(2)*60+a(3)); end; d = angle(mean(exp(i*phi*c)))/(2*pi); % days if (d<0) d += 1; t = datestr(d,"HH:MM:SS"); end;
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....
#Objective-C
Objective-C
  @implementation AVLTree   -(BOOL)insertWithKey:(NSInteger)key {   if (self.root == nil) { self.root = [[AVLTreeNode alloc]initWithKey:key andParent:nil]; } else {   AVLTreeNode *n = self.root; AVLTreeNode *parent;   while (true) {   if (n.key == key) { ...
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 ...
#Logo
Logo
to mean_angle :angles local "avgsin make "avgsin quotient apply "sum map "sin :angles count :angles local "avgcos make "avgcos quotient apply "sum map "cos :angles count :angles output (arctan :avgcos :avgsin) end   foreach [[350 10] [90 180 270 360] [10 20 30]] [ print (sentence [The average of \(] ? ...
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 ...
#Lua
Lua
function meanAngle (angleList) local sumSin, sumCos = 0, 0 for i, angle in pairs(angleList) do sumSin = sumSin + math.sin(math.rad(angle)) sumCos = sumCos + math.cos(math.rad(angle)) end local result = math.deg(math.atan2(sumSin, sumCos)) return string.format("%.2f", result) end   print(meanAngle({350...
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 ...
#Elena
Elena
import system'routines; import system'math; import extensions;   extension op { get Median() { var sorted := self.ascendant();   var len := sorted.Length; if (len == 0) { ^ nil } else { var middleIndex := len / 2; if ...
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 ...
#Elixir
Elixir
defmodule Average do def median([]), do: nil def median(list) do len = length(list) sorted = Enum.sort(list) mid = div(len, 2) if rem(len,2) == 0, do: (Enum.at(sorted, mid-1) + Enum.at(sorted, mid)) / 2, else: Enum.at(sorted, mid) end end   median = fn list -> IO.puts "#{ins...
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...
#IS-BASIC
IS-BASIC
100 PROGRAM "Averages.bas" 110 NUMERIC ARR(1 TO 10) 120 FOR I=LBOUND(ARR) TO UBOUND(ARR) 130 LET ARR(I)=I 140 NEXT 150 PRINT "Arithmetic mean =";ARITHM(ARR) 160 PRINT "Geometric mean =";GEOMETRIC(ARR) 170 PRINT "Harmonic mean =";HARMONIC(ARR) 180 DEF ARITHM(REF A) 190 LET T=0 200 FOR I=LBOUND(A) TO UBOUND(A) 2...
http://rosettacode.org/wiki/Balanced_ternary
Balanced ternary
Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0" ...
#Perl
Perl
use strict; use warnings;   my @d = qw( 0 + - ); my @v = qw( 0 1 -1 );   sub to_bt { my $n = shift; my $b = ''; while( $n ) { my $r = $n%3; $b .= $d[$r]; $n -= $v[$r]; $n /= 3; } return scalar reverse $b; }   sub from_bt { my $n = 0; for( split //, shift ) { # Horner ...
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....
#PureBasic
PureBasic
EnableExplicit Macro putresult(n) If OpenConsole("Babbage_problem") PrintN("The smallest number whose square ends in 269696 is " + Str(n)) Input() EndIf EndMacro   CompilerIf #PB_Processor_x64 #MAXINT = 1 << 63 - 1 CompilerElseIf #PB_Processor_x86 #MAXINT = 1 << 31 - 1 CompilerEndIf   #GOAL = 269696 #...
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...
#jq
jq
# 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): ((a - b) | fabs) <= (([(a|fabs), (b|fabs)] | max) * 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...
#Julia
Julia
testvalues = [[100000000000000.01, 100000000000000.011], [100.01, 100.011], [10000000000000.001 / 10000.0, 1000000000.0000001000], [0.001, 0.0010000001], [0.000000000000000000000101, 0.0], [sqr...
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...
#Kotlin
Kotlin
import kotlin.math.abs import kotlin.math.sqrt   fun approxEquals(value: Double, other: Double, epsilon: Double): Boolean { return abs(value - other) < epsilon }   fun test(a: Double, b: Double) { val epsilon = 1e-18 println("$a, $b => ${approxEquals(a, b, epsilon)}") }   fun main() { test(1000000000000...
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) ...
#CoffeeScript
CoffeeScript
  isBalanced = (brackets) -> openCount = 0 for bracket in brackets openCount += if bracket is '[' then 1 else -1 return false if openCount < 0 openCount is 0   bracketsCombinations = (n) -> for i in [0...Math.pow 2, n] str = i.toString 2 str = '0' + str while str.length < n str.replace(/0/g,...
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,...
#C.2B.2B
C++
#include <iostream> #include <fstream> #include <string> #include <vector>   std::ostream& operator<<(std::ostream& out, const std::string s) { return out << s.c_str(); }   struct gecos_t { std::string fullname, office, extension, homephone, email;   friend std::ostream& operator<<(std::ostream&, const geco...
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...
#ALGOL_68
ALGOL 68
main:(   MODE COLOR = BITS; FORMAT color repr = $"16r"16r6d$;   # This is an associative array which maps strings to ints # MODE ITEM = STRUCT(STRING key, COLOR value); REF[]ITEM color map items := LOC[0]ITEM;   PROC color map find = (STRING color)REF COLOR:( REF COLOR out; # linear search! # FOR in...
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
#ALGOL_W
ALGOL W
begin  % find some anti-primes - numbers with more factors than the numbers  %  % smaller than them  %  % calculates the number of divisors of v  % integer procedure divisor_count( integer value v ) ; begin integer t...
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
#AppleScript
AppleScript
on factorCount(n) set counter to 0 set sqrt to n ^ 0.5 set limit to sqrt div 1 if (limit = sqrt) then set counter to counter + 1 set limit to limit - 1 end if repeat with i from limit to 1 by -1 if (n mod i is 0) then set counter to counter + 2 end repeat   return...
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...
#Groovy
Groovy
class Buckets {   def cells = [] final n   Buckets(n, limit=1000, random=new Random()) { this.n = n (0..<n).each { cells << random.nextInt(limit) } }   synchronized getAt(i) { cells[i] }   synchronized transfer(from, to, amount) { assert fr...
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.
#Emacs_Lisp
Emacs Lisp
(require 'cl-lib) (let ((x 41)) (cl-assert (= x 42) t "This shouldn't happen"))
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.
#Erlang
Erlang
1> N = 42. 42 2> N = 43. ** exception error: no match of right hand side value 43 3> N = 42. 42 4> 44 = N. ** exception error: no match of right hand side value 42 5> 42 = N. 42
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#ALGOL_W
ALGOL W
begin procedure printSquare ( integer value x ) ; writeon( i_w := 1, s_w := 0, " ", x * x );  % applys f to each element of a from lb to ub (inclusive) % procedure applyI ( procedure f; integer array a ( * ); integer value lb, ub ) ; for i := lb until ub do f( a( i ) );  % test applyI % begin ...
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.
#APL
APL
- 1 2 3 ¯1 ¯2 ¯3 2 * 1 2 3 4 2 4 8 16 2 × ⍳4 2 4 6 8 3 * 3 3 ⍴ ⍳9 3 9 27 81 243 729 2187 6561 19683  
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...
#MUMPS
MUMPS
MODE(X)  ;X is assumed to be a list of numbers separated by "^"  ;I is a loop index  ;L is the length of X  ;Y is a new array  ;ML is the list of modes  ;LOC is a placeholder to shorten the statement Q:'$DATA(X) "No data" Q:X="" "Empty Set" NEW Y,I,L,LOC SET L=$LENGTH(X,"^"),ML="" FOR I=1:1:L SET LOC=+$P(X,"^",I),...
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
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...
#Go
Go
package main   import "fmt"   type filter struct { b, a []float64 }   func (f filter) filter(in []float64) []float64 { out := make([]float64, len(in)) s := 1. / f.a[0] for i := range in { tmp := 0. b := f.b if i+1 < len(b) { b = b[:i+1] } for j, bj := ...
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...
#Chef
Chef
Mean.   Chef has no way to detect EOF, so rather than interpreting some arbitrary number as meaning "end of input", this program expects the first input to be the sample size. Pass in the samples themselves as the other inputs. For example, if you wanted to compute the mean of 10, 100, 47, you could pass in 3, 10, 100,...
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...
#Clojure
Clojure
(defn mean [sq] (if (empty? sq) 0 (/ (reduce + sq) (count sq))))
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...
#Ol
Ol
  (define a1 { 'name "Rocket Skates" 'price 12.75 'color "yellow" })   (define a2 { 'price 15.25 'color "red" 'year 1974 })   (print "a1: " a1) (print "a2: " a2)   (define (collide a b) b) ; will use new key value (print "merged a1 a2: " (ff-union collide a1 a2))  
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...
#Perl
Perl
use strict; use warnings;   my %base = ("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"); my %more = ("price" => 15.25, "color" => "red", "year" => 1974);   print "Update\n"; my %update = (%base, %more); printf "%-7s %s\n", $_, $update{$_} for sort keys %update;   print "\nMerge\n"; my %merge; $merge{$...
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...
#Phix
Phix
constant MAX = 20, ITER = 1000000 function expected(integer n) atom sum = 0 for i=1 to n do sum += factorial(n) / power(n,i) / factorial(n-i) end for return sum end function function test(integer n) integer count = 0, x, bits for i=1 to ITER do x = 1 bits = 0 ...
http://rosettacode.org/wiki/Averages/Simple_moving_average
Averages/Simple moving average
Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is a method for computing an avera...
#Ruby
Ruby
def simple_moving_average(size) nums = [] sum = 0.0 lambda do |hello| nums << hello goodbye = nums.length > size ? nums.shift : 0 sum += hello - goodbye sum / nums.length end end   ma3 = simple_moving_average(3) ma5 = simple_moving_average(5)   (1.upto(5).to_a + 5.downto(1).to_a).each do |num| ...
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....
#Haskell
Haskell
import Data.Numbers.Primes import Data.Bool (bool)   attractiveNumbers :: [Integer] attractiveNumbers = [1 ..] >>= (bool [] . return) <*> (isPrime . length . primeFactors)   main :: IO () main = print $ takeWhile (<= 120) attractiveNumbers
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 ...
#Nim
Nim
import math, complex, strutils, sequtils   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)))   proc meanTime(times: openArray[string]): string = const day = 24 * 60 * 60 let angles = times.map(proc(time: s...