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/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.2FM | PL/M | 100H:
BDOS: PROCEDURE (F, ARG); DECLARE F BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PUT$CHAR: PROCEDURE (CH); DECLARE CH BYTE; CALL BDOS(2,CH); END PUT$CHAR;
DECLARE MAXIMUM LITERALLY '120';
PRINT4: PROCEDURE (N);
DECLARE (N, MAGN, Z) BYTE;
CALL PUT$CHAR(' ');
MAGN... |
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 ... | #Scheme | Scheme |
(import (scheme base)
(scheme inexact)
(scheme read)
(scheme write)
(srfi 1)) ; for fold
;; functions copied from "Averages/Mean angle" task
(define (average l)
(/ (fold + 0 l) (length l)))
(define pi 3.14159265358979323846264338327950288419716939937510582097)
(define ... |
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 ... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
include "math.s7i";
include "complex.s7i";
const func float: deg2rad (in float: degree) is
return degree * PI / 180.0;
const func float: rad2deg (in float: rad) is
return rad * 180.0 / PI;
const func float: meanAngle (in array float: degrees) is func
resu... |
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 ... | #Sidef | Sidef | func mean_angle(angles) {
atan2(
Math.avg(angles.map{ .deg2rad.sin }...),
Math.avg(angles.map{ .deg2rad.cos }...),
) -> rad2deg
}
[[350,10], [90,180,270,360], [10,20,30]].each { |angles|
say "The mean angle of #{angles.dump} is: #{ '%.2f' % mean_angle(angles)} degrees"
} |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches ... | #Lasso | Lasso | define median_ext(a::array) => {
#a->sort
if(#a->size % 2) => {
// odd numbered element array, pick middle
return #a->get(#a->size / 2 + 1)
else
// even number elements in array
return (#a->get(#a->size / 2) + #a->get(#a->size / 2 + 1)) / 2.0
}
}
median_ext(array(3,2,7,6)) // 4.5
median_ext(array(3,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 ... | #Liberty_BASIC | Liberty BASIC |
dim a( 100), b( 100) ' assumes we will not have vectors of more terms...
a$ ="4.1,5.6,7.2,1.7,9.3,4.4,3.2"
print "Median is "; median( a$) ' 4.4 7 terms
print
a$ ="4.1,7.2,1.7,9.3,4.4,3.2"
print "Median is "; median( a$) ' 4.25 6 terms
print
a$ ="4.1,4,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... | #Maxima | Maxima | /* built-in */
L: makelist(i, i, 1, 10)$
mean(L), numer; /* 5.5 */
geometric_mean(L), numer; /* 4.528728688116765 */
harmonic_mean(L), numer; /* 3.414171521474055 */ |
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.... | #Transd | Transd | #lang transd
MainModule : {
rem: 269696,
_start: (lambda
(with n (to-Int (sqrt rem))
(while (neq (mod (pow n 2) 1000000) rem) (+= n 1))
(lout 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.... | #UNIX_Shell | UNIX Shell | # Program to determine the smallest positive integer whose square
# has a decimal representation ending in the digits 269,696.
# Start with the smallest positive integer of them all
let trial_value=1
# Compute the remainder when the square of the current trial value is divided
# by 1,000,000.␣
while (( trial_value ... |
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) ... | #Forth | Forth | include lib/choose.4th ( n1 -- n2)
include lib/ctos.4th ( n -- a 1)
10 constant /[] \ maximum number of brackets
/[] string [] \ string with brackets
\ create string with brackets
: make[] ... |
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,... | #MATLAB_.2F_Octave | MATLAB / Octave | DS{1}.account='jsmith';
DS{1}.password='x';
DS{1}.UID=1001;
DS{1}.GID=1000;
DS{1}.fullname='Joe Smith';
DS{1}.office='Room 1007';
DS{1}.extension='(234)555-8917';
DS{1}.homephone='(234)555-0077';
DS{1}.email='jsmith@rosettacode.org';
DS{1}.directory='/home/jsmith';
DS{1}.shell='/bin/bash';
DS{... |
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... | #Brat | Brat | h = [:] #Empty hash
h[:a] = 1 #Assign value
h[:b] = [1 2 3] #Assign another value
h2 = [a: 1, b: [1 2 3], 10 : "ten"] #Initialized hash
h2[:b][2] #Returns 3 |
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
| #J | J |
NB. factor count is the product of the incremented powers of prime factors
factor_count =: [: */ [: >: _&q:
NB. N are the integers 1 to 10000
NB. FC are the corresponding factor counts
FC =: factor_count&> N=: >: i. 10000
NB. take from the integers N{~
NB. the indexes of truth I.
NB. the... |
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
| #Java | Java | public class Antiprime {
static 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;
}
public static void main(String[] args) {
int maxDiv = 0, count =... |
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... | #Scala | Scala |
object AtomicUpdates {
class Buckets(ns: Int*) {
import scala.actors.Actor._
val buckets = ns.toArray
case class Get(index: Int)
case class Transfer(fromIndex: Int, toIndex: Int, amount: Int)
case object GetAll
val handler = actor {
loop {
react {
case Get(i... |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #PicoLisp | PicoLisp | ...
~(assert (= N 42)) # Exists only in debug mode
... |
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.
| #PL.2FI | PL/I |
/* PL/I does not have an assert function as such, */
/* but it is something that can be implemented in */
/* any of several ways. A straight-forward way */
/* raises a user-defined interrupt. */
on condition (assert_failure) snap
put skip list ('Assert failure');
....
if a ^= b then signal condition(assert_fa... |
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.
| #Prolog | Prolog |
test(A):-
assertion(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.
| #PureBasic | PureBasic | Macro Assert(TEST,MSG="Assert: ")
CompilerIf #PB_Compiler_Debugger
If Not (TEST)
Debug MSG+" Line="+Str(#PB_Compiler_Line)+" in "+#PB_Compiler_File
CallDebugger
EndIf
CompilerEndIf
EndMacro |
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.
| #EGL | EGL | delegate callback( i int ) returns( int ) end
program ApplyCallbackToArray
function main()
values int[] = [ 1, 2, 3, 4, 5 ];
func callback = square;
for ( i int to values.getSize() )
values[ i ] = func( values[ i ] );
end
for ( i int to values.getSize() )
SysLib.writeStdout( values[ i ] );
end
... |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Elena | Elena | import system'routines;
PrintSecondPower(n){ console.writeLine(n * n) }
public program()
{
new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}.forEach:PrintSecondPower
} |
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... | #Python | Python | >>> from collections import defaultdict
>>> def modes(values):
count = defaultdict(int)
for v in values:
count[v] +=1
best = max(count.values())
return [k for k,v in count.items() if v == best]
>>> modes([1,3,6,6,6,6,7,7,12,12,17])
[6]
>>> modes((1,1,2,4,4))
[1, 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 ... | #Free_Pascal | Free Pascal | program AssociativeArrayIteration;
{$mode delphi}{$ifdef windows}{$apptype console}{$endif}
uses Generics.Collections;
type
TlDictionary = TDictionary<string, Integer>;
TlPair = TPair<string,integer>;
var
i: Integer;
s: string;
lDictionary: TlDictionary;
lPair: TlPair;
begin
lDictionary := TlDiction... |
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... | #Yabasic | Yabasic | sub filter(a(), b(), signal(), result())
local i, j, tmp
for i = 0 to arraysize(signal(), 1)
tmp = 0
for j = 0 to arraysize(b(), 1)
if (i-j<0) continue
tmp = tmp + b(j) * signal(i-j)
next
for j = 0 to arraysize(a(), 1)
if (i-j<0) continue
... |
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... | #zkl | zkl | fcn direct_form_II_transposed_filter(b,a,signal){
out:=List.createLong(signal.len(),0.0); // vector of zeros
foreach i in (signal.len()){
tmp:=0.0;
foreach j in (b.len()){ if(i-j >=0) tmp += b[j]*signal[i-j] }
foreach j in (a.len()){ if(i-j >=0) tmp -= a[j]*out[i-j] }
out[i] = tmp/a[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... | #Frink | Frink |
mean[x] := length[x] > 0 ? sum[x] / length[x] : undef
|
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... | #GAP | GAP | Mean := function(v)
local n;
n := Length(v);
if n = 0 then
return 0;
else
return Sum(v)/n;
fi;
end;
Mean([3, 1, 4, 1, 5, 9]);
# 23/6 |
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.... | #Prolog | Prolog | prime_factors(N, Factors):-
S is sqrt(N),
prime_factors(N, Factors, S, 2).
prime_factors(1, [], _, _):-!.
prime_factors(N, [P|Factors], S, P):-
P =< S,
0 is N mod P,
!,
M is N // P,
prime_factors(M, Factors, S, P).
prime_factors(N, Factors, S, P):-
Q is P + 1,
Q =< S,
!,
pr... |
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 ... | #Sidef | Sidef | func time2deg(t) {
(var m = t.match(/^(\d\d):(\d\d):(\d\d)$/)) || die "invalid time"
var (hh,mm,ss) = m.cap.map{.to_i}...
((hh ~~ 24.range) && (mm ~~ 60.range) && (ss ~~ 60.range)) || die "invalid time"
(hh*3600 + mm*60 + ss) * 360 / 86400
}
func deg2time(d) {
var sec = ((d % 360) * 86400 / 360)
"%02d:%02... |
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 ... | #Stata | Stata | mata
function meanangle(a) {
return(arg(sum(exp(C(0,a)))))
}
deg=pi()/180
meanangle((350,10)*deg)/deg
-1.61481e-15
meanangle((90,180,270,360)*deg)/deg
0
meanangle((10,20,30)*deg)/deg
20
end |
http://rosettacode.org/wiki/Averages/Mean_angle | Averages/Mean angle | When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle.
If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the ... | #Swift | Swift | import Foundation
@inlinable public func d2r<T: FloatingPoint>(_ f: T) -> T { f * .pi / 180 }
@inlinable public func r2d<T: FloatingPoint>(_ f: T) -> T { f * 180 / .pi }
public func meanOfAngles(_ angles: [Double]) -> Double {
let cInv = 1 / Double(angles.count)
let (s, c) =
angles.lazy
.map(d2r)
... |
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 ... | #Lingo | Lingo | on median (numlist)
-- numlist = numlist.duplicate() -- if input list should not be altered
numlist.sort()
if numlist.count mod 2 then
return numlist[numlist.count/2+1]
else
return (numlist[numlist.count/2]+numlist[numlist.count/2+1])/2.0
end if
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 ... | #LiveCode | LiveCode | put median("4.1,5.6,7.2,1.7,9.3,4.4,3.2") & "," & median("4.1,7.2,1.7,9.3,4.4,3.2")
returns 4.4, 4.25 |
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... | #Modula-2 | Modula-2 | MODULE PythagoreanMeans;
FROM FormatString IMPORT FormatString;
FROM LongMath IMPORT power;
FROM LongStr IMPORT RealToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE ArithmeticMean(numbers : ARRAY OF LONGREAL) : LONGREAL;
VAR
i,cnt : CARDINAL;
mean : LONGREAL;
BEGIN
mean := 0.0;
cnt ... |
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.... | #UTFool | UTFool |
···
http://rosettacode.org/wiki/Babbage_problem
···
■ BabbageProblem
§ static
▶ main
• args⦂ String[]
for each number from √269696 up to √Integer.MAX_VALUE
if ("⸨number × number⸩").endsWith "269696"
System.exit number
|
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.... | #VAX_Assembly | VAX Assembly |
36 35 34 33 32 31 00000008'010E0000' 0000 1 result: .ascid "123456" ;output buffer
0000 000E 2 retlen: .word 0 ;$fao_s bytes written
4C 55 21 00000018'010E0000' 0010 3 format: .ascid "!UL" ;unsigned decimal... |
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) ... | #Fortran | Fortran |
! $ gfortran -g -O0 -std=f2008 -Wall f.f08 -o f.exe
! $ ./f
! compiles syntax error
! :
! : ][
! : ]][[
! :[[[]]]
! : ][[][]][
! : ][[]]][[[] ... |
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,... | #Nim | Nim | import posix
import strutils
type
# GECOS representation.
Gecos = tuple[fullname, office, extension, homephone, email: string]
# Record representation.
Record = object
account: string
password: string
uid: int
gid: int
gecos: Gecos
directory: string
shell: string
#-----------... |
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,... | #Pascal | Pascal | program appendARecordToTheEndOfATextFile;
var
passwd: bindable text;
FD: bindingType;
begin
{ initialize FD }
FD := binding(passwd);
FD.name := '/tmp/passwd';
{ attempt opening file [e.g. effective user has proper privileges?] }
bind(passwd, FD);
{ query binding state of `passwd` }
FD := binding(passwd... |
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... | #C | C | System.Collections.HashTable map = new System.Collections.HashTable();
map["key1"] = "foo"; |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #JavaScript | JavaScript |
function factors(n) {
var factors = [];
for (var i = 1; i <= n; i++) {
if (n % i == 0) {
factors.push(i);
}
}
return factors;
}
function generateAntiprimes(n) {
var antiprimes = [];
var maxFactors = 0;
for (var i = 1; antiprimes.length < n; i++) {
var ifactors = factors(i);
if (i... |
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... | #Smalltalk | Smalltalk | NUM_BUCKETS := 10.
"create and preset with random data"
buckets := (1 to:NUM_BUCKETS)
collect:[:i | Random nextIntegerBetween:0 and:10000]
as:Array.
count_randomizations := 0.
count_equalizations := 0.
printSum :=
[
"the sum must be computed and printed while noone fiddles arou... |
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.
| #Python | Python | a = 5
#...input or change a here
assert a == 42 # throws an AssertionError when a is not 42
assert a == 42, "Error message" # throws an AssertionError
# when a is not 42 with "Error message" for the message
# the error message can be any expression |
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.
| #QB64 | QB64 | $ASSERTS:CONSOLE
DO
a = INT(RND * 10)
b$ = myFunc$(a)
PRINT a, , b$
_LIMIT 3
LOOP UNTIL _KEYHIT
FUNCTION myFunc$ (value AS SINGLE)
_ASSERT value > 0, "Value cannot be zero"
_ASSERT value <= 10, "Value cannot exceed 10"
IF value > 1 THEN plural$ = "s"
myFunc$ = STRING$(value, "*") +... |
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.
| #R | R | stopifnot(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.
| #Elixir | Elixir |
Enum.map([1, 2, 3], fn(n) -> n * 2 end)
Enum.map [1, 2, 3], &(&1 * 2)
|
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.
| #Erlang | Erlang |
1> L = [1,2,3].
[1,2,3]
|
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat... | #Q | Q | mode:{(key x) where value x=max x} count each group @ |
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... | #Quackery | Quackery | [ sort
[] [] rot
dup 0 peek temp put
witheach
[ dup temp share = iff
join
else
[ dup temp replace
dip [ nested join ]
[] join ] ]
nested join
temp release ] is bunch ( [ --> [ )
[ sortwith [ size dip size < ]
[] sw... |
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 ... | #Frink | Frink | d = new dict[[[1, "one"], [2, "two"]]]
for [key, value] = d
println["$key\t$value"]
println[]
for key = keys[d]
println["$key"]
|
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 ... | #Gambas | Gambas | Public Sub Main()
Dim cList As Collection = ["2": "quick", "4": "fox", "1": "The", "9": "dog", "7": "the", "5": "jumped", "3": "brown", "6": "over", "8": "lazy"]
Dim siCount As Short
Dim sTemp As String
For Each sTemp In cList
Print cList.key & "=" & sTemp;;
Next
Print
For siCount = 1 To cList.Count
Print cL... |
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... | #GEORGE | GEORGE | R (n) P ;
0
1, n rep (i)
R P +
]
n div
P |
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... | #GFA_Basic | GFA Basic |
DIM a%(10)
FOR i%=0 TO 10
a%(i%)=i%*2
PRINT "element ";i%;" is ";a%(i%)
NEXT i%
PRINT "mean is ";@mean(a%)
'
FUNCTION mean(a%)
LOCAL i%,size%,sum
' find size of array,
size%=DIM?(a%())
' return 0 for empty arrays
IF size%<=0
RETURN 0
ENDIF
' find sum of all elements
sum=0
FOR i%=0 TO size%-1... |
http://rosettacode.org/wiki/Attractive_numbers | Attractive numbers | A number is an attractive number if the number of its prime factors (whether distinct or not) is also prime.
Example
The number 20, whose prime decomposition is 2 × 2 × 5, is an attractive number because the number of its prime factors (3) is also prime.
Task
Show sequence items up to 120.... | #PureBasic | PureBasic | #MAX=120
Dim prime.b(#MAX)
FillMemory(@prime(),#MAX,#True,#PB_Byte) : FillMemory(@prime(),2,#False,#PB_Byte)
For i=2 To Int(Sqr(#MAX)) : n=i*i : While n<#MAX : prime(n)=#False : n+i : Wend : Next
Procedure.i pfCount(n.i)
Shared prime()
If n=1 : ProcedureReturn 0 : EndIf
If prime(n) : ProcedureR... |
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 ... | #SQL.2FPostgreSQL | SQL/PostgreSQL |
--Setup table for testing
CREATE TABLE time_table(times TIME);
INSERT INTO time_table VALUES ('23:00:17'::TIME),('23:40:20'::TIME),('00:12:45'::TIME),('00:17:19'::TIME)
--Compute mean time
SELECT to_timestamp((degrees(atan2(AVG(sin),AVG(cos))))* (24*60*60)/360)::TIME
FROM
(SELECT
cos(radians(t*360/(24*60*60))),si... |
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 ... | #Tcl | Tcl | proc meanAngle {angles} {
set toRadians [expr {atan2(0,-1) / 180}]
set sumSin [set sumCos 0.0]
foreach a $angles {
set sumSin [expr {$sumSin + sin($a * $toRadians)}]
set sumCos [expr {$sumCos + cos($a * $toRadians)}]
}
# Don't need to divide by counts; atan2() cancels that out
return [expr {at... |
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 ... | #Vala | Vala | double meanAngle(double[] angles) {
double y_part = 0.0;
double x_part = 0.0;
for (int i = 0; i < angles.length; i++) {
x_part += Math.cos(angles[i] * Math.PI / 180.0);
y_part += Math.sin(angles[i] * Math.PI / 180.0);
}
return Math.atan2(y_part / angles.length, x_part / angles.length) * 180 / Math... |
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 ... | #LSL | LSL | integer MAX_ELEMENTS = 10;
integer MAX_VALUE = 100;
default {
state_entry() {
list lst = [];
integer x = 0;
for(x=0 ; x<MAX_ELEMENTS ; x++) {
lst += llFrand(MAX_VALUE);
}
llOwnerSay("lst=["+llList2CSV(lst)+"]");
llOwnerSay("Geometric Mean: "+(string)llList... |
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 ... | #Lua | Lua | function median (numlist)
if type(numlist) ~= 'table' then return numlist end
table.sort(numlist)
if #numlist %2 == 0 then return (numlist[#numlist/2] + numlist[#numlist/2+1]) / 2 end
return numlist[math.ceil(#numlist/2)]
end
print(median({4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2}))
print(median({4.1, 7.2, 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... | #MUMPS | MUMPS | Pyth(n) New a,ii,g,h,x
For ii=1:1:n set x(ii)=ii
;
; Average
Set a=0 For ii=1:1:n Set a=a+x(ii)
Set a=a/n
;
; Geometric
Set g=1 For ii=1:1:n Set g=g*x(ii)
Set g=g**(1/n)
;
; Harmonic
Set h=0 For ii=1:1:n Set h=1/x(ii)+h
Set h=n/h
;
Write !,"Pythagorean means for 1..",n,":",!
Write "Average = ",a," >= Ge... |
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.... | #VBA | VBA |
Sub Baggage_Problem()
Dim i As Long
'We can start at the square root of 269696
i = 520
'269696 is a multiple of 4, 520 too
'so we can increment i by 4
Do While ((i * i) Mod 1000000) <> 269696
i = i + 4 'Increment by 4
Loop
Debug.Print "The smallest positive integer whose square e... |
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.... | #VBScript | VBScript | 'Sir, this is a script that could solve your problem.
'Lines that begin with the apostrophe are comments. The machine ignores them.
'The next line declares a variable n and sets it to 0. Note that the
'equals sign "assigns", not just "relates". So in here, this is more
'of a command, rather than just a mere propositi... |
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) ... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function isBalanced(s As String) As Boolean
If s = "" Then Return True
Dim countLeft As Integer = 0 '' counts number of left brackets so far unmatched
Dim c As String
For i As Integer = 1 To Len(s)
c = Mid(s, i, 1)
If c = "[" Then
countLeft += 1
ElseIf countLeft > 0 Then
... |
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,... | #Perl | Perl | use strict;
use warnings;
use Fcntl qw( :flock SEEK_END );
use constant {
RECORD_FIELDS => [qw( account password UID GID GECOS directory shell )],
GECOS_FIELDS => [qw( fullname office extension homephone email )],
RECORD_SEP => ':',
GECOS_SEP => ',',
PASSWD_FILE => 'passwd.txt',
};
#... |
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... | #C.23 | C# | System.Collections.HashTable map = new System.Collections.HashTable();
map["key1"] = "foo"; |
http://rosettacode.org/wiki/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #jq | jq |
# Compute the number of divisors, without calling sqrt
def ndivisors:
def sum(s): reduce s as $x (null; .+$x);
if . == 1 then 1
else . as $n
| sum( label $out
| range(1; $n) as $i
| ($i * $i) as $i2
| if $i2 > $n then break $out
else if $i2 == $n
then 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
| #Julia | Julia | using Primes, Combinatorics
function antiprimes(N, maxn = 2000000)
antip = [1] # special case: 1 is antiprime
count = 1
maxfactors = 1
for i in 2:2:maxn # antiprimes > 2 should be even
lenfac = length(unique(sort(collect(combinations(factor(Vector, i)))))) + 1
if lenfac > maxfactors
... |
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... | #Swift | Swift | import Foundation
final class AtomicBuckets: CustomStringConvertible {
var count: Int {
return buckets.count
}
var description: String {
return withBucketsLocked { "\(buckets)" }
}
var total: Int {
return withBucketsLocked { buckets.reduce(0, +) }
}
private let lock = DispatchSemaphore... |
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... | #Tcl | Tcl | package require Thread
package require Tk
# Make the shared state
canvas .c ;# So we can allocate the display lines in one loop
set m [thread::mutex create]
for {set i 0} {$i<100} {incr i} {
set bucket b$i ;# A handle for every bucket...
tsv::set buckets $bucket 50
lappend buckets $bucket
lappend lin... |
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.
| #Racket | Racket | #lang racket
(define/contract x
(=/c 42) ; make sure x = 42
42)
(define/contract f
(-> number? (or/c 'yes 'no)) ; function contract
(lambda (x)
(if (= 42 x) 'yes 'no)))
(f 42) ; succeeds
(f "foo") ; contract error!
|
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.
| #Raku | Raku | my $a = (1..100).pick;
$a == 42 or die '$a ain\'t 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.
| #REXX | REXX | /* REXX ***************************************************************
* There's no assert feature in Rexx. That's how I'd implement it
* 10.08.2012 Walter Pachl
**********************************************************************/
x.=42
x.2=11
Do i=1 By 1
Call assert x.i,42
End
Exit
assert:
Parse Arg assert_h... |
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.
| #ERRE | ERRE |
PROGRAM CALLBACK
!
! for rosettacode.org
!
DIM A[5]
FUNCTION CBACK(X)
CBACK=2*X-1
END FUNCTION
PROCEDURE PROCMAP(ZETA,DUMMY(X)->OUTP)
OUTP=DUMMY(ZETA)
END PROCEDURE
BEGIN
A[1]=1 A[2]=2 A[3]=3 A[4]=4 A[5]=5
FOR I%=1 TO 5 DO
PROCMAP(A[I%],CBACK(X)->OUTP)
PRINT(OUTP;)
END FOR
... |
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.
| #Euphoria | Euphoria | function apply_to_all(sequence s, integer f)
-- apply a function to all elements of a sequence
sequence result
result = {}
for i = 1 to length(s) do
-- we can call add1() here although it comes later in the program
result = append(result, call_func(f, {s[i]}))
end for
return result
end functio... |
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... | #R | R | statmode <- function(v) {
a <- sort(table(v), decreasing=TRUE)
r <- c()
for(i in 1:length(a)) {
if ( a[[1]] == a[[i]] ) {
r <- c(r, as.integer(names(a)[i]))
} else break; # since it's sorted, once we find
# a different value, we can stop
}
r
}
print(statmode(c(1, 3, 6, 6, 6, ... |
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... | #Racket | Racket | #lang racket
(define (mode seq)
(define frequencies (make-hash))
(for ([s seq])
(hash-update! frequencies
s
(lambda (freq) (add1 freq))
0))
(for/fold ([ms null]
[freq 0])
([(k v) (in-hash frequencies)])
(cond [(> v freq)
... |
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 ... | #Go | Go | myMap := map[string]int {
"hello": 13,
"world": 31,
"!" : 71 }
// iterating over key-value pairs:
for key, value := range myMap {
fmt.Printf("key = %s, value = %d\n", key, value)
}
// iterating over keys:
for key := range myMap {
fmt.Printf("key = %s\n", key)
}
// iterating over values:
for... |
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 ... | #Groovy | Groovy | def map = [lastName: "Anderson", firstName: "Thomas", nickname: "Neo", age: 24, address: "everywhere"]
println "Entries:"
map.each { println it }
println()
println "Keys:"
map.keySet().each { println it }
println()
println "Values:"
map.values().each { println it } |
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... | #Go | Go | package main
import (
"fmt"
"math"
)
func mean(v []float64) (m float64, ok bool) {
if len(v) == 0 {
return
}
// an algorithm that attempts to retain accuracy
// with widely different values.
var parts []float64
for _, x := range v {
var i int
for _, p := range... |
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.... | #Python | Python | from sympy import sieve # library for primes
def get_pfct(n):
i = 2; factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return len(factors)
sieve.extend(110) # first 110 primes...
primes=sieve._list
pool=[]
for each in xrange(0,121):
... |
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 ... | #Swift | Swift | import Foundation
@inlinable public func d2r<T: FloatingPoint>(_ f: T) -> T { f * .pi / 180 }
@inlinable public func r2d<T: FloatingPoint>(_ f: T) -> T { f * 180 / .pi }
public func meanOfAngles(_ angles: [Double]) -> Double {
let cInv = 1 / Double(angles.count)
let (y, x) =
angles.lazy
.map(d2r)
... |
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 ... | #Tcl | Tcl | proc meanTime {times} {
set secsPerRad [expr {60 * 60 * 12 / atan2(0,-1)}]
set sumSin [set sumCos 0.0]
foreach t $times {
# Convert time to count of seconds from midnight
scan $t "%02d:%02d:%02d" h m s
incr s [expr {[incr m [expr {$h * 60}]] * 60}]
# Feed into averaging
set sumSin [expr {$sumSin + sin(... |
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 ... | #VBA | VBA | Option Base 1
Private Function mean_angle(angles As Variant) As Double
Dim sins() As Double, coss() As Double
ReDim sins(UBound(angles))
ReDim coss(UBound(angles))
For i = LBound(angles) To UBound(angles)
sins(i) = Sin(WorksheetFunction.Radians(angles(i)))
coss(i) = Cos(WorksheetFunction... |
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 ... | #Visual_Basic_.NET | Visual Basic .NET | Imports System.Math
Module Module1
Function MeanAngle(angles As Double()) As Double
Dim x = angles.Sum(Function(a) Cos(a * PI / 180)) / angles.Length
Dim y = angles.Sum(Function(a) Sin(a * PI / 180)) / angles.Length
Return Atan2(y, x) * 180 / PI
End Function
Sub Main()
... |
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 ... | #Maple | Maple |
> Statistics:-Median( [ 1, 5, 3, 2, 4 ] );
3.
> Statistics:-Median( [ 1, 5, 3, 6, 2, 4 ] );
3.50000000000000
|
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 ... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | Median[{1, 5, 3, 2, 4}]
Median[{1, 5, 3, 6, 4, 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... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
numeric digits 20
a1 = ArrayList(Arrays.asList([Rexx 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]))
say "Arithmetic =" arithmeticMean(a1)", Geometric =" geometricMean(a1)", Harmonic =" harmonicMean(a1)
return
-- ~~~~~~~~~~~~~~~~~... |
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.... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function Right6Digits(num As Long) As Long
Dim asString = num.ToString()
If asString.Length < 6 Then
Return num
End If
Dim last6 = asString.Substring(asString.Length - 6)
Return Long.Parse(last6)
End Function
Sub Main()
Dim bnS... |
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) ... | #Gambas | Gambas | 'Altered to prevent lines starting with ']' or ending with '[' being generated as they can't work
siNumberOfBrackets As Short = 20 'Maximum amount of brackets in a line
siNumberOfLines As Short = 20 'Amount of lines to test
'----
Public Sub Main()
Dim sBrks As String[] = GenerateBrack... |
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,... | #Phix | Phix | without js -- (file i/o, sleep, task_yield, wait_key)
constant filename = "passwd.txt"
integer fn
constant
rec1 = {"jsmith","x",1001,1000,{"Joe Smith","Room 1007","(234)555-8917","(234)555-0077","jsmith@rosettacode.org"},"/home/jsmith","/bin/bash"},
rec2 = {"jdoe","x",1002,1000,{"Jane Doe","Room 1004","(234)555-891... |
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... | #C.2B.2B | C++ | #include <map> |
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
| #Kotlin | Kotlin | // Version 1.3.10
fun countDivisors(n: Int): Int {
if (n < 2) return 1;
var count = 2 // 1 and n
for (i in 2..n / 2) {
if (n % i == 0) count++
}
return count;
}
fun main(args: Array<String>) {
println("The first 20 anti-primes are:")
var maxDiv = 0
var count = 0
var n = 1... |
http://rosettacode.org/wiki/Atomic_updates | Atomic updates |
Task
Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to:
get the current value of any bucket
remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the t... | #Wren | Wren | import "random" for Random
import "scheduler" for Scheduler
import "timer" for Timer
import "/math" for Nums
var Rnd = Random.new()
var NUM_BUCKETS = 10
var MAX_VALUE = 9999
class Buckets {
construct new(data) {
_data = data.toList
_running = true
}
[index] { _data[index] }
t... |
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.
| #Ring | Ring |
x = 42
assert( x = 42 )
assert( x = 100 )
|
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.
| #RLaB | RLaB |
// test if 'a' is 42, and if not stop the execution of the code and print
// some error message
if (a != 42)
{
stop("a is not 42 as expected, therefore I stop until this issue is resolved!");
}
|
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.
| #Ruby | Ruby | require "test/unit/assertions"
include Test::Unit::Assertions
n = 5
begin
assert_equal(42, n)
rescue Exception => e
# Ruby 1.8: e is a Test::Unit::AssertionFailedError
# Ruby 1.9: e is a MiniTest::Assertion
puts e
end |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Rust | Rust |
let x = 42;
assert!(x == 42);
assert_eq!(x, 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.
| #F.23 | F# | let evenp x = x % 2 = 0
let result = Array.map evenp [| 1; 2; 3; 4; 5; 6 |] |
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.
| #Factor | Factor | { 1 2 3 4 } [ sq . ] each |
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... | #Raku | Raku | sub mode (*@a) {
my %counts := @a.Bag;
my $max = %counts.values.max;
%counts.grep(*.value == $max).map(*.key);
}
# Testing with arrays:
say mode [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];
say mode [1, 1, 2, 4, 4]; |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.