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/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.
#Clean
Clean
square x = x * x   values :: {#Int} values = {x \\ x <- [1 .. 10]}
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...
#Octave
Octave
function m = mode2(v) sv = sort(v); % build two vectors, vals and c, so that % c(i) holds how many times vals(i) appears i = 1; c = []; vals = []; while (i <= numel(v) ) tc = sum(sv==sv(i)); % it would be faster to count % them "by hand", since sv is sorted... c = [c, tc]; ...
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 ...
#D
D
import std.stdio: writeln;   void main() { // the associative array auto aa = ["alice":2, "bob":97, "charlie":45];   // how to iterate key/value pairs: foreach (key, value; aa) writeln("1) Got key ", key, " with value ", value); writeln();   // how to iterate the keys: foreach (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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
b = {0.16666667, 0.5, 0.5, 0.16666667}; a = {1.00000000, -2.77555756*^-16, 3.33333333*^-01, -1.85037171*^-17}; signal = {-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.4008...
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...
#MATLAB
MATLAB
  signal = [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 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...
#Dyalect
Dyalect
func avg(args...) { var acc = .0 var len = 0 for x in args { len += 1 acc += x } acc / len }   avg(1, 2, 3, 4, 5, 6)
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...
#E
E
def meanOrZero(numbers) { var count := 0 var sum := 0 for x in numbers { sum += x count += 1 } return sum / 1.max(count) }
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...
#Tcl
Tcl
set dict1 [dict create name "Rocket Skates" price 12.75 color yellow] set dict2 [dict create price 15.25 color red year 1974] dict for {key val} [dict merge $dict1 $dict2] { puts "$key: $val" }
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...
#VBA
VBA
  Private Type Associative Key As String Value As Variant End Type Sub Main_Array_Associative() Dim BaseArray(2) As Associative, UpdateArray(2) As Associative FillArrays BaseArray, UpdateArray ReDim Result(UBound(BaseArray)) As Associative MergeArray Result, BaseArray, UpdateArray PrintOut Resul...
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...
#Ruby
Ruby
class Integer def factorial self == 0 ? 1 : (1..self).inject(:*) end end   def rand_until_rep(n) rands = {} loop do r = rand(1..n) return rands.size if rands[r] rands[r] = true end end   runs = 1_000_000   puts " N average exp. diff ", "=== ======== ======== ==========="...
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...
#Rust
Rust
extern crate rand;   use rand::{ThreadRng, thread_rng}; use rand::distributions::{IndependentSample, Range}; use std::collections::HashSet; use std::env; use std::process;   fn help() { println!("usage: average_loop_length <max_N> <trials>"); }   fn main() { let args: Vec<String> = env::args().collect(); le...
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...
#Smalltalk
Smalltalk
Object subclass: MovingAverage [ |valueCollection period collectedNumber sum| MovingAverage class >> newWithPeriod: thePeriod [ |r| r := super basicNew. ^ r initWithPeriod: thePeriod ] initWithPeriod: thePeriod [ valueCollection := OrderedCollection new: thePeriod. period := thePeriod. collect...
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....
#Lua
Lua
-- Returns true if x is prime, and false otherwise function isPrime (x) if x < 2 then return false end if x < 4 then return true end if x % 2 == 0 then return false end for d = 3, math.sqrt(x), 2 do if x % d == 0 then return false end end return true end   -- Compute the prime factors of n function fact...
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 ...
#PHP
PHP
  <?php function time2ang($tim) { if (!is_string($tim)) return $tim; $parts = explode(':',$tim); if (count($parts)!=3) return $tim; $sec = ($parts[0]*3600)+($parts[1]*60)+$parts[2]; $ang = 360.0 * ($sec/86400.0); return $ang; } function ang2time($ang) { if (!is_nu...
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....
#Scheme
Scheme
(cond-expand (r7rs) (chicken (import r7rs)))   (define-library (avl-trees)   ;; ;; This library implements ‘persistent’ (that is, ‘immutable’) AVL ;; trees for R7RS Scheme. ;; ;; Included are generators of the key-data pairs in a tree. Because ;; the trees are persistent (‘immutable’), these generators ...
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 ...
#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 sprintf("%g",round(atan2(y,x)*180/P...
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 ...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Sub quicksort(a() As Double, first As Integer, last As Integer) Dim As Integer length = last - first + 1 If length < 2 Then Return Dim pivot As Double = a(first + length\ 2) Dim lft As Integer = first Dim rgt As Integer = last While lft <= rgt While a(lft) < pivot lft +=1 ...
http://rosettacode.org/wiki/Averages/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...
#Kotlin
Kotlin
import kotlin.math.round import kotlin.math.pow   fun Collection<Double>.geometricMean() = if (isEmpty()) Double.NaN else (reduce { n1, n2 -> n1 * n2 }).pow(1.0 / size)   fun Collection<Double>.harmonicMean() = if (isEmpty() || contains(0.0)) Double.NaN else size / fold(0.0) { n1, n2 -> n1 + 1.0 / n2 } ...
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" ...
#REXX
REXX
/*REXX program converts decimal ◄───► balanced ternary; it also performs arithmetic. */ numeric digits 10000 /*be able to handle gihugic numbers. */ Ao = '+-0++0+' ; Abt = Ao /* [↓] 2 literals used by subroutine*/ Bo = '-436' ; Bbt = d2bt(Bo); ...
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....
#Scala
Scala
  object BabbageProblem { def main( args:Array[String] ): Unit = {   var x : Int = 524 // Sqrt of 269696 = 519.something   while( (x * x) % 1000000 != 269696 ){ if( x % 10 == 4 ) x = x + 2 else x = x + 8 }   println("The smallest positive integer whose ...
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...
#Raku
Raku
say 0.1 + 0.2 + 0.3 + 0.4 === 1.0000000000000000000000000000000000000000000000000000000000000000000000000; # True
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...
#ReScript
ReScript
let approx_eq = (v1, v2, epsilon) => { abs_float (v1 -. v2) < epsilon }   let test = (a, b) => { let epsilon = 1e-18 Printf.printf("%g, %g => %b\n", a, b, approx_eq(a, b, epsilon)) }   { test(100000000000000.01, 100000000000000.011) test(100.01, 100.011) test(10000000000000.001 /. 10000.0, 1000000000.000000...
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...
#REXX
REXX
/*REXX program mimics an "approximately equal to" for comparing floating point numbers*/ numeric digits 15 /*what other FP hardware normally uses.*/ @.= /*assign default for the @ array. */ parse arg @.1 ...
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) ...
#EchoLisp
EchoLisp
  (define (balance str) (for/fold (closed 0) ((par str)) #:break (< closed 0 ) => closed (+ closed (cond ((string=? par "[") 1) ((string=? par "]") -1) (else 0)))))   (define (task N) (define str (list->string (append (make-list N "[") (make-list N "]")))) (for ((i 10)) (set! str (list->string (shuffle (...
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,...
#Go
Go
package main   import ( "bytes" "fmt" "io" "io/ioutil" "os" )   type pw struct { account, password string uid, gid uint gecos directory, shell string }   type gecos struct { fullname, office, extension, homephone, email string }   func (p *pw) encode(w io.Writer) (int, e...
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...
#AutoHotkey
AutoHotkey
associative_array := {key1: "value 1", "Key with spaces and non-alphanumeric characters !*+": 23} MsgBox % associative_array.key1 . "`n" associative_array["Key with spaces and non-alphanumeric characters !*+"]
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
#Common_Lisp
Common Lisp
(defun factors (n &aux (lows '()) (highs '())) (do ((limit (1+ (isqrt n))) (factor 1 (1+ factor))) ((= factor limit) (when (= n (* limit limit)) (push limit highs)) (remove-duplicates (nreconc lows highs))) (multiple-value-bind (quotient remainder) (floor n fa...
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...
#Oz
Oz
declare %% %% INIT %% NBuckets = 100 StartVal = 50 ExpectedSum = NBuckets * StartVal   %% Makes a tuple and calls Fun for every field fun {Make Label N Fun} R = {Tuple.make Label N} in for I in 1..N do R.I = {Fun} end R end   Buckets = {Make buckets NBuckets fun {$} {Cell.new StartV...
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.
#Liberty_BASIC
Liberty BASIC
  a=42 call assert a=42 print "passed"   a=41 call assert a=42 print "failed (we never get here)" end   sub assert cond if cond=0 then 'simulate error, mentioning "AssertionFailed" AssertionFailed(-1)=0 end if end sub  
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.
#Lingo
Lingo
-- in a movie script on assert (ok, message) if not ok then if not voidP(message) then _player.alert(message) abort -- exits from current call stack, i.e. also from the caller function end if end   -- anywhere in the code on test x = 42 assert(x=42, "Assertion 'x=42' failed") put "this shows up" x =...
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Lisaac
Lisaac
? { 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.
#Clio
Clio
[1 2 3 4] * 2 + 1 -> print
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.
#Clojure
Clojure
;; apply a named function, inc (map inc [1 2 3 4])
http://rosettacode.org/wiki/Averages/Mode
Averages/Mode
Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat...
#ooRexx
ooRexx
  -- will work with just about any collection... call testMode .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1) call testMode .list~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11) call testMode .queue~of(30, 10, 20, 30, 40, 50, -100, 4.7, -11e2)   ::routine testMode use arg list say "list =" list~makearray~toString("l",...
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 ...
#Dao
Dao
  dict = { 'def' => 1, 'abc' => 2 }   for( keyvalue in dict ) io.writeln( keyvalue ); for( key in dict.keys(); value in dict.values() ) io.writeln( key, value ) dict.iterate { [key, value] io.writeln( 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 ...
#Dart
Dart
  main(){ var fruits = { 'apples': 'red', 'oranges': 'orange', 'bananas': 'yellow', 'pears': 'green', 'plums': 'purple' };   print('Key Value pairs:'); fruits.forEach( (fruits, color) => print( '$fruits are $color' ) );   print('\nKeys only:'); fruits.keys.forEach( ( key ) => print( key ) );   pri...
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...
#Nim
Nim
  import strformat   func filter(a, b, signal: openArray[float]): seq[float] =   result.setLen(signal.len)   for i in 0..signal.high: var tmp = 0.0 for j in 0..min(i, b.high): tmp += b[j] * signal[i - j] for j in 1..min(i, a.high): tmp -= a[j] * result[i - j] tmp /= a[0] result[i] = ...
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...
#Objeck
Objeck
class DigitalFilter { function : Main(args : String[]) ~ Nil { a := [1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17]; b := [0.16666667, 0.5, 0.5, 0.16666667]; signal := [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677, 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...
#EasyLang
EasyLang
func mean . f[] r . for i range len f[] s += f[i] . r = s / len f[] . f[] = [ 1 2 3 4 5 6 7 8 ] call mean f[] r print r
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...
#EchoLisp
EchoLisp
  (lib 'math) (mean '(1 2 3 4)) ;; mean of a list → 2.5 (mean #(1 2 3 4)) ;; mean of a vector → 2.5   (lib 'sequences) (mean [1 3 .. 10]) ;; mean of a sequence → 5   ;; error handling (mean 'elvis) ⛔ error: mean : expected sequence : elvis (mean ()) 💣 error: mean : null is not an object (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...
#Wren
Wren
var mergeMaps = Fn.new { |m1, m2| var m3 = {} for (key in m1.keys) m3[key] = m1[key] for (key in m2.keys) m3[key] = m2[key] return m3 }   var base = { "name": "Rocket Skates" , "price": 12.75, "color": "yellow" } var update = { "price": 15.25, "color": "red", "year": 1974 } var merged = mergeMaps.c...
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...
#Vlang
Vlang
type Generic = int|string|f64 type Assoc = map[string]Generic   fn merge(base Assoc, update Assoc) Assoc { mut result := Assoc(map[string]Generic{}) for k, v in base { result[k] = v } for k, v in update { result[k] = v } return result }   fn main() { base := Assoc({"name": Ge...
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...
#Wren_2
Wren
var mergeMaps = Fn.new { |m1, m2| var m3 = {} for (key in m1.keys) m3[key] = m1[key] for (key in m2.keys) m3[key] = m2[key] return m3 }   var base = { "name": "Rocket Skates" , "price": 12.75, "color": "yellow" } var update = { "price": 15.25, "color": "red", "year": 1974 } var merged = mergeMaps.c...
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...
#Scala
Scala
  import scala.util.Random   object AverageLoopLength extends App {   val factorial: LazyList[Double] = 1 #:: factorial.zip(LazyList.from(1)).map(n => n._2 * factorial(n._2 - 1)) val results = for (n <- 1 to 20; avg = tested(n, 1000000); theory = expected(n) ...
http://rosettacode.org/wiki/Averages/Simple_moving_average
Averages/Simple moving average
Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is a method for computing an avera...
#Swift
Swift
struct SimpleMovingAverage { var period: Int var numbers = [Double]()   mutating func addNumber(_ n: Double) -> Double { numbers.append(n)   if numbers.count > period { numbers.removeFirst() }   guard !numbers.isEmpty else { return 0 }   return numbers.reduce(0, +) / Double(num...
http://rosettacode.org/wiki/Attractive_numbers
Attractive numbers
A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show sequence items up to   120....
#Maple
Maple
attractivenumbers := proc(n::posint) local an, i; an :=[]: for i from 1 to n do if isprime(NumberTheory:-NumberOfPrimeFactors(i)) then an := [op(an), i]: end if: end do: end proc: attractivenumbers(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....
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[AttractiveNumberQ] AttractiveNumberQ[n_Integer] := FactorInteger[n][[All, 2]] // Total // PrimeQ Reap[Do[If[AttractiveNumberQ[i], Sow[i]], {i, 120}]][[2, 1]]
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 ...
#PicoLisp
PicoLisp
(load "@lib/math.l")   (de meanTime (Lst) (let Tim (*/ (atan2 (sum '((S) (sin (*/ ($tim S) pi 43200))) Lst) (sum '((S) (cos (*/ ($tim S) pi 43200))) Lst) ) 43200 pi ) (tim$ (% (+ Tim 86400) 86400) T) ) )
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 ...
#PL.2FI
PL/I
*process source attributes xref; avt: Proc options(main); /*-------------------------------------------------------------------- * 25.06.2014 Walter Pachl taken from REXX *-------------------------------------------------------------------*/ Dcl (addr,hbound,sin,cos,atan) Builtin; Dcl sysprint Print; Dcl times(4...
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....
#Sidef
Sidef
class AVLtree {   has root = nil   struct Node { Number key, Number balance = 0, Node left = nil, Node right = nil, Node parent = nil, }   method insert(key) { if (root == nil) { root = Node(key) return true }   var ...
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 ...
#PHP
PHP
<?php $samples = array( '1st' => array(350, 10), '2nd' => array(90, 180, 270, 360), '3rd' => array(10, 20, 30) );   foreach($samples as $key => $sample){ echo 'Mean angle for ' . $key . ' sample: ' . meanAngle($sample) . ' degrees.' . PHP_EOL; }   function meanAngle ($angles){ $y_part = $x_part = 0; $size = cou...
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 ...
#GAP
GAP
Median := function(v) local n, w; w := SortedList(v); n := Length(v); return (w[QuoInt(n + 1, 2)] + w[QuoInt(n, 2) + 1]) / 2; end;   a := [41, 56, 72, 17, 93, 44, 32]; b := [41, 72, 17, 93, 44, 32];   Median(a); # 44 Median(b); # 85/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 ...
#Go
Go
package main   import ( "fmt" "sort" )   func main() { fmt.Println(median([]float64{3, 1, 4, 1})) // prints 2 fmt.Println(median([]float64{3, 1, 4, 1, 5})) // prints 3 }   func median(a []float64) float64 { sort.Float64s(a) half := len(a) / 2 m := a[half] if len(a)%2 == 0 { m ...
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...
#Lasso
Lasso
define arithmetic_mean(a::staticarray)::decimal => { //sum of the list divided by its length return (with e in #a sum #e) / decimal(#a->size) } define geometric_mean(a::staticarray)::decimal => { // The geometric mean is the nth root of the product of the list local(prod = 1) with e in #a do => { #prod *= #e } re...
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" ...
#Ruby
Ruby
class BalancedTernary include Comparable def initialize(str = "") if str =~ /[^-+0]+/ raise ArgumentError, "invalid BalancedTernary number: #{str}" end @digits = trim0(str) end   I2BT = {0 => ["0",0], 1 => ["+",0], 2 => ["-",1]} def self.from_int(value) n = value.to_i digits = "" ...
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....
#Scheme
Scheme
  (define (digits n) (string->list (number->string n)))   (define (ends-with list tail) ;; does list end with tail? (starts-with (reverse list) (reverse tail)))   (define (starts-with list head) (cond ((null? head) #t) ((null? list) #f) ((equal? (car list) (car h...
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...
#Ruby
Ruby
require "bigdecimal"   testvalues = [[100000000000000.01, 100000000000000.011], [100.01, 100.011], [10000000000000.001 / 10000.0, 1000000000.0000001000], [0.001, 0.0010000001], [0.000000000000000000000101, 0...
http://rosettacode.org/wiki/Approximate_equality
Approximate equality
Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the difference in floating point calculations between different language implementations becomes significant. For example, a difference between 32 bit and 64 bit floating point calculations may appear by about the 8t...
#Rust
Rust
/// Return whether the two numbers `a` and `b` are close. /// Closeness is determined by the `epsilon` parameter - /// the numbers are considered close if the difference between them /// is no more than epsilon * max(abs(a), abs(b)). fn isclose(a: f64, b: f64, epsilon: f64) -> bool { (a - b).abs() <= a.abs().max(b...
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) ...
#Elena
Elena
import system'routines; import extensions; import extensions'text;   randomBrackets(len) { if (0 == len) { ^emptyString } else { var brackets := Array.allocate(len).populate:(i => $91) + Array.allocate(len).populate:(i => $93);   brack...
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,...
#Groovy
Groovy
class PasswdRecord { String account, password, directory, shell int uid, gid SourceRecord source   private static final fs = ':' private static final fieldNames = ['account', 'password', 'uid', 'gid', 'source', 'directory', 'shell'] private static final stringFields = ['account', 'password', 'di...
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...
#AutoIt
AutoIt
; Associative arrays in AutoIt. ; All the required functions are below the examples.   ; Initialize an error handler to deal with any COM errors.. global $oMyError = ObjEvent("AutoIt.Error", "AAError")   ; first example, simple. global $simple   ; Initialize your array ... AAInit($simple)   AAAdd($simple, "Appple", "fr...
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
#Cowgol
Cowgol
include "cowgol.coh"; const AMOUNT := 20;   sub countFactors(n: uint16): (count: uint16) is var i: uint16 := 1; count := 1; while i <= n/2 loop if n%i == 0 then count := count + 1; end if; i := i + 1; end loop; end sub;   var max: uint16 := 0; var seen: uint8 := 0; va...
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
#Crystal
Crystal
def count_divisors(n : Int64) : Int64 return 1_i64 if n < 2 count = 2_i64   i = 2 while i <= n // 2 count += 1 if n % i == 0 i += 1 end   count end   max_div = 0_i64 count = 0_i64   print "The first 20 anti-primes are: "   n = 1_i64 while count < 20 d = count_divisors n   if d > max_div 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...
#PARI.2FGP
PARI/GP
use strict; use 5.10.0;   use threads 'yield'; use threads::shared;   my @a :shared = (100) x 10; my $stop :shared = 0;   sub pick2 { my $i = int(rand(10)); my $j; $j = int(rand(10)) until $j != $i; ($i, $j) }   sub even { lock @a; my ($i, $j) = pick2; my $sum = $a[$i] + $a[$j]; $a[$i] = int($sum / 2); $a[$j] ...
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.
#Lua
Lua
a = 5 assert (a == 42) assert (a == 42,'\''..a..'\' is not the answer to life, the universe, and everything')
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.
#M2000_Interpreter
M2000 Interpreter
  Module Assert { \\ This is a global object named Rec Global Group Rec { Private: document doc$="Error List at "+date$(today)+" "+time$(now)+{ } Public: lastfilename$="noname.err" Module Error(a$) { if a$="" then exit ...
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.
#Maple
Maple
a := 5: ASSERT( a = 42 ); ASSERT( a = 42, "a is not the answer to life, the universe, and everything" );
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.
#CLU
CLU
% This procedure will call a given procedure with each element % of the given array. Thanks to CLU's type parameterization, % it will work for any type of element. apply_to_all = proc [T: type] (a: array[T], f: proctype(int,T)) for i: int in array[T]$indexes(a) do f(i, a[i]) end end apply_to_all   % Cal...
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.
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. Map.   DATA DIVISION. WORKING-STORAGE SECTION. 01 Table-Size CONSTANT 30.   LOCAL-STORAGE SECTION. 01 I USAGE UNSIGNED-INT.   LINKAGE SECTION. 01 Table-Param. 03 Table-Values USAGE COMP-2 OCCURS Table-Size...
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...
#Oz
Oz
declare fun {Mode Xs} Freq = {Dictionary.new} for X in Xs do Freq.X := {CondSelect Freq X 0} + 1 end MaxCount = {FoldL {Dictionary.items Freq} Max 0} in for Value#Count in {Dictionary.entries Freq} collect:C do if Count == MaxCount then {C Value} end end e...
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 ...
#Delphi
Delphi
program AssociativeArrayIteration;   {$APPTYPE CONSOLE}   uses SysUtils, Generics.Collections;   var i: Integer; s: string; lDictionary: TDictionary<string, Integer>; lPair: TPair<string, Integer>; begin lDictionary := TDictionary<string, Integer>.Create; try lDictionary.Add('foo', 5); lDictionary.A...
http://rosettacode.org/wiki/Apply_a_digital_filter_(direct_form_II_transposed)
Apply a digital filter (direct form II transposed)
Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [1] Task Filt...
#ooRexx
ooRexx
/* REXX */ a=.array~of(1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17) b=.array~of(0.16666667, 0.5, 0.5, 0.16666667) s=.array~of(-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412,, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044,, 0.743500089861, 1.01...
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...
#Perl
Perl
use strict; use List::AllUtils 'natatime';   sub TDF_II_filter { our(@signal,@a,@b); local(*signal,*a,*b) = (shift, shift, shift); my @out = (0) x $#signal; for my $i (0..@signal-1) { my $this; map { $this += $b[$_] * $signal[$i-$_] if $i-$_ >= 0 } 0..@b; map { $this -= $a[$_...
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...
#ECL
ECL
  AveVal(SET OF INTEGER s) := AVE(s);   //example usage   SetVals := [14,9,16,20,91]; AveVal(SetVals) //returns 30.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...
#Elena
Elena
import extensions;   extension op { average() { real sum := 0; int count := 0;   var enumerator := self.enumerator();   while (enumerator.next()) { sum += enumerator.get(); count += 1; };   ^ sum / count } }   public program() {...
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...
#zkl
zkl
base:=Dictionary( "name", "Rocket Skates", "price", 12.75, "color", "yellow",); update:=Dictionary( "price", 15.25, "color", "red", "year", 1974,);   update.pump( new:=base.copy() );   new.pump(Void,fcn([(k,v)]){ println("%s\t%s".fmt(k,v)) });
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...
#Scheme
Scheme
  (import (scheme base) (scheme write) (srfi 1 lists) (only (srfi 13 strings) string-pad-right) (srfi 27 random-bits))   (define (analytical-function n) (define (factorial n) (fold * 1 (iota n 1))) ; (fold (lambda (i sum) (+ sum (/ (factorial n) (expt n ...
http://rosettacode.org/wiki/Averages/Simple_moving_average
Averages/Simple moving average
Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is a method for computing an avera...
#Tcl
Tcl
oo::class create SimpleMovingAverage { variable vals idx constructor {{period 3}} { set idx end-[expr {$period-1}] set vals {} } method val x { set vals [lrange [list {*}$vals $x] $idx end] expr {[tcl::mathop::+ {*}$vals]/double([llength $vals])} } }
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....
#Modula-2
Modula-2
MODULE AttractiveNumbers; FROM InOut IMPORT WriteCard, WriteLn;   CONST Max = 120;   VAR n, col: CARDINAL; Prime: ARRAY [1..Max] OF BOOLEAN;   PROCEDURE Sieve; VAR i, j: CARDINAL; BEGIN Prime[1] := FALSE; FOR i := 2 TO Max DO Prime[i] := TRUE; END;   FOR i := 2 TO Max DIV 2 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 ...
#PowerShell
PowerShell
  function Get-MeanTimeOfDay { [CmdletBinding()] [OutputType([timespan])] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [ValidatePattern("(?:2[0-3]|[01]?[0-9])[:.][0-5]?[0-9][:.][0-5]?[0-9]")] ...
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....
#Simula
Simula
CLASS AVL; BEGIN    ! AVL TREE ADAPTED FROM JULIENNE WALKER'S PRESENTATION AT ;  ! HTTP://ETERNALLYCONFUZZLED.COM/TUTS/DATASTRUCTURES/JSW_TUT_AVL.ASPX. ;  ! THIS PORT USES SIMILAR INDENTIFIER NAMES. ;    ! THE KEY INTERFACE MUST BE SUPPORTED BY DATA STORED IN THE AVL TREE. ; CLASS KEY; VIRTUAL: ...
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 ...
#PicoLisp
PicoLisp
(load "@lib/math.l")   (de meanAngle (Lst) (*/ (atan2 (sum '((A) (sin (*/ A pi 180.0))) Lst) (sum '((A) (cos (*/ A pi 180.0))) Lst) ) 180.0 pi ) )   (for L '((350.0 10.0) (90.0 180.0 270.0 360.0) (10.0 20.0 30.0)) (prinl "The mean angle of [" (glue ", " (mapcar round L '(...
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 ...
#PL.2FI
PL/I
averages: procedure options (main); /* 31 August 2012 */ declare b1(2) fixed initial (350, 10); declare b2(4) fixed initial (90, 180, 270, 360); declare b3(3) fixed initial (10, 20, 30);   put edit ( b1) (f(7)); put edit ( ' mean=', mean(b1) ) (a, f(7) ); put skip edit ( b3) (f(7)); p...
http://rosettacode.org/wiki/Averages/Mean_angle
Averages/Mean angle
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the ...
#PowerShell
PowerShell
  function Get-MeanAngle ([double[]]$Angles) { $x = ($Angles | ForEach-Object {[Math]::Cos($_ * [Math]::PI / 180)} | Measure-Object -Average).Average $y = ($Angles | ForEach-Object {[Math]::Sin($_ * [Math]::PI / 180)} | Measure-Object -Average).Average   [Math]::Atan2($y, $x) * 180 / [Math]::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 ...
#Groovy
Groovy
def median(Iterable col) { def s = col as SortedSet if (s == null) return null if (s.empty) return 0 def n = s.size() def m = n.intdiv(2) def l = s.collect { it } n%2 == 1 ? l[m] : (l[m] + l[m-1])/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...
#Liberty_BASIC
Liberty BASIC
for i = 1 to 10 a = a + i next ArithmeticMean = a/10   b = 1 for i = 1 to 10 b = b * i next GeometricMean = b ^ (1/10)   for i = 1 to 10 c = c + (1/i) next HarmonicMean = 10/c   print "ArithmeticMean: ";ArithmeticMean print "Geometric Mean: ";GeometricMean print "Harmonic Mean: ";HarmonicMean   if (Arithmet...
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" ...
#Rust
Rust
use std::{ cmp::min, convert::{TryFrom, TryInto}, fmt, ops::{Add, Mul, Neg}, str::FromStr, };   fn main() -> Result<(), &'static str> { let a = BalancedTernary::from_str("+-0++0+")?; let b = BalancedTernary::from(-436); let c = BalancedTernary::from_str("+-++-")?; println!("a = {} = ...
http://rosettacode.org/wiki/Babbage_problem
Babbage problem
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p....
#Scilab
Scilab
n=2; flag=%F while ~flag n = n+2; if pmodulo(n*n,1000000)==269696 then flag=%T; end end disp(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....
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local var integer: current is 0; begin while current ** 2 rem 1000000 <> 269696 do incr(current); end while; writeln("The square of " <& current <& " is " <& current ** 2); end func;
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...
#Scala
Scala
object Approximate extends App { val (ok, notOk, ε) = ("👌", "❌", 1e-18d)   private def approxEquals(value: Double, other: Double, epsilon: Double) = scala.math.abs(value - other) < epsilon   private def test(a: BigDecimal, b: BigDecimal, expected: Boolean): Unit = { val result = approxEquals(a.toDouble, ...
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...
#Sidef
Sidef
[ 100000000000000.01, 100000000000000.011, 100.01, 100.011, 10000000000000.001 / 10000.0, 1000000000.0000001000, 0.001, 0.0010000001, 0.000000000000000000000101, 0.0, sqrt(2) * sqrt(2), 2.0, -sqrt(2) * sqrt(2), -2.0, sqrt(-2) * sqrt(-2), -2.0, cbrt(3)**3, 3, cbrt(-3)**3, -3, ...
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) ...
#Elixir
Elixir
defmodule Balanced_brackets do def task do Enum.each(0..5, fn n -> brackets = generate(n) result = is_balanced(brackets) |> task_balanced IO.puts "#{brackets} is #{result}" end) end   defp generate( 0 ), do: [] defp generate( n ) do for _ <- 1..2*n, do: Enum.random ["[", "]"] end...
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,...
#Haskell
Haskell
  {-# LANGUAGE RecordWildCards #-}   import System.IO import Data.List (intercalate)   data Gecos = Gecos { fullname :: String , office :: String , extension :: String , homephone :: String , email :: String }   dat...
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...
#AWK
AWK
BEGIN { a["red"] = 0xff0000 a["green"] = 0x00ff00 a["blue"] = 0x0000ff for (i in a) { printf "%8s %06x\n", i, a[i] } # deleting a key/value delete a["red"] for (i in a) { print i } # check if a key exists print ( "red" in a ) # print 0 print ( "blue" in a ) # print 1 }
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#D
D
import std.stdio;   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; }   void main() { int maxDiv, count; writeln("The first 20 anti-primes are:"...
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
#Delphi
Delphi
defmodule AntiPrimes do def divcount(n) when is_integer(n), do: divcount(n, 1, 0)   def divcount(n, d, count) when d * d > n, do: count def divcount(n, d, count) do divs = case rem(n, d) do 0 -> case n - d * d do 0 -> 1 _ -> 2 end _ -> 0 end divcount(n, d + 1, count + divs) end   def ...
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...
#Perl
Perl
use strict; use 5.10.0;   use threads 'yield'; use threads::shared;   my @a :shared = (100) x 10; my $stop :shared = 0;   sub pick2 { my $i = int(rand(10)); my $j; $j = int(rand(10)) until $j != $i; ($i, $j) }   sub even { lock @a; my ($i, $j) = pick2; my $sum = $a[$i] + $a[$j]; $a[$i] = int($sum / 2); $a[$j] ...
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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Assert[var===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.
#MATLAB_.2F_Octave
MATLAB / Octave
assert(x == 42,'x = %d, not 42.',x);
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Metafont
Metafont
def assert(expr t) = if not (t): errmessage("assertion failed") fi enddef;