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...
#F.23
F#
open System   let gamma z = let lanczosCoefficients = [76.18009172947146;-86.50532032941677;24.01409824083091;-1.231739572450155;0.1208650973866179e-2;-0.5395239384953e-5] let rec sumCoefficients acc i coefficients = match coefficients with | [] -> acc | h::t -> sumCoefficients (acc +...
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...
#PowerShell
PowerShell
  #This version allows a user to enter numbers one at a time to figure this into the SMA calculations   $inputs = @() #Create an array to hold all inputs as they are entered. $period1 = 3 #Define the periods you want to utilize $period2 = 5   Write-host "Enter numbers to observe their moving averages." -ForegroundColor...
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....
#CLU
CLU
sieve = proc (max: int) returns (array[bool]) prime: array[bool] := array[bool]$fill(1,max,true) prime[1] := false for p: int in int$from_to(2, max/2) do if prime[p] then for c: int in int$from_to_by(p*p, max, p) do prime[c] := false end end end ...
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....
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. ATTRACTIVE-NUMBERS.   DATA DIVISION. WORKING-STORAGE SECTION. 77 MAXIMUM PIC 999 VALUE 120. 01 SIEVE-DATA VALUE SPACES. 03 MARKER PIC X OCCURS 120 TIMES. 88 PRIME VALUE SPACE. 03 SIEVE-...
http://rosettacode.org/wiki/Averages/Mean_time_of_day
Averages/Mean time of day
Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ideas of Averages/Mean angle compute ...
#Haskell
Haskell
import Data.Complex (cis, phase) import Data.List.Split (splitOn) import Text.Printf (printf)   timeToRadians :: String -> Float timeToRadians time = let hours:minutes:seconds:_ = splitOn ":" time s = fromIntegral (read seconds :: Int) m = fromIntegral (read minutes :: Int) ...
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....
#J
J
insert=: {{ X=.1 {::2{.x,x NB. middle element of x (don't fail on empty x) Y=.1 {::2{.y,y NB. middle element of y (don't fail on empty y) select.#y case.0 do.x NB. y is an empty node case.1 do. NB. y is a leaf node select.*Y-X case._1 do.a:,y;<x case. 0 do.y case. 1 do...
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 ...
#FreeBASIC
FreeBASIC
  ' FB 1.05.0 Win64   Const PI As Double = 3.1415926535897932   Function MeanAngle(angles() As Double) As Double Dim As Integer length = Ubound(angles) - Lbound(angles) + 1 Dim As Double sinSum = 0.0 Dim As Double cosSum = 0.0 For i As Integer = LBound(angles) To UBound(angles) sinSum += Sin(angles(i) * PI ...
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#C.2B.2B
C++
#include <algorithm>   // inputs must be random-access iterators of doubles // Note: this function modifies the input range template <typename Iterator> double median(Iterator begin, Iterator end) { // this is middle for odd-length, and "upper-middle" for even length Iterator middle = begin + (end - begin) / 2;   ...
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...
#FunL
FunL
import lists.zip   def mean( s, 0 ) = product( s )^(1/s.length()) mean( s, p ) = (1/s.length() sum( x^p | x <- s ))^(1/p)   def monotone( [_], _ ) = true monotone( a1:a2:as, p ) = p( a1, a2 ) and monotone( a2:as, p )   means = [mean( 1..10, m ) | m <- [1, 0, -1]]   for (m, l) <- zip( means, ['Arithmetic', 'Geom...
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" ...
#Julia
Julia
struct BalancedTernary <: Signed digits::Vector{Int8} end BalancedTernary() = zero(BalancedTernary) BalancedTernary(n) = convert(BalancedTernary, n)   const sgn2chr = Dict{Int8,Char}(-1 => '-', 0 => '0', +1 => '+') Base.show(io::IO, bt::BalancedTernary) = print(io, join(sgn2chr[x] for x in reverse(bt.digits))) Base...
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....
#Phix
Phix
with javascript_semantics for i=2 to 99736 by 2 do if remainder(i*i,1000000)=269696 then ?i exit end if end for
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...
#C
C
#include <math.h> #include <stdbool.h> #include <stdio.h>   bool approxEquals(double value, double other, double epsilon) { return fabs(value - other) < epsilon; }   void test(double a, double b) { double epsilon = 1e-18; printf("%f, %f => %d\n", a, b, approxEquals(a, b, epsilon)); }   int main() { test...
http://rosettacode.org/wiki/Approximate_equality
Approximate equality
Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the difference in floating point calculations between different language implementations becomes significant. For example, a difference between 32 bit and 64 bit floating point calculations may appear by about the 8t...
#C.23
C#
using System;   public static class Program { public static void Main() { Test(100000000000000.01, 100000000000000.011); Test(100.01, 100.011); Test(10000000000000.001 / 10000.0, 1000000000.0000001000); Test(0.001, 0.0010000001); Test(0.000000000000000000000101, 0.0); ...
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) ...
#Brat
Brat
string.prototype.balanced? = { brackets = [] balanced = true   my.dice.each_while { c | true? c == "[" { brackets << c } { true? c == "]" { last = brackets.pop false? last == "[" { balanced = false } } }   balanced }   true? brackets.empty? { b...
http://rosettacode.org/wiki/Atomic_updates
Atomic updates
Task Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to: get the current value of any bucket remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the t...
#C.23
C#
- Changed to using object locks and Montor.Enter rather than Mutexes. This allows use of the cleaner "lock" statement, and also has lower runtime overhead for in process locks - The previous implementation tracked a "swapped" state - which seems a harder way to tackle the problem. You need to acquire the locks in th...
http://rosettacode.org/wiki/Atomic_updates
Atomic updates
Task Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to: get the current value of any bucket remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the t...
#C.2B.2B
C++
#include <algorithm> #include <array> #include <chrono> #include <iomanip> #include <iostream> #include <mutex> #include <random> #include <thread>   using namespace std;   constexpr int bucket_count = 15;   void equalizer(array<int, bucket_count>& buckets, array<mutex, bucket_count>& bucket_mutex) { ...
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.
#Axe
Axe
A=42??Returnʳ
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.
#BaCon
BaCon
' Assertions answer = assertion(42) PRINT "The ultimate answer is indeed ", answer   PRINT "Now, expect a failure, unless NDEBUG defined at compile time" answer = assertion(41) PRINT answer END   ' Ensure the given number is the ultimate answer FUNCTION assertion(NUMBER i)   ' BaCon can easily be intimately integra...
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.
#BASIC256
BASIC256
  subroutine assert (condition, message) if not condition then print "ASSERTION FAIED: ";message: throwerror 1 end subroutine   call assert(1+1=2, "but I don't expect this assertion to fail"): rem Does not throw an error rem call assert(1+1=3, "and rightly so"): rem Throws an error  
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...
#J
J
mode=: ~. #~ ( = >./ )@( #/.~ )
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...
#Java
Java
import java.util.*;   public class Mode { public static <T> List<T> mode(List<? extends T> coll) { Map<T, Integer> seen = new HashMap<T, Integer>(); int max = 0; List<T> maxElems = new ArrayList<T>(); for (T value : coll) { if (seen.containsKey(value)) 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 ...
#8th
8th
  {"one": 1, "two": "bad"} ( swap . space . cr ) m:each  
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 ...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Containers.Indefinite_Ordered_Maps;   procedure Test_Iteration is package String_Maps is new Ada.Containers.Indefinite_Ordered_Maps (String, Integer); use String_Maps; A  : Map; Index : Cursor; begin A.Insert ("hello", 1); A.Insert ("world", 2); ...
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...
#Ada
Ada
with Ada.Text_IO;   procedure Apply_Filter is   generic type Num is digits <>; type Num_Array is array (Natural range <>) of Num; A : Num_Array; B : Num_Array; package Direct_Form_II_Transposed is pragma Assert (A'First = 0 and B'First = 0); pragma Assert (A'Last = B'Last); ...
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...
#Arturo
Arturo
arr: [1 2 3 4 5 6 7]   print average arr
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...
#Astro
Astro
mean([1, 2, 3]) mean(1..10) mean([])  
http://rosettacode.org/wiki/Associative_array/Merging
Associative array/Merging
Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merge these into a new associativ...
#Dart
Dart
  main() { var base = { 'name': 'Rocket Skates', 'price': 12.75, 'color': 'yellow' };   var newData = { 'price': 15.25, 'color': 'red', 'year': 1974 };   var updated = Map.from( base ) // create new Map from base ..addAll( newData ); // use cascade operator to add all new data   assert( base.to...
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...
#Delphi
Delphi
  program Associative_arrayMerging;   {$APPTYPE CONSOLE}   uses System.Generics.Collections;   type TData = TDictionary<string, Variant>;   var baseData, updateData, mergedData: TData; entry: string;   begin baseData := TData.Create(); baseData.Add('name', 'Rocket Skates'); baseData.Add('price', 12.75); ...
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...
#Factor
Factor
USING: formatting fry io kernel locals math math.factorials math.functions math.ranges random sequences ;   : (analytical) ( m n -- x ) [ drop factorial ] [ ^ /f ] [ - factorial / ] 2tri ;   : analytical ( n -- x ) dup [1,b] [ (analytical) ] with map-sum ;   : loop-length ( n -- x ) [ 0 0 1 [ 2dup bitand ze...
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...
#FreeBASIC
FreeBASIC
Const max_N = 20, max_ciclos = 1000000   Function Factorial(Byval N As Integer) As Double Dim As Double d: d = 1 If N = 0 Then Factorial = 1: Exit Function While (N > 1) d *= N N -= 1 Wend Factorial = d End Function   Function Analytical(N As Integer) As Double Dim As Double i, s...
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...
#PureBasic
PureBasic
Procedure.d SMA(Number, Period=0) Static P Static NewList L() Protected Sum=0 If Period<>0 P=Period EndIf LastElement(L()) AddElement(L()) L()=Number While ListSize(L())>P FirstElement(L()) DeleteElement(L(),1) Wend ForEach L() sum+L() Next ProcedureReturn sum/ListSize(L()) En...
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....
#Comal
Comal
0010 FUNC factors#(n#) CLOSED 0020 count#:=0 0030 WHILE n# MOD 2=0 DO n#:=n# DIV 2;count#:+1 0040 fac#:=3 0050 WHILE fac#<=n# DO 0060 WHILE n# MOD fac#=0 DO n#:=n# DIV fac#;count#:+1 0070 fac#:+2 0080 ENDWHILE 0090 RETURN count# 0100 ENDFUNC factors# 0110 // 0120 ZONE 4 0130 seen#:=0 0140 FOR i#:=2 ...
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....
#Common_Lisp
Common Lisp
  (defun attractivep (n) (primep (length (factors n))) )   ; For primality testing we can use different methods, but since we have to define factors that's what we'll use (defun primep (n) (= (length (factors n)) 1) )   (defun factors (n) "Return a list of factors of N." (when (> n 1) (loop with max-d = (is...
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 ...
#Icon_and_Unicon
Icon and Unicon
procedure main(A) every put(B := [], ct2a(!A)) write(ca2t(meanAngle(B))) end   procedure ct2a(t) t ? {s := ((1(move(2),move(1))*60 + 1(move(2),move(1)))*60 + move(2))} return (360.0/86400.0) * s end   procedure ca2t(a) while a < 0 do a +:= 360.0 t := integer((86400.0/360.0)*a + 0.5) s := lef...
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 ...
#J
J
require 'types/datetime' parseTimes=: ([: _&".;._2 ,&':');._2 secsFromTime=: 24 60 60 #. ] NB. convert from time to seconds rft=: 2r86400p1 * secsFromTime NB. convert from time to radians meanTime=: 'hh:mm:ss' fmtTime [: secsFromTime [: avgAngleR&.rft parseTimes
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....
#Java
Java
public class AVLtree {   private Node root;   private static class Node { private int key; private int balance; private int height; private Node left; private Node right; private Node parent;   Node(int key, Node parent) { this.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 ...
#Go
Go
package main   import ( "fmt" "math" "math/cmplx" )   func deg2rad(d float64) float64 { return d * math.Pi / 180 } func rad2deg(r float64) float64 { return r * 180 / math.Pi }   func mean_angle(deg []float64) float64 { sum := 0i for _, x := range deg { sum += cmplx.Rect(1, deg2rad(x)) } return rad2deg(cmplx.Ph...
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 ...
#Clojure
Clojure
(defn median [ns] (let [ns (sort ns) cnt (count ns) mid (bit-shift-right cnt 1)] (if (odd? cnt) (nth ns mid) (/ (+ (nth ns mid) (nth ns (dec mid))) 2))))
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 ...
#COBOL
COBOL
FUNCTION MEDIAN(some-table (ALL))
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...
#Futhark
Futhark
  fun arithmetic_mean(as: [n]f64): f64 = reduce (+) 0.0 (map (/f64(n)) as)   fun geometric_mean(as: [n]f64): f64 = reduce (*) 1.0 (map (**(1.0/f64(n))) as)   fun harmonic_mean(as: [n]f64): f64 = f64(n) / reduce (+) 0.0 (map (1.0/) as)   fun main(as: [n]f64): (f64,f64,f64) = (arithmetic_mean as, geometric_mea...
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" ...
#Kotlin
Kotlin
// version 1.1.3   import java.math.BigInteger   val bigZero = BigInteger.ZERO val bigOne = BigInteger.ONE val bigThree = BigInteger.valueOf(3L)   data class BTernary(private var value: String) : Comparable<BTernary> {   init { require(value.all { it in "0+-" }) value = value.trimStart('0') }   ...
http://rosettacode.org/wiki/Babbage_problem
Babbage problem
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p....
#PHP
PHP
<?php   for ( $i = 1 ; // Initial positive integer to check ($i * $i) % 1000000 !== 269696 ; // While i*i does not end with the digits 269,696 $i++ // ... go to next integer );   echo $i, ' * ', $i, ' = ', ($i * $i), PHP_EO...
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...
#C.2B.2B
C++
#include <iomanip> #include <iostream> #include <cmath>   bool approxEquals(double a, double b, double e) { return fabs(a - b) < e; }   void test(double a, double b) { constexpr double epsilon = 1e-18; std::cout << std::setprecision(21) << a; std::cout << ", "; std::cout << std::setprecision(21) << ...
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) ...
#C
C
#include<stdio.h> #include<stdlib.h> #include<string.h>   int isBal(const char*s,int l){ signed c=0; while(l--) if(s[l]==']') ++c; else if(s[l]=='[') if(--c<0) break; return !c; }   void shuffle(char*s,int h){ int x,t,i=h; while(i--){ t=s[x=rand()%h]; s[x]=s[i]; s[i]=t; } }   void genSeq(ch...
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...
#11l
11l
V dict = [‘key1’ = 1, ‘key2’ = 2] V value2 = dict[‘key2’]
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...
#Clojure
Clojure
(defn xfer [m from to amt] (let [{f-bal from t-bal to} m f-bal (- f-bal amt) t-bal (+ t-bal amt)] (if (or (neg? f-bal) (neg? t-bal)) (throw (IllegalArgumentException. "Call results in negative balance.")) (assoc m from f-bal to t-bal))))
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...
#Common_Lisp
Common Lisp
(ql:quickload '(:alexandria :stmx :bordeaux-threads))   (defpackage :atomic-updates (:use :cl))   (in-package :atomic-updates)   (defvar *buckets* nil) (defvar *running* nil)   (defun distribute (ratio a b) "Atomically redistribute the values of buckets A and B by RATIO." (stmx:atomic (let* ((sum (+ (stmx:$ a)...
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.
#BBC_BASIC
BBC BASIC
PROCassert(a% = 42) END   DEF PROCassert(bool%) IF NOT bool% THEN ERROR 100, "Assertion failed" ENDPROC
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.
#BQN
BQN
 ! 2=3 # Failed Error: Assertion error at ! 2=3 # Failed ^ "hello" ! 2=3 # Failed Error: hello at "hello" ! 2=3 # Failed
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.
#Brat
Brat
squish import :assert :assertions   assert_equal 42 42 assert_equal 13 42 #Raises an exception
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...
#JavaScript
JavaScript
function mode(ary) { var counter = {}; var mode = []; var max = 0; for (var i in ary) { if (!(ary[i] in counter)) counter[ary[i]] = 0; counter[ary[i]]++;   if (counter[ary[i]] == max) mode.push(ary[i]); else if (counter[ary[i]] > max) { ...
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 ...
#Aime
Aime
record r; text s;   r_put(r, "A", 33); # an integer value r_put(r, "C", 2.5); # a real value r_put(r, "B", "associative"); # a string value   if (r_first(r, s)) { do { o_form("key ~, value ~ (~)\n", s, r[s], r_type(r, s)); } while (rsk_greater(r, s, s)); }
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 ...
#ALGOL_68
ALGOL 68
# associative array handling using hashing #   # the modes allowed as associative array element values - change to suit # MODE AAVALUE = STRING; # the modes allowed as associative array element keys - change to suit # MODE AAKEY = STRING; # nil element 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...
#ALGOL_68
ALGOL 68
BEGIN # apply a digital filter # PROC filter = ( []REAL a, b, signal, REF[]REAL result )VOID: BEGIN FOR i FROM LWB result TO UPB result DO result[ i ] := 0 OD; FOR i FROM LWB signal TO UPB signal DO REAL tmp := 0; FOR j FROM LWB b TO UPB b DO ...
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...
#AutoHotkey
AutoHotkey
i = 10 Loop, % i { Random, v, -3.141592, 3.141592 list .= v "`n" sum += v } MsgBox, % i ? list "`nmean: " sum/i:0
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#AWK
AWK
cat mean.awk #!/usr/local/bin/gawk -f   # User defined function function mean(v, i,n,sum) { for (i in v) { n++ sum += v[i] } if (n>0) { return(sum/n) } else { return("zero-length input !") } }   BEGIN { # fill a vector with random numbers for(i=0; i < 10; i++) { vett[i] = rand()*1...
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...
#Elixir
Elixir
base = %{name: "Rocket Skates", price: 12.75, color: "yellow"} update = %{price: 15.25, color: "red", year: 1974} result = Map.merge(base, update) IO.inspect(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...
#F.23
F#
  type N = |Price of float|Name of string|Year of int|Colour of string let n=Map<string,N>[("name",Name("Rocket Skates"));("price",Price(12.75));("colour",Colour("yellow"))] let g=Map<string,N>[("price",Price(15.25));("colour",Colour("red"));("year",Year(1974))] let ng=(Map.toList n)@(Map.toList g)|>Map.ofList printfn ...
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...
#Factor
Factor
USING: assocs prettyprint ;   { { "name" "Rocket Skates" } { "price" 12.75 } { "color" "yellow" } } { { "price" 15.25 } { "color" "red" } { "year" 1974 } } assoc-union .
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...
#FutureBasic
FutureBasic
  _nmax = 20 _times = 1000000   local fn Average( n as long, times as long ) as double long i, x double b, c = 0   for i = 0 to times x = 1 : b = 0 while ( b and x ) == 0 c++ b = b || x x = 1 << ( rnd(n) - 1 ) wend next end fn = c / times   local fn Analyltic( n as long ) as doub...
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...
#Go
Go
package main   import ( "fmt" "math" "math/rand" )   const nmax = 20   func main() { fmt.Println(" N average analytical (error)") fmt.Println("=== ========= ============ =========") for n := 1; n <= nmax; n++ { a := avg(n) b := ana(n) fmt.Printf("%3d  %9.4f  %...
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...
#Python
Python
from collections import deque   def simplemovingaverage(period): assert period == int(period) and period > 0, "Period must be an integer >0"   summ = n = 0.0 values = deque([0.0] * period) # old value queue   def sma(x): nonlocal summ, n   values.append(x) summ += x - values....
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....
#Cowgol
Cowgol
include "cowgol.coh"; const MAXIMUM := 120;   typedef N is int(0, MAXIMUM + 1); var prime: uint8[MAXIMUM + 1];   sub Sieve() is MemSet(&prime[0], 1, @bytesof prime); prime[0] := 0; prime[1] := 0;   var cand: N := 2; while cand <= MAXIMUM >> 1 loop if prime[cand] != 0 then var com...
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....
#D
D
import std.stdio;   enum MAX = 120;   bool isPrime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; int d = 5; while (d * d <= n) { if (n % d == 0) return false; d += 2; if (n % d == 0) return false; d += 4; } ret...
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 ...
#Java
Java
public class MeanTimeOfDay {   static double meanAngle(double[] angles) { int len = angles.length; double sinSum = 0.0; for (int i = 0; i < len; i++) { sinSum += Math.sin(angles[i] * Math.PI / 180.0); }   double cosSum = 0.0; for (int i = 0; i < len; i++) ...
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....
#JavaScript
JavaScript
function tree(less, val, more) { return { depth: 1+Math.max(less.depth, more.depth), less: less, val: val, more: more, }; }   function node(val) { return tree({depth: 0}, val, {depth: 0}); }   function insert(x,y) { if (0 == y.depth) return x; if (0 == x.depth) return y; if (1 == x.depth && ...
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 ...
#Groovy
Groovy
import static java.lang.Math.* def meanAngle = { atan2( it.sum { sin(it * PI / 180) } / it.size(), it.sum { cos(it * PI / 180) } / it.size()) * 180 / PI }
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 ...
#Haskell
Haskell
import Data.Complex (cis, phase)   meanAngle :: RealFloat c => [c] -> c meanAngle = (/ pi) . (* 180) . phase . sum . map (cis . (/ 180) . (* pi))   main :: IO () main = mapM_ (\angles -> putStrLn $ "The mean angle of " ++ show angles ++ " is: " ++ show (meanAngle angles) ++ " degrees")...
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#Common_Lisp
Common Lisp
((defun select-nth (n list predicate) "Select nth element in list, ordered by predicate, modifying list." (do ((pivot (pop list)) (ln 0) (left '()) (rn 0) (right '())) ((endp list) (cond ((< n ln) (select-nth n left predicate)) ((eql n ln) pivot) ((< n (+ ln rn 1))...
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...
#GAP
GAP
# The first two work with rationals or with floats # (but bear in mind that support of floating point is very poor in GAP) mean := v -> Sum(v) / Length(v); harmean := v -> Length(v) / Sum(v, Inverse); geomean := v -> EXP_FLOAT(Sum(v, LOG_FLOAT) / Length(v));   mean([1 .. 10]); # 11/2 harmean([1 .. 10]); # 25200/7381  ...
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" ...
#Liberty_BASIC
Liberty BASIC
  global tt$ tt$="-0+" '-1 0 1; +2 -> 1 2 3, instr   'Test case: 'With balanced ternaries a from string "+-0++0+", b from native integer -436, c "+-++-": '* write out a, b and c in decimal notation; '* calculate a * (b - c), write out the result in both ternary and decimal notations.   a$="+-0++0+" a=deci(a$) print "...
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....
#Picat
Picat
main => N = 1, while (N**2 mod 1000000 != 269696) N := N + 1 end, println(N).
http://rosettacode.org/wiki/Babbage_problem
Babbage problem
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p....
#PicoLisp
PicoLisp
: (for N 99736 # Iterate N from 1 to 99736 (T (= 269696 (% (* N N) 1000000)) N) ) # Stop if remainder is 269696 -> 25264
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...
#Common_Lisp
Common Lisp
  (defun approx-equal (float1 float2 &optional (threshold 0.000001)) "Determine whether float1 and float2 are equal; THRESHOLD is the maximum allowable difference between normalized significands of floats with the same exponent. The significands are scaled appropriately before comparison for floats with different exp...
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...
#D
D
import std.math; import std.stdio;   auto approxEquals = (double a, double b, double epsilon) => abs(a - b) < epsilon;   void main() { void test(double a, double b) { double epsilon = 1e-18; writefln("%.18f, %.18f => %s", a, b, a.approxEquals(b, epsilon)); }   test(100000000000000.01, 100000...
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) ...
#C.23
C#
using System; using System.Linq;   class Program { static bool IsBalanced(string text, char open = '[', char close = ']') { var level = 0; foreach (var character in text) { if (character == close) { if (level == 0) { ...
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...
#8th
8th
  { "one" : 1, "two" : "bad" }  
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...
#D
D
import std.stdio: writeln; import std.conv: text; import std.random: uniform, Xorshift; import std.algorithm: min, max; import std.parallelism: task; import core.thread: Thread; import core.sync.mutex: Mutex; import core.time: seconds;   __gshared uint transfersCount;   final class Buckets(size_t nBuckets) if (nBuckets...
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.
#C
C
#include <assert.h>   int main(){ int a; /* ...input or change a here */ assert(a == 42); /* aborts program when a is not 42, unless the NDEBUG macro was defined */   return 0; }
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.
#C.23_and_Visual_Basic_.NET
C# and Visual Basic .NET
using System.Diagnostics; // Debug and Trace are in this namespace.   static class Program { static void Main() { int a = 0;   Console.WriteLine("Before");   // Always hit. Trace.Assert(a == 42, "Trace assertion failed");   Console.WriteLine("After Trace.Assert");   ...
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#11l
11l
V array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] V arrsq = array.map(i -> i * i) print(arrsq)
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...
#jq
jq
# modes/0 produces an array of [value, count] # in increasing order of count: def modes: sort | reduce .[] as $i ([]; # state variable is an array of [value, count] if length == 0 then [ [$i, 1] ] elif .[-1][0] == $i then setpath([-1,1]; .[-1][1] + 1) else . + [[$i,1]] end ) | sort_by( .[1] );...
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...
#Julia
Julia
function modes(values) dict = Dict() # Values => Number of repetitions modesArray = typeof(values[1])[] # Array of the modes so far max = 0 # Max of repetitions so far   for v in values # Add one to the dict[v] entry (create one if none) if v in keys(dict) dict[v] += 1 ...
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 ...
#App_Inventor
App Inventor
; create a dictionary d: #[ name: "john" surname: "doe" age: 34 ]   ; Iterate over key/value pairs loop d [key,value][ print ["key =" key ", value =" value] ]   print "----"   ; Iterate over keys loop keys d [k][ print ["key =" k] ]   print "----"   ; Iterate over values loop values d [v][ print ["value =" 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 ...
#Arturo
Arturo
; create a dictionary d: #[ name: "john" surname: "doe" age: 34 ]   ; Iterate over key/value pairs loop d [key,value][ print ["key =" key ", value =" value] ]   print "----"   ; Iterate over keys loop keys d [k][ print ["key =" k] ]   print "----"   ; Iterate over values loop values d [v][ print ["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...
#AppleScript
AppleScript
on min(a, b) if (b < a) then return b return a end min   on DF2TFilter(a, b, sig) set aCount to (count a) set bCount to (count b) set sigCount to (count sig) set rst to {}   repeat with i from 1 to sigCount set tmp to 0 set iPlus1 to i + 1 repeat with j from 1 to min(...
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...
#Babel
Babel
(3 24 18 427 483 49 14 4294 2 41) dup len <- sum ! -> / itod <<
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...
#BASIC
BASIC
mean = 0 sum = 0; FOR i = LBOUND(nums) TO UBOUND(nums) sum = sum + nums(i); NEXT i size = UBOUND(nums) - LBOUND(nums) + 1 PRINT "The mean is: "; IF size <> 0 THEN PRINT (sum / size) ELSE PRINT 0 END IF
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...
#Go
Go
package main   import "fmt"   type assoc map[string]interface{}   func merge(base, update assoc) assoc { result := make(assoc) for k, v := range base { result[k] = v } for k, v := range update { result[k] = v } return result }   func main() { base := assoc{"name": "Rocket Ska...
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...
#Haskell
Haskell
data Item = Item { name :: Maybe String , price :: Maybe Float , color :: Maybe String , year :: Maybe Int } deriving (Show)   itemFromMerge :: Item -> Item -> Item itemFromMerge (Item n p c y) (Item n1 p1 c1 y1) = Item (maybe n pure n1) (maybe p pure p1) (maybe c pure c1) (maybe y pure y1)   main :: IO () ...
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...
#Haskell
Haskell
import System.Random import qualified Data.Set as S import Text.Printf   findRep :: (Random a, Integral a, RandomGen b) => a -> b -> (a, b) findRep n gen = findRep' (S.singleton 1) 1 gen where findRep' seen len gen' | S.member fx seen = (len, gen'') | otherwise = findRep' (S.insert ...
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...
#J
J
(~.@, {&0 0@{:)^:_] 0 0 (~.@, {&0 0@{:)^:_] 1 1 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...
#Quackery
Quackery
[ $ "bigrat.qky" loadfile ] now!   [ over size - space swap of join ] is pad ( $ n --> $ )   [ ' [ stack [ ] ] copy nested ' [ tuck take swap join dup size ] join swap join ' [ > if [ 1 split nip ] tuck swap put 0 over witheach + ...
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....
#Delphi
Delphi
/* Sieve of Eratosthenes */ proc nonrec sieve([*] bool prime) void: word p, c, max; max := (dim(prime,1)-1)>>1; prime[0] := false; prime[1] := false; for p from 2 upto max do prime[p] := true od; for p from 2 upto max>>1 do if prime[p] then for c from p*2 by p upto max do ...
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....
#Draco
Draco
/* Sieve of Eratosthenes */ proc nonrec sieve([*] bool prime) void: word p, c, max; max := (dim(prime,1)-1)>>1; prime[0] := false; prime[1] := false; for p from 2 upto max do prime[p] := true od; for p from 2 upto max>>1 do if prime[p] then for c from p*2 by p upto max do ...
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 ...
#JavaScript
JavaScript
var args = process.argv.slice(2);   function time_to_seconds( hms ) { var parts = hms.split(':'); var h = parseInt(parts[0]); var m = parseInt(parts[1]); var s = parseInt(parts[2]); if ( h < 12 ) { h += 24; } var seconds = parseInt(parts[0]) * 60 * 60 + parseInt(parts[1]) * 60 + par...
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....
#Julia
Julia
module AVLTrees   import Base.print export AVLNode, AVLTree, insert, deletekey, deletevalue, findnodebykey, findnodebyvalue, allnodes   @enum Direction LEFT RIGHT avlhash(x) = Int32(hash(x) & 0xfffffff) const MIDHASH = Int32(div(0xfffffff, 2))   mutable struct AVLNode{T} value::T key::Int32 balance::Int32 ...
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 ...
#Icon_and_Unicon
Icon and Unicon
procedure main(A) write("Mean angle is ",meanAngle(A)) end   procedure meanAngle(A) every (sumSines := 0.0) +:= sin(dtor(!A)) every (sumCosines := 0.0) +:= cos(dtor(!A)) return rtod(atan(sumSines/*A,sumCosines/*A)) end
http://rosettacode.org/wiki/Averages/Mean_angle
Averages/Mean angle
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the ...
#IDL
IDL
function mean_angle, phi z = total(exp(complex(0,phi*!dtor))) return, atan(imaginary(z),real_part(z))*!radeg end
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 ...
#Crystal
Crystal
def median(ary) srtd = ary.sort alen = srtd.size 0.5*(srtd[(alen-1)//2] + srtd[alen//2]) end   a = [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2] puts median a   a = [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2, 5.0] puts median a   a = [5.0] puts median a