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/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...
#Python
Python
from __future__ import division # Only necessary for Python 2.X from math import factorial from random import randrange   MAX_N = 20 TIMES = 1000000   def analytical(n): return sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))   def test(n, times): count = 0 for i in range(times): ...
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...
#R
R
  expected <- function(size) { result <- 0 for (i in 1:size) { result <- result + factorial(size) / size^i / factorial(size -i) } result }   knuth <- function(size) { v <- sample(1:size, size, replace = TRUE)   visit <- vector('logical',size) place <- 1 visit[[1]] <- TRUE steps <- 0   repeat { ...
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...
#Scala
Scala
class MovingAverage(period: Int) { private var queue = new scala.collection.mutable.Queue[Double]() def apply(n: Double) = { queue.enqueue(n) if (queue.size > period) queue.dequeue queue.sum / queue.size } override def toString = queue.mkString("(", ", ", ")")+", period "+period+", average "+(...
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....
#jq
jq
  def count(s): reduce s as $x (null; .+1);   def is_attractive: count(prime_factors) | is_prime;   def printattractive($m; $n): "The attractive numbers from \($m) to \($n) are:\n", [range($m; $n+1) | select(is_attractive)];   printattractive(1; 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....
#Julia
Julia
using Primes   # oneliner is println("The attractive numbers from 1 to 120 are:\n", filter(x -> isprime(sum(values(factor(x)))), 1:120))   isattractive(n) = isprime(sum(values(factor(n))))   printattractive(m, n) = println("The attractive numbers from $m to $n are:\n", filter(isattractive, m:n))   printattractive(1, 12...
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 ...
#PARI.2FGP
PARI/GP
meanAngle(v)=atan(sum(i=1,#v,sin(v[i]))/sum(i=1,#v,cos(v[i])))%(2*Pi) meanTime(v)=my(x=meanAngle(2*Pi*apply(u->u[1]/24+u[2]/1440+u[3]/86400, v))*12/Pi); [x\1, 60*(x-=x\1)\1, round(60*(60*x-60*x\1))] meanTime([[23,0,17], [23,40,20], [0,12,45], [0,17,19]])
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....
#Raku
Raku
  class AVL-Tree { has $.root is rw = 0;   class Node { has $.key is rw = ''; has $.parent is rw = 0; has $.data is rw = 0; has $.left is rw = 0; has $.right is rw = 0; has Int $.balance is rw = 0; has Int $.height is rw = 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 ...
#OCaml
OCaml
let pi = 3.14159_26535_89793_23846_2643   let deg2rad d = d *. pi /. 180.0   let rad2deg r = r *. 180.0 /. pi   let mean_angle angles = let rad_angles = List.map deg2rad angles in let sum_sin = List.fold_left (fun sum a -> sum +. sin a) 0.0 rad_angles and sum_cos = List.fold_left (fun sum a -> sum +. cos a) 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 ...
#ooRexx
ooRexx
/*REXX program computes the mean angle (angles expressed in degrees). */ numeric digits 50 /*use fifty digits of precision, */ showDig=10 /*··· but only display 10 digits.*/ xl = 350 10  ; say showit(xl, meanAngleD(xl) ) xl = 90 180 270 360  ; say...
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 ...
#Excel
Excel
  =MEDIAN(A1:A10)  
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 ...
#F.23
F#
  let rec splitToFives list = match list with | a::b::c::d::e::tail -> ([a;b;c;d;e])::(splitToFives tail) | [] -> [] | _ -> let left = 5 - List.length (list) let last = List.append list (List.init left (fun _ -> System.Double.PositiveInfinity) ) ...
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...
#jq
jq
def amean: add/length;   def logProduct: map(log) | add;   def gmean: (logProduct / length) | exp;   def hmean: length / (map(1/.) | add);   # Tasks: [range(1;11) ] | [amean, gmean, hmean] as $ans | ( $ans[], "amean > gmean > hmean => \($ans[0] > $ans[1] and $ans[1] > $ans[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" ...
#Python
Python
class BalancedTernary: # Represented as a list of 0, 1 or -1s, with least significant digit first.   str2dig = {'+': 1, '-': -1, '0': 0} # immutable dig2str = {1: '+', -1: '-', 0: '0'} # immutable table = ((0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)) # immutable   def __init__(self, i...
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....
#Red
Red
Red [] number: 510 ;; starting number ;; repeat, until the last condition in the block is true until [ number: number + 2 ;; only even numbers can have even squares  ;; The word modulo computes the non-negative remainder of the  ;; first argument divided by the second argument.  ;; ** => Returns a number raised to ...
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....
#REXX
REXX
/*REXX program finds the lowest (positive) integer whose square ends in 269,696. */ do j=2 by 2 until right(j * j, 6) == 269696 /*start J at two, increment by two. */ end /*◄── signifies the end of the DO loop.*/ ...
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...
#Perl
Perl
use strict; use warnings;   sub is_close { my($a,$b,$eps) = @_; $eps //= 15; my $epse = $eps; $epse++ if sprintf("%.${eps}f",$a) =~ /\./; $epse++ if sprintf("%.${eps}f",$a) =~ /\-/; my $afmt = substr((sprintf "%.${eps}f", $a), 0, $epse); my $bfmt = substr((sprintf "%.${eps}f", $b), 0, $epse)...
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) ...
#D
D
import std.stdio, std.algorithm, std.random, std.range;   void main() { foreach (immutable i; 1 .. 9) { immutable s = iota(i * 2).map!(_ => "[]"[uniform(0, 2)]).array; writeln(s.balancedParens('[', ']') ? " OK: " : "bad: ", s); } }
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,...
#Elixir
Elixir
  defmodule Gecos do defstruct [:fullname, :office, :extension, :homephone, :email]   defimpl String.Chars do def to_string(gecos) do [:fullname, :office, :extension, :homephone, :email] |> Enum.map_join(",", &Map.get(gecos, &1)) end end end   defmodule Passwd do defstruct [:account, :passwo...
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,...
#Fortran
Fortran
PROGRAM DEMO !As per the described task, more or less. TYPE DETAILS !Define a component. CHARACTER*28 FULLNAME CHARACTER*12 OFFICE CHARACTER*16 EXTENSION CHARACTER*16 HOMEPHONE CHARACTER*88 EMAIL END TYPE DETAILS TYPE USERSTUFF !Define the desired data aggreg...
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...
#ARM_Assembly
ARM Assembly
  /* 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
#BCPL
BCPL
get "libhdr" manifest $( LIMIT = 20 $)   let nfactors(n) = n < 2 -> 1, valof $( let c = 2 for i=2 to n/2 if n rem i = 0 then c := c + 1 resultis c $)   let start() be $( let max = 0 and seen = 0 and n = 1 while seen < LIMIT $( let f = nfactors(n) if f > max $( writef("%N ...
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
#C
C
#include <stdio.h>   int countDivisors(int n) { int i, count; if (n < 2) return 1; count = 2; // 1 and n for (i = 2; i <= n/2; ++i) { if (n%i == 0) ++count; } return count; }   int main() { int n, d, maxDiv = 0, count = 0; printf("The first 20 anti-primes are:\n"); for (n = 1...
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...
#Julia
Julia
using StatsBase   function runall() nbuckets = 16 unfinish = true spinner = ReentrantLock() buckets = rand(1:99, nbuckets) totaltrans = 0   bucketsum() = sum(buckets) smallpause() = sleep(rand() / 2000) picktwo() = (samplepair(nbuckets)...) function equalizer() while unfinish...
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...
#Kotlin
Kotlin
// version 1.2.0   import java.util.concurrent.ThreadLocalRandom import kotlin.concurrent.thread   const val NUM_BUCKETS = 10   class Buckets(data: IntArray) { private val data = data.copyOf()   operator fun get(index: Int) = synchronized(data) { data[index] }   fun transfer(srcIndex: Int, dstIndex: Int, am...
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.
#Haskell
Haskell
import Control.Exception   main = let a = someValue in assert (a == 42) -- throws AssertionFailed when a is not 42 somethingElse -- what to return when a is 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.
#Icon_and_Unicon
Icon and Unicon
... runerr(n,( expression ,"Assertion/error - message.")) # Throw (and possibly trap) an error number n if expression succeeds. ... stop(( expression ,"Assertion/stop - message.")) # Terminate program if expression succeeds. ...
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.
#J
J
assert 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.
#Bracmat
Bracmat
( ( callbackFunction1 = location value .  !arg:(?location,?value) & out$(str$(array[ !location "] = " !!value)) ) & ( callbackFunction2 = location value .  !arg:(?location,?value) & !!value^2:?!value ) & ( mapar = arr len callback i .  !arg:(?arr,?len,?callback) & 0:?i ...
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.
#Brat
Brat
#Print out each element in array [:a :b :c :d :e].each { element | p element }
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...
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   @interface NSArray (Mode) - (NSArray *)mode; @end   @implementation NSArray (Mode) - (NSArray *)mode { NSCountedSet *seen = [NSCountedSet setWithArray:self]; int max = 0; NSMutableArray *maxElems = [NSMutableArray array]; for ( obj in seen ) { int count = [see...
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 ...
#Clojure
Clojure
  (doseq [[k v] {:a 1, :b 2, :c 3}] (println k "=" v))   (doseq [k (keys {:a 1, :b 2, :c 3})] (println k))   (doseq [v (vals {:a 1, :b 2, :c 3})] (println v))  
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 ...
#CoffeeScript
CoffeeScript
hash = a: 'one' b: 'two'   for key, value of hash console.log key, value   for key of hash console.log key  
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...
#Julia
Julia
function DF2TFilter(a::Vector, b::Vector, sig::Vector) rst = zeros(sig) for i in eachindex(sig) tmp = sum(b[j] * sig[i-j+1] for j in 1:min(i, length(b))) tmp -= sum(a[j] * rst[i-j+1] for j in 1:min(i, length(a))) rst[i] = tmp / a[1] end return rst end   acoef = [1.00000000, -2.7...
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...
#Kotlin
Kotlin
// version 1.1.3   fun filter(a: DoubleArray, b: DoubleArray, signal: DoubleArray): DoubleArray { val result = DoubleArray(signal.size) for (i in 0 until signal.size) { var tmp = 0.0 for (j in 0 until b.size) { 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...
#Dart
Dart
num mean(List<num> l) => l.reduce((num p, num n) => p + n) / l.length;   void main(){ print(mean([1,2,3,4,5,6,7])); }
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#dc
dc
1 2 3 5 7 zsn1k[+z1<+]ds+xln/p 3.6
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...
#Ring
Ring
  load "stdlib.ring"   list1 = [:name = "Rocket Skates", :price = 12.75, :color = "yellow"] list2 = [:price = 15.25, :color = "red", :year = 1974]   for n = 1 to len(list2) flag = 0 for m = 1 to len(list1) if list2[n][1] = list1[m][1] flag = 1 del(list1,m) add(list1,[lis...
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...
#Ruby
Ruby
base = {"name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"} update = {"price" => 15.25, "color" => "red", "year" => 1974}   result = base.merge(update) p 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...
#Rust
Rust
use std::collections::HashMap;   fn main() { let mut original = HashMap::new(); original.insert("name", "Rocket Skates"); original.insert("price", "12.75"); original.insert("color", "yellow");   let mut update = HashMap::new(); update.insert("price", "15.25"); update.insert("color", "red"); ...
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...
#Scheme
Scheme
; Merge alists by appending the update list onto the front of the base list. ; (The extra '() is so that append doesn't co-opt the second list.) (define append-alists (lambda (base update) (append update base '())))   ; Test... (printf "~%Merge using append procedure...~%") ; The original base and update alists. ...
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...
#Racket
Racket
  #lang racket (require (only-in math factorial))   (define (analytical n) (for/sum ([i (in-range 1 (add1 n))]) (/ (factorial n) (expt n i) (factorial (- n i)))))   (define (test n times) (define (count-times seen times) (define x (random n)) (if (memq x seen) times (count-times (cons x seen) (add1 time...
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...
#Raku
Raku
constant MAX_N = 20; constant TRIALS = 100;   for 1 .. MAX_N -> $N { my $empiric = TRIALS R/ [+] find-loop(random-mapping($N)).elems xx TRIALS; my $theoric = [+] map -> $k { $N ** ($k + 1) R/ [*] flat $k**2, $N - $k + 1 .. $N }, 1 .. $N;   FIRST say " N empiric theoric (error)"; FI...
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...
#Scheme
Scheme
(define ((simple-moving-averager size . nums) num) (set! nums (cons num (if (= (length nums) size) (reverse (cdr (reverse nums))) nums))) (/ (apply + nums) (length nums)))   (define av (simple-moving-averager 3)) (map av '(1 2 3 4 5 5 4 3 2 1))  
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....
#Kotlin
Kotlin
// Version 1.3.21   const val MAX = 120   fun isPrime(n: Int) : Boolean { if (n < 2) return false if (n % 2 == 0) return n == 2 if (n % 3 == 0) return n == 3 var d : Int = 5 while (d * d <= n) { if (n % d == 0) return false d += 2 if (n % d == 0) return false d += 4 ...
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 ...
#Perl
Perl
use strict; use warnings; use POSIX 'fmod'; use Math::Complex; use List::Util qw(sum); use utf8;   use constant τ => 2 * 3.1415926535;   # time-of-day to radians sub tod2rad { ($h,$m,$s) = split /:/, @_[0]; (3600*$h + 60*$m + $s) * τ / 86400; }   # radians to time-of-day sub rad2tod { my $x = $_[0] * 86400 ...
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....
#Rust
Rust
import scala.collection.mutable   class AVLTree[A](implicit val ordering: Ordering[A]) extends mutable.SortedSet[A] {   if (ordering eq null) throw new NullPointerException("ordering must not be null")   private var _root: AVLNode = _ private var _size = 0   override def size: Int = _size   override def forea...
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 ...
#PARI.2FGP
PARI/GP
meanAngle(v)=atan(sum(i=1,#v,sin(v[i]))/sum(i=1,#v,cos(v[i])))%(2*Pi) meanDegrees(v)=meanAngle(v*Pi/180)*180/Pi apply(meanDegrees,[[350, 10], [90, 180, 270, 360], [10, 20, 30]])
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 ...
#Pascal
Pascal
program MeanAngle; {$IFDEF DELPHI} {$APPTYPE CONSOLE} {$ENDIF} uses math;// sincos and atan2 type tAngles = array of double;   function MeanAngle(const a:tAngles;cnt:longInt):double; // calculates mean angle. // returns 0.0 if direction is not sure. const eps = 1e-10;   var i : LongInt; s,c, Sumsin,SumCos...
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 ...
#Factor
Factor
USING: arrays kernel locals math math.functions random sequences ; IN: median   : pivot ( seq -- pivot ) random ;   : split ( seq pivot -- {lt,eq,gt} ) [ [ < ] curry partition ] keep [ = ] curry partition 3array ;   DEFER: nth-in-order :: nth-in-order-recur ( seq ind -- elt ) seq dup pivot split dup [ length ...
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 ...
#Forth
Forth
-1 cells constant -cell : cell- -cell + ;   defer lessthan ( a@ b@ -- ? ) ' < is lessthan   : mid ( l r -- mid ) over - 2/ -cell and + ;   : exch ( addr1 addr2 -- ) dup @ >r over @ swap ! r> swap ! ;   : part ( l r -- l r r2 l2 ) 2dup mid @ >r ( r: pivot ) 2dup begin swap begin dup @ r@ lessthan while cell...
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...
#Julia
Julia
amean(A) = sum(A)/length(A)   gmean(A) = prod(A)^(1/length(A))   hmean(A) = length(A)/sum(1./A)
http://rosettacode.org/wiki/Balanced_ternary
Balanced ternary
Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0" ...
#Racket
Racket
#lang racket   ;; Represent a balanced-ternary number as a list of 0's, 1's and -1's. ;; ;; e.g. 11 = 3^2 + 3^1 - 3^0 ~ "++-" ~ '(-1 1 1) ;; 6 = 3^2 - 3^1 ~ "+-0" ~ '(0 -1 1) ;; ;; Note: the list-rep starts with the least signifcant tert, while ;; the string-rep starts with the most significsnt tert. ...
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....
#Ring
Ring
  n = 0 while pow(n,2) % 1000000 != 269696 n = n + 1 end   see "The smallest number whose square ends in 269696 is : " + n + nl see "Its square is : " + pow(n,2)  
http://rosettacode.org/wiki/Babbage_problem
Babbage problem
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p....
#Ruby
Ruby
n = 0 n = n + 2 until (n*n).modulo(1000000) == 269696 print n  
http://rosettacode.org/wiki/Approximate_equality
Approximate equality
Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the difference in floating point calculations between different language implementations becomes significant. For example, a difference between 32 bit and 64 bit floating point calculations may appear by about the 8t...
#Phix
Phix
with javascript_semantics procedure test(atom a,b, string dfmt="%g", cfmt="%g") string ca = sprintf(cfmt,a), cb = sprintf(cfmt,b), eqs = iff(ca=cb?"":"NOT "), da = sprintf(dfmt,a), db = sprintf(dfmt,b) printf(1,"%30s and\n%30s are %sapproximately equal\n",{da,db,eqs})...
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...
#Python
Python
math.isclose -> bool a: double b: double * rel_tol: double = 1e-09 maximum difference for being considered "close", relative to the magnitude of the input values abs_tol: double = 0.0 maximum difference for being considered "close", regardless of the magnitude of the ...
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) ...
#Delphi
Delphi
procedure Balanced_Brackets;   var BracketsStr : string; TmpStr : string; I,J : integer;   begin Randomize; for I := 1 to 9 do begin { Create a random string of 2*N chars with N*"[" and N*"]" } TmpStr := ''; for J := 1 to I do TmpStr := '['+TmpStr+']'; ...
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,...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Type Person As String fullname As String office As String extension As String homephone As String email Declare Constructor() Declare Constructor(As String, As String, As String, As String, As String) Declare Operator Cast() As String End Type   Constructor Person() End Construc...
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...
#Arturo
Arturo
; create a dictionary d: #[ name: "john" surname: "doe" age: 34 ]   print d
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
#C.23
C#
using System; using System.Linq; using System.Collections.Generic;   public static class Program { public static void Main() => Console.WriteLine(string.Join(" ", FindAntiPrimes().Take(20)));   static IEnumerable<int> FindAntiPrimes() { int max = 0; for (int i = 1; ; i++) { i...
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
#C.2B.2B
C++
#include <iostream>   int countDivisors(int n) { if (n < 2) return 1; int count = 2; // 1 and n for (int i = 2; i <= n/2; ++i) { if (n%i == 0) ++count; } return count; }   int main() { int maxDiv = 0, count = 0; std::cout << "The first 20 anti-primes are:" << std::endl; for (int ...
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...
#Lasso
Lasso
define atomic => thread { data private buckets = staticarray_join(10, void), private lock = 0   public onCreate => { loop(.buckets->size) => { .`buckets`->get(loop_count) = math_random(0, 1000) } }   public buckets => .`buckets`   public bucket(index::inte...
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...
#Logtalk
Logtalk
  :- object(buckets).   :- threaded.   :- public([start/0, start/4]).   % bucket representation :- private(bucket_/2). :- dynamic(bucket_/2).   % use the same mutex for all the predicates that access the buckets :- private([bucket/2, buckets/1, transfer/3]). :- synchronized([bucket/2, bu...
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.
#Java
Java
public class Assertions {   public static void main(String[] args) { int a = 13;   // ... some real code here ...   assert a == 42; // Throws an AssertionError when a is not 42.   assert a == 42 : "Error message"; // Throws an AssertionError when a is not 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.
#JavaScript
JavaScript
  function check() { try { if (isNaN(answer)) throw '$answer is not a number'; if (answer != 42) throw '$answer is not 42'; } catch(err) { console.log(err); answer = 42; } finally { console.log(answer); } }   console.count('try'); // 1 let answer; check();   console.count('try'); // 2 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.
#C
C
#ifndef CALLBACK_H #define CALLBACK_H   /* * By declaring the function in a separate file, we allow * it to be used by other source files. * * It also stops ICC from complaining. * * If you don't want to use it outside of callback.c, this * file can be removed, provided the static keyword is prepended * to the ...
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.
#C.23
C#
int[] intArray = { 1, 2, 3, 4, 5 }; // Simplest method: LINQ, functional int[] squares1 = intArray.Select(x => x * x).ToArray();   // Slightly fancier: LINQ, query expression int[] squares2 = (from x in intArray select x * x).ToArray();   // Or, if you only want to call a function on each element, ju...
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...
#OCaml
OCaml
let mode lst = let seen = Hashtbl.create 42 in List.iter (fun x -> let old = if Hashtbl.mem seen x then Hashtbl.find seen x else 0 in Hashtbl.replace seen x (old + 1)) lst; let best = Hashtbl.fold (fun _ -> max) seen 0 in Hash...
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 ...
#Common_Lisp
Common Lisp
;; iterate using dolist, destructure manually (dolist (pair alist) (destructuring-bind (key . value) pair (format t "~&Key: ~a, Value: ~a." key value)))   ;; iterate and destructure with loop (loop for (key . value) in alist do (format t "~&Key: ~a, Value: ~a." key value))
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 ...
#Crystal
Crystal
dict = {'A' => 1, 'B' => 2}   dict.each { |pair| puts pair }   dict.each_key { |key| puts key }   dict.each_value { |value| puts value }
http://rosettacode.org/wiki/Apply_a_digital_filter_(direct_form_II_transposed)
Apply a digital filter (direct form II transposed)
Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [1] Task Filt...
#Lua
Lua
function filter(b,a,input) local out = {} for i=1,table.getn(input) do local tmp = 0 local j = 0 out[i] = 0   for j=1,table.getn(b) do if i - j < 0 then --continue else tmp = tmp + b[j] * input[i - j + 1] 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...
#Delphi
Delphi
program AveragesArithmeticMean;   {$APPTYPE CONSOLE}   uses Types;   function ArithmeticMean(aArray: TDoubleDynArray): Double; var lValue: Double; begin Result := 0;   for lValue in aArray do Result := Result + lValue; if Result > 0 then Result := Result / Length(aArray); end;   begin Writeln(Mean(TDo...
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...
#SenseTalk
SenseTalk
set base to {name:"Rocket Skates", price:12.75, color:"yellow"}   set update to {price:15.25, color:"red", year:1974}   put "Base data: " & base put "Update data: " & update   // replacing as an operator, to generate merged data on the fly: put "Merged data: " & base replacing properties in update   // replace as a com...
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...
#Smalltalk
Smalltalk
base := Dictionary withAssociations:{ 'name'-> 'Rocket Skates' . 'price' -> 12.75 . 'color' -> 'yellow' }.   update := Dictionary withAssociations:{ 'price' -> 15.25 . 'color' -> 'red' . 'year' -> 1974 }.   result := Dictionary new declareAllFrom:base;...
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...
#Swift
Swift
let base : [String: Any] = ["name": "Rocket Skates", "price": 12.75, "color": "yellow"] let update : [String: Any] = ["price": 15.25, "color": "red", "year": 1974]   let result = base.merging(update) { (_, new) in new }   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...
#REXX
REXX
/*REXX program computes the average loop length mapping a random field 1···N ───► 1···N */ parse arg runs tests seed . /*obtain optional arguments from the CL*/ if runs =='' | runs =="," then runs = 40 /*Not specified? Then use the default.*/ if tests =='' | tests =="," then tests= 100000...
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...
#Sidef
Sidef
func simple_moving_average(period) {   var list = [] var sum = 0   func (number) { list.append(number) sum += number if (list.len > period) { sum -= list.shift } (sum / list.length) } }   var ma3 = simple_moving_average(3) var ma5 = simple_moving_avera...
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....
#LLVM
LLVM
; This is not strictly LLVM, as it uses the C library function "printf". ; LLVM does not provide a way to print values, so the alternative would be ; to just load the string into memory, and that would be boring.   $"ATTRACTIVE_STR" = comdat any $"FORMAT_NUMBER" = comdat any $"NEWLINE_STR" = comdat any   @"ATTRACTIVE_S...
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 ...
#Phix
Phix
with javascript_semantics function MeanAngle(sequence angles) atom x = 0, y = 0 for i=1 to length(angles) do atom ai_rad = angles[i]*PI/180 x += cos(ai_rad) y += sin(ai_rad) end for if abs(x)<1e-16 then return "not meaningful" end if return atan2(y,x)*180/PI end function fu...
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....
#Scala
Scala
import scala.collection.mutable   class AVLTree[A](implicit val ordering: Ordering[A]) extends mutable.SortedSet[A] {   if (ordering eq null) throw new NullPointerException("ordering must not be null")   private var _root: AVLNode = _ private var _size = 0   override def size: Int = _size   override def forea...
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 ...
#Perl
Perl
sub Pi () { 3.1415926535897932384626433832795028842 }   sub meanangle { my($x, $y) = (0,0); ($x,$y) = ($x + sin($_), $y + cos($_)) for @_; my $atan = atan2($x,$y); $atan += 2*Pi while $atan < 0; # Ghetto fmod $atan -= 2*Pi while $atan > 2*Pi; $atan; }   sub meandegrees { meanangle( map { $_ * Pi/180 } ...
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 ...
#Fortran
Fortran
program Median_Test   real :: a(7) = (/ 4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2 /), & b(6) = (/ 4.1, 7.2, 1.7, 9.3, 4.4, 3.2 /)   print *, median(a) print *, median(b)   contains   function median(a, found) real, dimension(:), intent(in) :: a ! the optional found argument can...
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...
#K
K
  am:{(+/x)%#x} gm:{(*/x)^(%#x)} hm:{(#x)%+/%:'x}   {(am x;gm x;hm x)} 1+!10 5.5 4.528729 3.414172  
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" ...
#Raku
Raku
class BT { has @.coeff;   my %co2bt = '-1' => '-', '0' => '0', '1' => '+'; my %bt2co = %co2bt.invert;   multi method new (Str $s) { self.bless(coeff => %bt2co{$s.flip.comb}); } multi method new (Int $i where $i >= 0) { self.bless(coeff => carry $i.base(3).comb.reverse); } multi method ...
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....
#Run_BASIC
Run BASIC
for n = 1 to 1000000 if n^2 MOD 1000000 = 269696 then exit for next   PRINT "The smallest number whose square ends in 269696 is "; n PRINT "Its square is "; n^2
http://rosettacode.org/wiki/Babbage_problem
Babbage problem
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p....
#Rust
Rust
fn main() { let mut current = 0; while (current * current) % 1_000_000 != 269_696 { current += 1; } println!( "The smallest number whose square ends in 269696 is {}", current ); }
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...
#R
R
approxEq <- function(...) isTRUE(all.equal(...)) tests <- rbind(c(100000000000000.01, 100000000000000.011), c(100.01, 100.011), c(10000000000000.001 / 10000.0, 1000000000.0000001000), c(0.001, 0.0010000001), c(0.000000000000000000000101, 0.0), c(sqrt(2) *...
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...
#Racket
Racket
#lang racket   (define (≈ a b [tolerance 1e-9]) (<= (abs (/ (- a b) (max a b))) tolerance))   (define all-tests `(([100000000000000.01 100000000000000.011] [100.01 100.011] [,(/ 10000000000000.001 10000.0) 1000000000.0000001000] [0.001 0.0010000001] [0.000000000000000000000101 0.0] [,(* (sq...
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) ...
#D.C3.A9j.C3.A0_Vu
Déjà Vu
matching?: swap 0 for c in chars: if = c "]": ++ elseif = c "[": if not dup: drop return false -- not   !. matching? "" !. matching? "[]" !. matching? "[][]" !. matching? "[[][]]" !. matching? "][" !. matching? "][][" !. matching? "[]][[]"
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,...
#Free_Pascal
Free Pascal
{$mode objFPC} {$longStrings on} {$modeSwitch classicProcVars+}   uses cTypes, // for system call wrappers unix;   const passwdPath = '/tmp/passwd';   resourceString advisoryLockFailed = 'Error: could not obtain advisory lock';   type GECOS = object fullname: string; office: string; extension: string; ...
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...
#ATS
ATS
(*------------------------------------------------------------------*)   #define ATS_DYNLOADFLAG 0   #include "share/atspre_staload.hats"   (*------------------------------------------------------------------*) (* Interface *)   (* You can put the interface in a .s...
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
#CLU
CLU
% Count factors factors = proc (n: int) returns (int) if n<2 then return(1) end count: int := 2 for i: int in int$from_to(2, n/2) do if n//i = 0 then count := count + 1 end end return(count) end factors   % Generate antiprimes antiprimes = iter () yields (int) max: int := 0 n: int :=...
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
#COBOL
COBOL
  ****************************************************************** * COBOL solution to Anti-primes challange * The program was run on OpenCobolIDE ****************************************************************** IDENTIFICATION DIVISION. PROGRAM-ID. ANGLE-PRIMES.   ENVIRO...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
transfer[bucks_, src_, dest_, n_] := ReplacePart[ bucks, {src -> Max[bucks[[src]] - n, 0], dest -> bucks[[dest]] + Min[bucks[[src]], n]}]; DistributeDefinitions[transfer]; SetSharedVariable[bucks, comp]; bucks = RandomInteger[10, 20]; comp = True; Print["Original sum: " <> IntegerString[Plus @@ bucks]]; Prin...
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...
#Nim
Nim
import locks import math import os import random   const N = 10 # Number of buckets. const MaxInit = 99 # Maximum initial value for buckets.   var buckets: array[1..N, Natural] # Array of buckets. var bucketLocks: array[1..N, Lock] # Array of bucket locks. var randomLock: Lock ...
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.
#jq
jq
SHELL SET UNSET sh bash (etc) export JQ_ASSERT=1 unset JQ_ASSERT fish set -x JQ_ASSERT 1 set -u JQ_ASSERT csh, tcsh setenv JQ_ASSERT 1 unsetenv JQ_ASSERT Windows/DOS SET JQ_ASSERT=1 set JQ_ASSERT= Windows: Start > Control Panel > System > Ad...
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.
#Julia
Julia
const x = 5   # @assert macro checks the supplied conditional expression, with the expression # returned in the failed-assertion message @assert x == 42 # ERROR: LoadError: AssertionError: x == 42   # Julia also has type assertions of the form, x::Type which can be appended to # variable for type-checking at any point ...
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.
#Kotlin
Kotlin
fun main() { val a = 42 assert(a == 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.
#Lasso
Lasso
local(a) = 8 fail_if( #a != 42, error_code_runtimeAssertion, error_msg_runtimeAssertion + ": #a is not 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.
#C.2B.2B
C++
#include <iostream> //cout for printing #include <algorithm> //for_each defined here   //create the function (print the square) void print_square(int i) { std::cout << i*i << " "; }   int main() { //create the array int ary[]={1,2,3,4,5}; //stl for_each std::for_each(ary,ary+5,print_square); return 0; } //p...