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/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.
#Oforth
Oforth
: testInteger(n, m) assert: [ n isInteger ] assert: [ n 42 == ]   System.Out "Assertions are ok, parameters are : " << n << ", " << m << cr ;
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.
#Delphi
Delphi
  // Declare the callback function procedure callback(const AInt:Integer); begin WriteLn(AInt); end;   const // Declare a static array myArray:Array[0..4] of Integer=(1,4,6,8,7); var // Declare interator variable i:Integer; begin // Iterate the array and apply callback for i:=0 to length(myArray)-1 do ...
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...
#PHP
PHP
<?php function mode($arr) { $count = array_count_values($arr); $best = max($count); return array_keys($count, $best); }   print_r(mode(array(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17))); print_r(mode(array(1, 1, 2, 4, 4))); ?>
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 ...
#Erlang
Erlang
  -module(assoc). -compile([export_all]).   test_create() -> D = dict:new(), D1 = dict:store(foo,1,D), D2 = dict:store(bar,2,D1), print_vals(D2).   print_vals(D) -> lists:foreach(fun (K) -> io:format("~p: ~b~n",[K,dict:fetch(K,D)]) end, dict:fetch_keys(...
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...
#REXX
REXX
/*REXX pgm filters a signal with a order3 lowpass Butterworth, direct form II transposed*/ @a= '1 -2.77555756e-16 3.33333333e-1 -1.85037171e-17' /*filter coefficients*/ @b= 0.16666667 0.5 0.5 0.16666667 /* " " */ @s= '-0.917843918645 0.141984778794 1.205369...
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...
#Ruby
Ruby
def filter(a,b,signal) result = Array.new(signal.length(), 0.0) for i in 0..signal.length()-1 do tmp = 0.0 for j in 0 .. b.length()-1 do if i - j < 0 then next end tmp += b[j] * signal[i - j] end for j in 1 .. a.length()-1 do if i - j < 0 then ...
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...
#F.23
F#
let avg (a:float) (v:float) n = a + (1. / ((float n) + 1.)) * (v - a)   let mean_series list = let a, _ = List.fold_left (fun (a, n) h -> avg a (float h) n, n + 1) (0., 0) list in 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...
#Factor
Factor
USING: math math.statistics ;   : arithmetic-mean ( seq -- n ) [ 0 ] [ mean ] if-empty ;
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...
#VBScript
VBScript
  Const MAX = 20 Const ITER = 100000   Function expected(n) Dim sum ni=n For i = 1 To n sum = sum + fact(n) / ni / fact(n-i) ni=ni*n Next expected = sum End Function   Function test(n ) Dim coun,x,bits For i = 1 To ITER x = 1 bits = 0 Do While Not bits And x count = count + 1 ...
http://rosettacode.org/wiki/Average_loop_length
Average loop length
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t...
#Vlang
Vlang
import rand import math   const nmax = 20   fn main() { println(" N average analytical (error)") println("=== ========= ============ =========") for n := 1; n <= nmax; n++ { a := avg(n) b := ana(n) println("${n:3} ${a:9.4f} ${b:12.4f} (${math.abs(a-b)/b*100:6.2f}%)" ) ...
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...
#VBScript
VBScript
data = "1,2,3,4,5,5,4,3,2,1" token = Split(data,",") stream = "" WScript.StdOut.WriteLine "Number" & vbTab & "SMA3" & vbTab & "SMA5" For j = LBound(token) To UBound(token) If Len(stream) = 0 Then stream = token(j) Else stream = stream & "," & token(j) End If WScript.StdOut.WriteLine token(j) & vbTab & Round(SMA...
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....
#Perl
Perl
use ntheory <is_prime factor>;   is_prime +factor $_ and print "$_ " for 1..120;
http://rosettacode.org/wiki/Attractive_numbers
Attractive numbers
A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show sequence items up to   120....
#Phix
Phix
function attractive(integer lim) sequence s = {} for i=1 to lim do integer n = length(prime_factors(i,true)) if is_prime(n) then s &= i end if end for return s end function sequence s = attractive(120) printf(1,"There are %d attractive numbers up to and including %d:\n",{length(s),120}) ...
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 ...
#Ruby
Ruby
def time2deg(t) raise "invalid time" unless m = t.match(/^(\d\d):(\d\d):(\d\d)$/) hh,mm,ss = m[1..3].map {|e| e.to_i} raise "invalid time" unless (0..23).include? hh and (0..59).include? mm and (0..59).include? ss (hh*3600 + mm*60 + ss) * 360 / 86400.0...
http://rosettacode.org/wiki/Averages/Mean_angle
Averages/Mean angle
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the ...
#REXX
REXX
Note that the second set of angles: 90 180 270 360 is the same as: 90 180 -90 0 and: -270 -180 -90 -360 and other combinations.
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 ...
#Ring
Ring
  # Project : Averages/Mean angle   load "stdlib.ring" decimals(6) pi = 3.1415926535897 angles = [350,10] see meanangle(angles, len(angles)) + nl angles = [90,180,270,360] see meanangle(angles, len(angles)) + nl angles = [10,20,30] see meanangle(angles, len(angles)) + nl   func meanangle(angles, n) sumsin = 0 ...
http://rosettacode.org/wiki/Averages/Mean_angle
Averages/Mean angle
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the ...
#Ruby
Ruby
require 'complex' # Superfluous in Ruby >= 2.0; complex is added to core.   def deg2rad(d) d * Math::PI / 180 end   def rad2deg(r) r * 180 / Math::PI end   def mean_angle(deg) rad2deg((deg.inject(0) {|z, d| z + Complex.polar(1, deg2rad(d))} / deg.length).arg) end   [[350, 10], [90, 180, 270, 360], [10, 20, 30]].e...
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 ...
#Java
Java
// Note: this function modifies the input list public static double median(List<Double> list) { Collections.sort(list); return (list.get(list.size() / 2) + list.get((list.size() - 1) / 2)) / 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 ...
#JavaScript
JavaScript
function median(ary) { if (ary.length == 0) return null; ary.sort(function (a,b){return a - b}) var mid = Math.floor(ary.length / 2); if ((ary.length % 2) == 1) // length is odd return ary[mid]; else return (ary[mid - 1] + ary[mid]) / 2; }   median([]); // null median([5,...
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...
#Maple
Maple
x := [ seq( 1 .. 10 ) ]; Means := proc( x ) uses Statistics; return Mean( x ), GeometricMean( x ), HarmonicMean( x ); end proc: Arithmeticmean, Geometricmean, Harmonicmean := Means( x );   is( Arithmeticmean >= Geometricmean and Geometricmean >= Harmonicmean );  
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" ...
#Wren
Wren
import "/big" for BigInt import "/trait" for Comparable   class BTernary is Comparable { toBT_(v) { if (v < BigInt.zero) return flip_(toBT_(-v)) if (v == BigInt.zero) return "" var rem = mod3_(v) return (rem == BigInt.zero) ? toBT_(v/BigInt.three) + "0" : (rem == BigIn...
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....
#SQL
SQL
  /* This code is an implementation of Babbage Problem in SQL ORACLE 19c p_ziel -- the substring to search for, which can start with leading zeros p_max -- upper bound of the cycle v_max -- safe determination of the upper bound of the cycle v_start -- safe starting point */ WITH FUNCTION babbage(p_ziel IN varch...
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) ...
#F.23
F#
let isBalanced str = let rec loop count = function | ']'::_ when count = 0 -> false | '['::xs -> loop (count+1) xs | ']'::xs -> loop (count-1) xs | [] -> count = 0 | _::_ -> false   str |> Seq.toList |> loop 0     let shuffle a...
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,...
#Julia
Julia
  using SHA # security instincts say do not write bare passwords to a shared file even in toy code :)   mutable struct Personnel fullname::String office::String extension::String homephone::String email::String Personnel(ful,off,ext,hom,ema) = new(ful,off,ext,hom,ema) end   mutable struct Passw...
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,...
#Kotlin
Kotlin
// Version 1.2.41   import java.io.File   class Record( val account: String, val password: String, val uid: Int, val gid: Int, val gecos: List<String>, val directory: String, val shell: String ){ override fun toString() = "$account:$password:$uid:$gid:${gecos.joinToString(",")}:$...
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...
#Batch_File
Batch File
::assocarrays.cmd @echo off setlocal ENABLEDELAYEDEXPANSION set array.dog=1 set array.cat=2 set array.wolf=3 set array.cow=4 for %%i in (dog cat wolf cow) do call :showit array.%%i !array.%%i! set c=-27 call :mkarray sicko flu 5 measles 6 mumps 7 bromodrosis 8 for %%i in (flu measles mumps bromodrosis) do call :showit ...
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
#Fortran
Fortran
  program anti_primes use iso_fortran_env, only: output_unit implicit none   integer :: n, d, maxDiv, pCount   write(output_unit,*) "The first 20 anti-primes are:" n = 1 maxDiv = 0 pCount = 0 do if (pCount >= 20) exit   d = countDivisors(n) if (d > maxDiv) then ...
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
#FreeBASIC
FreeBASIC
  ' convertido desde Ada Declare Function count_divisors(n As Integer) As Integer   Dim As Integer max_divisors, divisors, results(1 To 20), candidate, j candidate = 1   Function count_divisors(n As Integer) As Integer Dim As Integer i, count = 1 For i = 1 To n/2 If (n Mod i) = 0 Then count += 1 Nex...
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...
#Racket
Racket
#lang racket   (struct bucket (value [lock #:auto]) #:auto-value #f #:mutable #:transparent)   (define *buckets* (build-vector 10 (λ (i) (bucket 100))))   (define (show-buckets) (let* ([values (for/list ([b *buckets*]) (bucket-value b))] [total (apply + values)]) (append values (list '- total))))  ...
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...
#Raku
Raku
#| A collection of non-negative integers, with atomic operations. class BucketStore {   has $.elems is required; has @!buckets = ^1024 .pick xx $!elems; has $lock = Lock.new;   #| Returns an array with the contents of all buckets. method buckets { $lock.protect: { [@!buckets] } }   #| Transfers $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.
#Ol
Ol
  (define i 24)   (assert i ===> 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.
#Oz
Oz
declare proc {PrintNumber N} N=42 %% assert {Show N} end in {PrintNumber 42} %% ok {PrintNumber 11} %% throws
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.
#PARI.2FGP
PARI/GP
#include <assert.h> #include <pari/pari.h>   void test() { GEN a; // ... input or change a here   assert(equalis(a, 42)); /* Aborts program if a is not 42, unless the NDEBUG macro was defined */ }
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.
#Dyalect
Dyalect
func Array.Select(pred) { let ys = [] for x in this when pred(x) { ys.Add(x) } return ys }   var arr = [1, 2, 3, 4, 5] var squares = arr.Select(x => x * x)   print(squares)
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.
#D.C3.A9j.C3.A0_Vu
Déjà Vu
!. map @++ [ 1 4 8 ]   #implemented roughly like this: #map f lst: # ] # for i in lst: # f i # [
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...
#PicoLisp
PicoLisp
(de modes (Lst) (let A NIL (for X Lst (accu 'A X 1) ) (mapcar car (maxi cdar (by cdr group A) ) ) ) )
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...
#PL.2FI
PL/I
av: procedure options (main); /* 28 October 2013 */ declare x(10) fixed binary static initial (1, 4, 2, 6, 2, 5, 6, 2, 4, 2); declare f(32767) fixed binary; declare (j, n, max, value) fixed binary; declare i fixed;   n = hbound(x,1);   do i = 1 to n; j = x(i); f(j) = f(j) + 1; end; ...
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#F.23
F#
  let myMap = [ ("Hello", 1); ("World", 2); ("!", 3) ]   for k, v in myMap do printfn "%s -> %d" k 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 ...
#Factor
Factor
H{ { "hi" "there" } { "a" "b" } } [ ": " glue print ] assoc-each
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...
#Rust
Rust
use std::cmp::Ordering;   struct IIRFilter<'f>(&'f [f32], &'f [f32]);   impl<'f> IIRFilter<'f> { pub fn with_coefficients(a: &'f [f32], b: &'f [f32]) -> IIRFilter<'f> { IIRFilter(a, b) }   // Performs the calculation as an iterator chain. pub fn apply<I: Iterator<Item = &'f f32> + 'f>( &...
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...
#Scala
Scala
object ButterworthFilter extends App { private def filter(a: Vector[Double], b: Vector[Double], signal: Vector[Double]): Vector[Double] = {   @scala.annotation.tailrec def outer(i: Int, acc: Vector[Double]): Vector[Double] = { if (i >= signal.length) acc e...
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...
#Fantom
Fantom
  class Main { static Float average (Float[] nums) { if (nums.size == 0) return 0.0f Float sum := 0f nums.each |num| { sum += num } return sum / nums.size.toFloat }   public static Void main () { [[,], [1f], [1f,2f,3f,4f]].each |Float[] i| { echo ("Average of $i is: " + average(i...
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...
#Fish
Fish
!vl0=?vl1=?vl&! v< +<>0n; >n; >l1)?^&,n;
http://rosettacode.org/wiki/Average_loop_length
Average loop length
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t...
#Wren
Wren
import "random" for Random import "/fmt" for Fmt   var nmax = 20 var rand = Random.new()   var avg = Fn.new { |n| var tests = 1e4 var sum = 0 for (t in 0...tests) { var v = List.filled(nmax, false) var x = 0 while (!v[x]) { v[x] = true sum = sum + 1 ...
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...
#Vlang
Vlang
fn sma(period int) fn(f64) f64 { mut i := int(0) mut sum := f64(0) mut storage := []f64{len: 0, cap:period}   return fn[mut storage, mut sum, mut i, period](input f64) f64 { if storage.len < period { sum += input storage << input }   sum += input - storage...
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....
#PHP
PHP
<?php function isPrime ($x) { if ($x < 2) return false; if ($x < 4) return true; if ($x % 2 == 0) return false; for ($d = 3; $d < sqrt($x); $d++) { if ($x % $d == 0) return false; } return true; }   function countFacs ($n) { $count = 0; $divisor = 1; if ($n < 2) return 0;...
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 ...
#Run_BASIC
Run BASIC
global pi pi = acs(-1)   Print "Average of:" for i = 1 to 4 read t$ print t$ a = time2angle(t$) ss = ss+sin(a) sc = sc+cos(a) next a = atan2(ss,sc) if a < 0 then a = a + 2 * pi print "is ";angle2time$(a) end data "23:00:17", "23:40:20", "00:12:45", "00:17:19"   function nn$(n) nn$ = right$("0"...
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 ...
#Rust
Rust
  use std::f64::consts::PI;   #[derive(Debug, PartialEq, Eq)] struct Time { h: u8, m: u8, s: u8, }   impl Time { /// Create a Time from equivalent radian measure fn from_radians(mut rads: f64) -> Time { rads %= 2.0 * PI; if rads < 0.0 { rads += 2.0 * 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 ...
#Rust
Rust
  use std::f64; // the macro is from // http://stackoverflow.com/questions/30856285/assert-eq-with-floating- // point-numbers-and-delta fn mean_angle(angles: &[f64]) -> f64 { let length: f64 = angles.len() as f64; let cos_mean: f64 = angles.iter().fold(0.0, |sum, i| sum + i.to_radians().cos()) / length; let...
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 ...
#Scala
Scala
trait MeanAnglesComputation { import scala.math.{Pi, atan2, cos, sin}   def meanAngle(angles: List[Double], convFactor: Double = 180.0 / Pi) = { val sums = angles.foldLeft((.0, .0))((r, c) => { val rads = c / convFactor (r._1 + sin(rads), r._2 + cos(rads)) }) val result = atan2(sums._1, sums...
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#jq
jq
def median: length as $length | sort as $s | if $length == 0 then null else ($length / 2 | floor) as $l2 | if ($length % 2) == 0 then ($s[$l2 - 1] + $s[$l2]) / 2 else $s[$l2] end 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 ...
#Julia
Julia
using Statistics function median2(n) s = sort(n) len = length(n) if len % 2 == 0 return (s[floor(Int, len / 2) + 1] + s[floor(Int, len / 2)]) / 2 else return s[floor(Int, len / 2) + 1] end end   a = [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2] b = [4.1, 7.2, 1.7, 9.3, 4.4, 3.2]   @show a b median2(a) median(a) median2...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Print["{Arithmetic Mean, Geometric Mean, Harmonic Mean} = ", N@Through[{Mean, GeometricMean, HarmonicMean}[Range@10]]]
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....
#Swift
Swift
import Swift   for i in 2...Int.max { if i * i % 1000000 == 269696 { print(i, "is the smallest number that ends with 269696") break } }
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) ...
#Factor
Factor
USING: io formatting locals kernel math sequences unicode.case ; IN: balanced-brackets   :: balanced ( str -- ) 0 :> counter! 1 :> ok! str [ dup length 0 > ] [ 1 cut swap "[" = [ counter 1 + counter! ] [ counter 1 - counter! ] if counter 0 < [ 0 ok! ] when ] while drop ok 0 = [ ...
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file
Append a record to the end of a text file
Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. This feature is most useful in the case of log files,...
#Lua
Lua
function append(tbl,filename) local file,err = io.open(filename, "a") if err then return err end   file:write(tbl.account..":") file:write(tbl.password..":") file:write(tbl.uid..":") file:write(tbl.gid..":")   for i,v in ipairs(tbl.gecos) do if i>1 then file:write(",") ...
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...
#BBC_BASIC
BBC BASIC
REM Store some values with their keys: PROCputdict(mydict$, "FF0000", "red") PROCputdict(mydict$, "00FF00", "green") PROCputdict(mydict$, "0000FF", "blue")   REM Retrieve some values using their keys: PRINT FNgetdict(mydict$, "green") PRINT FNgetdict(mydict$, "red") END  ...
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
#Go
Go
package main   import "fmt"   func countDivisors(n int) int { if n < 2 { return 1 } count := 2 // 1 and n for i := 2; i <= n/2; i++ { if n%i == 0 { count++ } } return count }   func main() { fmt.Println("The first 20 anti-primes are:") maxDiv := 0 ...
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
#Groovy
Groovy
def getAntiPrimes(def limit = 10) { def antiPrimes = [] def candidate = 1L def maxFactors = 0   while (antiPrimes.size() < limit) { def factors = factorize(candidate) if (factors.size() > maxFactors) { maxFactors = factors.size() antiPrimes << candidate } ...
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...
#Ring
Ring
  # Project : Atomic updates   bucket = list(10) f2 = 0 for i = 1 to 10 bucket[i] = floor(random(9)*10) next   a = display("display:") see nl a = flatten(a) see "" + a + nl a = display("flatten:") see nl a = transfer(3,5) see a + nl see "19 from 3 to 5: " a = display(a) see nl   func display(a) displ...
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...
#Ruby
Ruby
require 'thread'   # A collection of buckets, filled with random non-negative integers. # There are atomic operations to look at the bucket contents, and # to move amounts between buckets. class BucketStore   # Creates a BucketStore with +nbuckets+ buckets. Fills each bucket # with a random non-negative integer. ...
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.
#Pascal
Pascal
print "Give me a number: "; chomp(my $a = <>);   $a == 42 or die "Error message\n";   # Alternatives die "Error message\n" unless $a == 42; die "Error message\n" if not $a == 42; die "Error message\n" if $a != 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.
#Perl
Perl
print "Give me a number: "; chomp(my $a = <>);   $a == 42 or die "Error message\n";   # Alternatives die "Error message\n" unless $a == 42; die "Error message\n" if not $a == 42; die "Error message\n" if $a != 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.
#E
E
def array := [1,2,3,4,5] def square(value) { return value * value }
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.
#EchoLisp
EchoLisp
  (vector-map sqrt #(0 4 16 49)) → #( 0 2 4 7) ;; or (map exp #(0 1 2)) → #( 1 2.718281828459045 7.38905609893065) ;; or (for/vector ([elem #(2 3 4)] [i (in-naturals)]) (printf "v[%d] = %a" i elem) (* elem elem)) v[0] = 2 v[1] = 3 v[2] = 4 → #( 4 9 16)  
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...
#PowerShell
PowerShell
$data = @(1,1,1,2,3,4,5,5,6,7,7,7) $groups = $data | group-object | sort-object count -Descending $groups | ? {$_.Count -eq $groups[0].Count}
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 ...
#Fantom
Fantom
  class Main { public static Void main () { Int:Str map := [1:"alpha", 2:"beta", 3:"gamma"]   map.keys.each |Int key| { echo ("Key is: $key") }   map.vals.each |Str value| { echo ("Value is: $value") }   map.each |Str value, Int key| { echo ("Key $key maps to $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 ...
#Forth
Forth
include ffl/hct.fs include ffl/hci.fs   \ Create hashtable and iterator in dictionary 10 hct-create htable htable hci-create hiter   \ Insert entries 1 s" hello" htable hct-insert 2 s" world" htable hct-insert 3 s" !" htable hct-insert   : iterate hiter hci-first BEGIN WHILE ." key = " hiter hci-key t...
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...
#Sidef
Sidef
func TDF_II_filter(signal, a, b) { var out = [0]*signal.len for i in ^signal { var this = 0 for j in ^b { i-j >= 0 && (this += b[j]*signal[i-j]) } for j in ^a { i-j >= 0 && (this -= a[j]* out[i-j]) } out[i] = this/a[0] } return out }   var signal = [ -0.917843918645...
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...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Function Filter(a As Double(), b As Double(), signal As Double()) As Double() Dim result(signal.Length - 1) As Double For i = 1 To signal.Length Dim tmp = 0.0 For j = 1 To b.Length If i - j < 0 Then Continue For ...
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#Forth
Forth
: fmean ( addr n -- f ) 0e dup 0= if 2drop exit then tuck floats bounds do i f@ f+ 1 floats +loop 0 d>f f/ ;   create test 3e f, 1e f, 4e f, 1e f, 5e f, 9e f, test 6 fmean f. \ 3.83333333333333
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...
#Fortran
Fortran
real, target, dimension(100) :: a = (/ (i, i=1, 100) /) real, dimension(5,20) :: b = reshape( a, (/ 5,20 /) ) real, pointer, dimension(:) :: p => a(2:1) ! pointer to zero-length array real :: mean, zmean, bmean real, dimension(20) :: colmeans real, dimension(5) :: rowmeans   mean = sum(a)/size(a) !...
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...
#zkl
zkl
const N=20;   (" N average analytical (error)").println(); ("=== ========= ============ =========").println(); foreach n in ([1..N]){ a := avg(n); b := ana(n); "%3d  %9.4f  %12.4f (%6.2f%%)".fmt( n, a, b, ((a-b)/b*100)).println(); }   fcn f(n){ (0).random(n) }   fcn avg(n){ tests :=...
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...
#Wren
Wren
import "/fmt" for Fmt   var sma = Fn.new { |period| var i = 0 var sum = 0 var storage = [] return Fn.new { |input| if (storage.count < period) { sum = sum + input storage.add(input) } sum = sum + input - storage[i] storage[i] = input i = (i...
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....
#PL.2FI
PL/I
attractive: procedure options(main);  %replace MAX by 120; declare prime(1:MAX) bit(1);   sieve: procedure; declare (i, j, sqm) fixed; prime(1) = 0; do i=2 to MAX; prime(i) = '1'b; end;   sqm = sqrt(MAX); do i=2 to sqm; if prime(i) then do j=i*2 to MAX by i...
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 ...
#Scala
Scala
import java.time.LocalTime import scala.compat.Platform   trait MeanAnglesComputation { import scala.math.{Pi, atan2, cos, sin}   def meanAngle(angles: List[Double], convFactor: Double = 180.0 / Pi) = { val sums = angles.foldLeft((.0, .0))((r, c) => { val rads = c / convFactor (r._1 + sin(rads), r._...
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 ...
#Scheme
Scheme
  (import (srfi 1 lists)) ;; use 'fold' from library   (define (average l) (/ (fold + 0 l) (length l)))   (define pi 3.14159265358979323846264338327950288419716939937510582097)   (define (radians a) (* pi 1/180 a))   (define (degrees a) (* 180 (/ 1 pi) a))   (define (mean-angle angles) (let* ((angles (map rad...
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 ...
#K
K
  med:{a:x@<x; i:(#a)%2; :[(#a)!2; a@i; {(+/x)%#x} a@i,i-1]} v:10*6 _draw 0 v 5.961475 2.025856 7.262835 1.814272 2.281911 4.854716 med[v] 3.568313 med[1_ v] 2.281911  
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 ...
#Kotlin
Kotlin
fun median(l: List<Double>) = l.sorted().let { (it[it.size / 2] + it[(it.size - 1) / 2]) / 2 }   fun main(args: Array<String>) { median(listOf(5.0, 3.0, 4.0)).let { println(it) } // 4 median(listOf(5.0, 4.0, 2.0, 3.0)).let { println(it) } // 3.5 median(listOf(3.0, 4.0, 1.0, -8.4, 7.2, 4.0, 1.0, 1.2)).let ...
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...
#MATLAB
MATLAB
function [A,G,H] = pythagoreanMeans(list)   A = mean(list); G = geomean(list); H = harmmean(list);   end
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....
#Tcl
Tcl
for {set i 1} {![string match *269696 [expr $i*$i]]} {incr i} {} puts "$i squared is [expr $i*$i]"
http://rosettacode.org/wiki/Babbage_problem
Babbage problem
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p....
#TI-83_BASIC
TI-83 BASIC
536→N
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) ...
#Fantom
Fantom
  class Main { static Bool matchingBrackets (Str[] brackets) { Int opened := 0 Int i := 0 while (i < brackets.size) { if (brackets[i] == "[") opened += 1 else opened -= 1 if (opened < 0) return false i += 1 } return true }   public static Void main...
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,...
#M2000_Interpreter
M2000 Interpreter
Module TestThis { Class passwd { account$, password$ UID, GID group GECOS { fullname$,office$,extension$,homephone$,email$ function Line$() { =format$("{0},{1} {2},{3},{4}", .fullname$,.office$,.extension$,.homephone$,.email$) } } directory$, shell$ Function Line$() { =format$("{0}:{1}:{2}:...
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,...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
data = <|"account" -> "xyz", "password" -> "x", "UID" -> 1003, "GID" -> 1000, "fullname" -> "X Yz", "office" -> "Room 1003", "extension" -> "(234)555-8913", "homephone" -> "(234)555-0033", "email" -> "xyz@rosettacode.org", "directory" -> "/home/xyz", "shell" -> "/bin/bash"|>; asString[data_] := Strin...
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...
#Bracmat
Bracmat
new$hash:?myhash & (myhash..insert)$(title."Some title") & (myhash..insert)$(formula.a+b+x^7) & (myhash..insert)$(fruit.apples oranges kiwis) & (myhash..insert)$(meat.) & (myhash..insert)$(fruit.melons bananas) & out$(myhash..find)$fruit & (myhash..remove)$formula & (myhash..insert)$(formula.x^2+y^2) & out$(myhash..f...
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#GW-BASIC
GW-BASIC
10 C = -999 20 N = N + 1 30 GOSUB 60 40 IF T = 20 THEN END 50 GOTO 20 60 D = 0 70 FOR F = 1 TO INT(N/2) 80 IF N MOD F = 0 THEN D = D + 1 90 NEXT F 100 IF D > C THEN GOSUB 120 110 RETURN 120 C = D 130 T = T + 1 140 PRINT N 150 RETURN
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
#Haskell
Haskell
import Data.List (find, group) import Data.Maybe (fromJust)   firstPrimeFactor :: Int -> Int firstPrimeFactor n = head $ filter ((0 ==) . mod n) [2 .. n]   allPrimeFactors :: Int -> [Int] allPrimeFactors 1 = [] allPrimeFactors n = let first = firstPrimeFactor n in first : allPrimeFactors (n `div` first)   factorCou...
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...
#Run_BASIC
Run BASIC
DIM bucket(10) FOR i = 1 TO 10 : bucket(i) = int(RND(0)*100) : NEXT   a = display(" Display:") ' show original array a = flatten(a) ' flatten the array a = display(" Flatten:") ' show flattened array a = transfer(3,5) ' transfer some amount from 3 to 5 a = display(a;" from 3 to 5:") ' Show transfer array...
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...
#Rust
Rust
extern crate rand;   use std::sync::{Arc, Mutex}; use std::thread; use std::cmp; use std::time::Duration;   use rand::Rng; use rand::distributions::{IndependentSample, Range};   trait Buckets { fn equalize<R:Rng>(&mut self, rng: &mut R); fn randomize<R:Rng>(&mut self, rng: &mut R); fn print_state(&self); } ...
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.
#Phix
Phix
type int42(object i) return i=42 end type int42 i i = 41 -- type-check failure (desktop/Phix only)
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.
#PHP
PHP
<?php $a = 5 #...input or change $a here assert($a == 42) # when $a is not 42, take appropriate actions, # which is set by assert_options() ?>
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.
#Picat
Picat
go =>    %  % Test predicates  % S = "ablewasiereisawelba", assert("test1",$is_palindrome(S)), assert_failure("test2",$not is_palindrome(S)),   assert("test3",$member(1,1..10)), assert_failure("test4",$member(1,1..10)), % bad test nl,    %  % Test functions  % assert("test5",$2+2,4), assert_fa...
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.
#Efene
Efene
square = fn (N) { N * N }   # list comprehension squares1 = fn (Numbers) { [square(N) for N in Numbers] }   # functional form squares2a = fn (Numbers) { lists.map(fn square:1, Numbers) }   # functional form with lambda squares2b = fn (Numbers) { lists.map(fn (N) { N * N }, Numbers) }   # no need for a f...
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...
#PureBasic
PureBasic
Procedure mean(Array InArray(1))   Structure MyMean Value.i Cnt.i EndStructure   Protected i, max, found Protected NewList MyDatas.MyMean()   Repeat found=#False ForEach MyDatas() If InArray(i)=MyDatas()\Value MyDatas()\Cnt+1 found=#True Break EndIf Ne...
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 ...
#FreeBASIC
FreeBASIC
#include"assoc.bas"   function get_dict_data_string( d as dicitem ) as string select case d.datatype case BOOL if d.value.bool then return "true" else return "false" case INTEG return str(d.value.integ) case STRNG return """"+d.value.strng+"""" cas...
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...
#Vlang
Vlang
struct Filter { b []f64 a []f64 }   fn (f Filter) filter(inp []f64) []f64 { mut out := []f64{len: inp.len} s := 1.0 / f.a[0] for i in 0..inp.len { mut tmp := 0.0 mut b := f.b if i+1 < b.len { b = b[..i+1] } for j, bj in b { tmp += bj * ...
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...
#Wren
Wren
import "/fmt" for Fmt   var filter = Fn.new { |a, b, signal| var result = List.filled(signal.count, 0) for (i in 0...signal.count) { var tmp = 0 for (j in 0...b.count) { if (i - j < 0) continue tmp = tmp + b[j] * signal[i - j] } for (j in 1...a.count) { ...
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...
#FreeBASIC
FreeBASIC
  ' FB 1.05.0 Win64   Function Mean(array() As Double) As Double Dim length As Integer = Ubound(array) - Lbound(array) + 1 If length = 0 Then Return 0.0/0.0 'NaN End If Dim As Double sum = 0.0 For i As Integer = LBound(array) To UBound(array) sum += array(i) Next Return sum/length End Function   F...
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...
#zkl
zkl
fcn SMA(P){ fcn(n,ns,P){ sz:=ns.append(n.toFloat()).len(); if(P>sz) return(0.0); if(P<sz) ns.del(0); ns.sum(0.0)/P; }.fp1(List.createLong(P+1),P) // pre-allocate a list of length P+1 }