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/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 ... | #Harbour | Harbour | LOCAL arr := { 6 => 16, "eight" => 8, "eleven" => 11 }
LOCAL x
FOR EACH x IN arr
// key, value
? x:__enumKey(), x
// or key only
? x:__enumKey()
// or value only
? x
NEXT |
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 ... | #Haskell | Haskell | import qualified Data.Map as M
myMap :: M.Map String Int
myMap = M.fromList [("hello", 13), ("world", 31), ("!", 71)]
main :: IO ()
main =
(putStrLn . unlines) $
[ show . M.toList -- Pairs
, show . M.keys -- Keys
, show . M.elems -- Values
] <*>
pure myMap |
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... | #Groovy | Groovy | def avg = { list -> list == [] ? 0 : list.sum() / list.size() } |
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.... | #Quackery | Quackery | [ primefactors size
primefactors size 1 = ] is attractive ( n --> b )
120 times
[ i^ 1+ attractive if
[ i^ 1+ echo sp ] ] |
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.... | #R | R |
is_prime <- function(num) {
if (num < 2) return(FALSE)
if (num %% 2 == 0) return(num == 2)
if (num %% 3 == 0) return(num == 3)
d <- 5
while (d*d <= num) {
if (num %% d == 0) return(FALSE)
d <- d + 2
if (num %% d == 0) return(FALSE)
d <- d + 4
}
TRUE
}
count_prime_factors <- function(... |
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 ... | #VBA | VBA | Public Sub mean_time()
Dim angles() As Double
s = [{"23:00:17","23:40:20","00:12:45","00:17:19"}]
For i = 1 To UBound(s)
s(i) = 360 * TimeValue(s(i))
Next i
Debug.Print Format(mean_angle(s) / 360 + 1, "hh:mm:ss")
End Sub |
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 ... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function TimeToDegrees(time As TimeSpan) As Double
Return 360 * time.Hours / 24.0 + 360 * time.Minutes / (24 * 60.0) + 360 * time.Seconds / (24 * 3600.0)
End Function
Function DegreesToTime(angle As Double) As TimeSpan
Return New TimeSpan((24 * 60 * 60 * angle \ 360) \ 360... |
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 ... | #Vlang | Vlang | import math
fn mean_angle(deg []f64) f64 {
mut ss, mut sc := f64(0), f64(0)
for x in deg {
s, c := math.sincos(x * math.pi / 180)
ss += s
sc += c
}
return math.atan2(ss, sc) * 180 / math.pi
}
fn main() {
for angles in [
[f64(350), 10],
[f64(90), 180, 270, 360],
[f64(10), 20, 30],
] {
println("Th... |
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 ... | #Wren | Wren | import "/fmt" for Fmt
var meanAngle = Fn.new { |angles|
var n = angles.count
var sinSum = 0
var cosSum = 0
for (angle in angles) {
sinSum = sinSum + (angle * Num.pi / 180).sin
cosSum = cosSum + (angle * Num.pi / 180).cos
}
return (sinSum/n).atan(cosSum/n) * 180 / Num.pi
}
var... |
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 ... | #MATLAB | MATLAB | function medianValue = findmedian(setOfValues)
medianValue = median(setOfValues);
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 ... | #Maxima | Maxima | /* built-in */
median([41, 56, 72, 17, 93, 44, 32]); /* 44 */
median([41, 72, 17, 93, 44, 32]); /* 85/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... | #Nim | Nim | import math, sequtils, sugar
proc amean(num: seq[float]): float =
sum(num) / float(len(num))
proc gmean(num: seq[float]): float =
result = 1
for n in num: result *= n
result = pow(result, 1.0 / float(num.len))
proc hmean(num: seq[float]): float =
for n in num: result += 1.0 / n
result = float(num.len)... |
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... | #Oberon-2 | Oberon-2 |
MODULE PythMean;
IMPORT Out, ML := MathL;
PROCEDURE Triplets(a: ARRAY OF INTEGER;VAR triplet: ARRAY OF LONGREAL);
VAR
i: INTEGER;
BEGIN
triplet[0] := 0.0;triplet[1] := 0.0; triplet[2] := 0.0;
FOR i:= 0 TO LEN(a) - 1 DO
triplet[0] := triplet[0] + a[i];
triplet[1] := triplet[1] + ML.Ln(a[i]);
triplet[2] := t... |
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.... | #Vlang | Vlang |
const (
target = 269696
modulus = 1000000
)
fn main() {
for n := 1; ; n++ { // Repeat with n=1, n=2, n=3, ...
square := n * n
ending := square % modulus
if ending == target {
println("The smallest number whose square ends with $target is $n")
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.... | #Wren | Wren | /*
The answer must be an even number and it can't be less than the square root of 269,696.
So, if we start from that, keep on adding 2 and squaring it we'll eventually find the answer.
*/
import "/fmt" for Fmt // this enables us to format numbers with thousand separators
var start = 269696.s... |
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) ... | #GAP | GAP | Balanced := function(L)
local c, r;
r := 0;
for c in L do
if c = ']' then
r := r - 1;
if r < 0 then
return false;
fi;
elif c = '[' then
r := r + 1;
fi;
od;
return r = 0;
end;
Balanced("");
# true
Balanced("["... |
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,... | #Phixmonti | Phixmonti | include ..\Utilitys.pmt
def ltos /# l -- s #/
"" >ps
len for get
string? not if
number? if
tostr
else
ltos
"<ls>:" swap "</ls>" chain chain
endif
endif
ps> swap chain ":" chain >ps
en... |
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,... | #PHP | PHP | <?php
$filename = '/tmp/passwd';
$data = array(
'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL,
'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL,
'jdoe:x:1002:1000:Jane Doe,Room 10... |
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... | #Ceylon | Ceylon | import ceylon.collection {
ArrayList,
HashMap,
naturalOrderTreeMap
}
shared void run() {
// the easiest way is to use the map function to create
// an immutable map
value myMap = map {
"foo" -> 5,
"bar" -> 10,
"baz" -> 15,
"foo" -> 6 // by default the first "foo" will remain
};
// or you can use... |
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
| #Lua | Lua | -- First 20 antiprimes.
function count_factors(number)
local count = 0
for attempt = 1, number do
local remainder = number % attempt
if remainder == 0 then
count = count + 1
end
end
return count
end
function antiprimes(goal)
local list, number, mostFactors = {}, 1, 0
while #list < goal do
local fac... |
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
| #Maple | Maple | antiprimes := proc(n)
local ap, i, max_divisors, num_divisors;
max_divisors := 0;
ap := [];
for i from 1 while numelems(ap) < n do
num_divisors := numelems(NumberTheory:-Divisors(i));
if num_divisors > max_divisors then
ap := [op(ap), i];
max_divisors := num_divisors;
end if;
end do;
retur... |
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... | #zkl | zkl | class B{
const N=10;
var [const]
buckets=(1).pump(N,List).copy(), //(1,2,3...)
lock=Atomic.Lock(), cnt=Atomic.Int();
fcn init{ "Initial sum: ".println(values().sum()); }
fcn transferArb{ // transfer arbitary amount from 1 bucket to another
b1:=(0).random(N); b2:=(0).random(N);
crit... |
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.
| #Sather | Sather | class MAIN is
main is
i ::= 41;
assert i = 42; -- fatal
-- ...
end;
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.
| #Scala | Scala | assert(a == 42)
assert(a == 42, "a isn't equal to 42")
assume(a == 42)
assume(a == 42, "a isn't equal to 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.
| #Scheme | Scheme | (let ((x 42))
(assert (and (integer? x) (= x 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.
| #SETL | SETL | assert( n = 42 ); |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Fantom | Fantom |
class Main
{
public static Void main ()
{
[1,2,3,4,5].each |Int i| { echo (i) }
Int[] result := [1,2,3,4,5].map |Int i->Int| { return i * i }
echo (result)
}
}
|
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.
| #FBSL | FBSL | #APPTYPE CONSOLE
FOREACH DIM e IN MyMap(Add42, {1, 2, 3})
PRINT e, " ";
NEXT
PAUSE
FUNCTION MyMap(f, a)
DIM ret[]
FOREACH DIM e IN a
ret[] = f(e)
NEXT
RETURN ret
END FUNCTION
FUNCTION Add42(n): RETURN n + 42: END FUNCTION |
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... | #REXX | REXX | /*REXX program finds the mode (most occurring element) of a vector. */
/* ════════vector═══════════ ═══show vector═══ ═════show result═════ */
v= 1 8 6 0 1 9 4 6 1 9 9 9 ; say 'vector='v; say 'mode='mode(v); say
v= 1 2 3 4 5 6 7 8 9 11 10 ; say 've... |
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 ... | #Icon_and_Unicon | Icon and Unicon | procedure main()
t := table()
every t[a := !"ABCDE"] := map(a)
every pair := !sort(t) do
write("\t",pair[1]," -> ",pair[2])
writes("Keys:")
every writes(" ",key(t))
write()
writes("Values:")
every writes(" ",!t)
write()
end |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin... | #Haskell | Haskell | mean :: (Fractional a) => [a] -> a
mean [] = 0
mean xs = sum xs / Data.List.genericLength xs |
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... | #HicEst | HicEst | REAL :: vec(100) ! no zero-length arrays in HicEst
vec = $ - 1/2 ! 0.5 ... 99.5
mean = SUM(vec) / LEN(vec) ! 50
END |
http://rosettacode.org/wiki/Attractive_numbers | Attractive numbers | A number is an attractive number if the number of its prime factors (whether distinct or not) is also prime.
Example
The number 20, whose prime decomposition is 2 × 2 × 5, is an attractive number because the number of its prime factors (3) is also prime.
Task
Show sequence items up to 120.... | #Racket | Racket | #lang racket
(require math/number-theory)
(define attractive? (compose1 prime? prime-omega))
(filter attractive? (range 1 121)) |
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.... | #Raku | Raku | use Lingua::EN::Numbers;
use ntheory:from<Perl5> <factor is_prime>;
sub display ($n,$m) { ($n..$m).grep: (~*).&factor.elems.&is_prime }
sub count ($n,$m) { +($n..$m).grep: (~*).&factor.elems.&is_prime }
# The Task
put "Attractive numbers from 1 to 120:\n" ~
display(1, 120)».fmt("%3d").rotor(20, :partial).join: "\... |
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 ... | #Vlang | Vlang | import math
const inputs = ["23:00:17", "23:40:20", "00:12:45", "00:17:19"]
fn main() {
angles := inputs.map(time_to_degs(it))
println('Mean time of day is: ${degs_to_time(mean_angle(angles))}')
}
fn mean_angle(angles []f64) f64 {
n := angles.len
mut sin_sum := f64(0)
mut cos_sum := f64(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 ... | #Wren | Wren | import "/fmt" for Fmt
var timeToDegs = Fn.new { |time|
var t = time.split(":")
var h = Num.fromString(t[0]) * 3600
var m = Num.fromString(t[1]) * 60
var s = Num.fromString(t[2])
return (h + m + s) / 240
}
var degsToTime = Fn.new { |d|
while (d < 0) d = d + 360
var s = (d * 240).round
... |
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 ... | #XPL0 | XPL0 | include c:\cxpl\codes;
def Pi = 3.14159265358979323846;
def D2R = Pi/180.0; \coefficient to convert degrees to radians
func real MeanAng(A); \Return the mean of the given list of angles
int A;
real X, Y;
int I;
[X:= 0.0; Y:= 0.0;
for I:= 1 to A(0) do
[X:= X + Cos(D2R*float(A(I)));
... |
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 ... | #zkl | zkl | fcn meanA(a1,a2,etc){
as:=vm.arglist.pump(List,"toFloat","toRad");
n:=as.len();
(as.apply("sin").sum(0.0)/n)
.atan2(as.apply("cos").sum(0.0)/n)
.toDeg()
} |
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 ... | #MiniScript | MiniScript | list.median = function()
self.sort
m = floor(self.len/2)
if self.len % 2 then return self[m]
return (self[m] + self[m-1]) * 0.5
end function
print [41, 56, 72, 17, 93, 44, 32].median
print [41, 72, 17, 93, 44, 32].median |
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 ... | #MUMPS | MUMPS | MEDIAN(X)
;X is assumed to be a list of numbers separated by "^"
;I is a loop index
;L is the length of X
;Y is a new array
QUIT:'$DATA(X) "No data"
QUIT:X="" "Empty Set"
NEW I,ODD,L,Y
SET L=$LENGTH(X,"^"),ODD=L#2,I=1
;The values in the vector are used as indices for a new array Y, which sorts them
FOR QUIT:... |
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... | #Objeck | Objeck | class PythagMeans {
function : Main(args : String[]) ~ Nil {
array := [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
arithmetic := ArithmeticMean(array);
geometric := GeometricMean(array);
harmonic := HarmonicMean(array);
arith_geo := arithmetic >= geometric;
geo_harm := geometric >= h... |
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.... | #x86_Assembly | x86 Assembly | # What is the lowest number whose square ends in 269,696?
# At the very end, when we have a result and we need to print it, we shall use for the purpose a program called PRINTF, which forms part of a library of similar utility programs that are provided for us. The codes given here will be needed at that point to tel... |
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.... | #XLISP | XLISP | ; The computer will evaluate expressions written in -- possibly nested -- parentheses, where the first symbol gives the operation and any subsequent symbols or numbers give the operands.
; For instance, (+ (+ 2 2) (- 7 5)) evaluates to 6.
; We define our problem as a function:
(define (try n)
; We are looking f... |
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) ... | #Go | Go | package main
import (
"bytes"
"fmt"
"math/rand"
"time"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func generate(n uint) string {
a := bytes.Repeat([]byte("[]"), int(n))
for i := len(a) - 1; i >= 1; i-- {
j := rand.Intn(i + 1)
a[i], a[j] = a[j], a[i]
}
re... |
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,... | #PicoLisp | PicoLisp | (setq L '((jsmith x 1001 1000
"Joe Smith,Room 1007,(234)555-8917,\
(234)555-0077,jsmith@rosettacode.org"
/home/jsmith /bin/bash )
(jdoe x 1002 1000
"Jane Doe,Room 1004,(234)555-8914,\
(234)555-0044,jdoe@rosettacode.org"
/home/jsmith /bin/bash ) ) )
(setq A '(xyz x 1003 1000
"X Yz,Room 1003,(... |
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,... | #PowerShell | PowerShell |
function Test-FileLock
{
Param
(
[parameter(Mandatory=$true)]
[string]
$Path
)
$outFile = New-Object System.IO.FileInfo $Path
if (-not(Test-Path -Path $Path))
{
return $false
}
try
{
$outStream = $outFile.Open([System.IO.FileMode]::Open... |
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... | #Chapel | Chapel | // arr is an array of string to int. any type can be used in both places.
var keys: domain(string);
var arr: [keys] int;
// keys can be added to a domain using +, new values will be initialized to the default value (0 for int)
keys += "foo";
keys += "bar";
keys += "baz";
// array access via [] or ()
arr["foo"] = 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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | sigma = DivisorSigma[0, #] &;
currentmax = -\[Infinity];
res = {};
Do[
s = sigma[v];
If[s > currentmax,
AppendTo[res, v];
currentmax = s;
];
If[Length[res] >= 25, Break[]]
,
{v, \[Infinity]}
]
res |
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
| #Modula-2 | Modula-2 | MODULE Antiprimes;
FROM InOut IMPORT WriteCard, WriteLn;
CONST Amount = 20;
VAR max, seen, n, f: CARDINAL;
PROCEDURE factors(n: CARDINAL): CARDINAL;
VAR facs, div: CARDINAL;
BEGIN
IF n<2 THEN RETURN 1; END;
facs := 2;
FOR div := 2 TO n DIV 2 DO
IF n MOD div = 0 THEN
INC(facs);
... |
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.
| #Sidef | Sidef | var num = pick(0..100);
assert_eq(num, 42); # dies when "num" is not 42 |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Slate | Slate | load: 'src/lib/assert.slate'.
define: #n -> 7.
assert: n = 42 &description: 'That is not the Answer.'. |
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.
| #Smalltalk | Smalltalk | foo := 41.
...
self assert: (foo == 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.
| #SPARK | SPARK | -# check 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.
| #Forth | Forth | : map ( addr n fn -- )
-rot cells bounds do i @ over execute i ! cell +loop ; |
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.
| #Fortran | Fortran | module arrCallback
contains
elemental function cube( x )
implicit none
real :: cube
real, intent(in) :: x
cube = x * x * x
end function cube
end module arrCallback |
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... | #Ring | Ring |
# Project : Averages/Mode
a = [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]
b = [1, 2, 4, 4, 1]
amodes = list(12)
see "mode(s) of a() = " + nl
for i1 = 1 to modes(a,amodes)
see "" + amodes[i1] + " "
next
see nl
see "mode(s) of b() = " + nl
for i1 = 1 to modes(b,amodes)
see "" + amodes [i1] + " "
next
see nl
fun... |
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... | #Ruby | Ruby | def mode(ary)
seen = Hash.new(0)
ary.each {|value| seen[value] += 1}
max = seen.values.max
seen.find_all {|key,value| value == max}.map {|key,value| key}
end
def mode_one_pass(ary)
seen = Hash.new(0)
max = 0
max_elems = []
ary.each do |value|
seen[value] += 1
if seen[value] > max
max = s... |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked ... | #Io | Io | myDict := Map with(
"hello", 13,
"world", 31,
"!" , 71
)
// iterating over key-value pairs:
myDict foreach( key, value,
writeln("key = ", key, ", value = ", value)
)
// iterating over keys:
myDict keys foreach( key,
writeln("key = ", key)
)
// iterating over values:
myDict foreach( value,
... |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked ... | #J | J | nl__example 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... | #Hy | Hy | (defn arithmetic-mean [xs]
(if xs
(/ (sum xs) (len xs)))) |
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... | #Icon_and_Unicon | Icon and Unicon | procedure main(args)
every (s := 0) +:= !args
write((real(s)/(0 ~= *args)) | 0)
end |
http://rosettacode.org/wiki/Attractive_numbers | Attractive numbers | A number is an attractive number if the number of its prime factors (whether distinct or not) is also prime.
Example
The number 20, whose prime decomposition is 2 × 2 × 5, is an attractive number because the number of its prime factors (3) is also prime.
Task
Show sequence items up to 120.... | #REXX | REXX | /*REXX program finds and shows lists (or counts) attractive numbers up to a specified N.*/
parse arg N . /*get optional argument from the C.L. */
if N=='' | N=="," then N= 120 /*Not specified? Then use the default.*/
cnt= N<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 ... | #XPL0 | XPL0 | include c:\cxpl\codes;
proc NumOut(N); \Display 2-digit N with leading zero
int N;
[if N<10 then ChOut(0, ^0);
IntOut(0, N);
];
proc TimeOut(Sec); \Display real seconds as HH:MM:SS
real Sec;
[NumOut(fix(Sec)/3600); ChOut(0, ^:);
NumOut(rem(0)/60); ChOut(0, ^:);
NumOut(rem(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 ... | #Yabasic | Yabasic | sub atan2(y, x)
return 2 * atan((sqrt(x **2 + y ** 2) - x) / y)
end sub
sub MeanAngle(angles())
local x, y, ai_rad, l, i
l = arraysize(angles(), 1)
for i = 1 to l
ai_rad = angles(i) * PI / 180
x = x + cos(ai_rad)
y = y + sin(ai_rad)
next i
if abs(x) < 1e-16 return f... |
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 ... | #Nanoquery | Nanoquery | import sort
def median(aray)
srtd = sort(aray)
alen = len(srtd)
return 0.5*( srtd[int(alen-1/2)] + srtd[int(alen/2)])
end
a = {4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2}
println a + " " + median(a)
a = {4.1, 7.2, 1.7, 9.3, 4.4, 3.2}
println a + " " + median(a) |
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 ... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
class RAvgMedian00 public
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method median(lvector = java.util.List) public static returns Rexx
cvector = ArrayList(lvector) -- make a copy of input to ens... |
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... | #OCaml | OCaml | let means v =
let n = Array.length v
and a = ref 0.0
and b = ref 1.0
and c = ref 0.0 in
for i=0 to n-1 do
a := !a +. v.(i);
b := !b *. v.(i);
c := !c +. 1.0/.v.(i);
done;
let nn = float_of_int n in
(!a /. nn, !b ** (1.0/.nn), nn /. !c)
;; |
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.... | #XPL0 | XPL0 | int N, C, R;
[C:= 0;
for N:= sqrt(269696) to -1>>1 do \to infinity (2^31-1)
if rem(N/10)=4 or rem(N/10)=6 then \must end 6: 4^2=16; 6^2=36
[R:= rem(N/100);
if R=14 or R=36 or R=64 or R=86 then \14^2=196, etc.
[R:= rem(N/1000);
if R=236 or R=264 or R=736 or R=76... |
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.... | #Yabasic | Yabasic | // Charles Babbage habría sabido que solo un número que termina en 4 o 6
// podría producir un cuadrado que termina en 6, y cualquier número por
// debajo de 520 produciría un cuadrado menor que 269696. Podemos detenernos
// cuando hayamos alcanzado 99736, sabemos que es cuadrado y termina en 269696.
number = 524 // ... |
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) ... | #Groovy | Groovy | def random = new Random()
def factorial = { (it > 1) ? (2..it).inject(1) { i, j -> i*j } : 1 }
def makePermutation;
makePermutation = { string, i ->
def n = string.size()
if (n < 2) return string
def fact = factorial(n-1)
assert i < fact*n
def index = i.intdiv(fact)
string[index] + makePer... |
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,... | #Python | Python | #############################
# Create a passwd text file
#############################
# note that UID & gid are of type "text"
passwd_list=[
dict(account='jsmith', password='x', UID=1001, GID=1000, # UID and GID are type int
GECOS=dict(fullname='Joe Smith', office='Room 1007', extension='(234)555-8917',
... |
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... | #Clojure | Clojure | {:key "value"
:key2 "value2"
:key3 "value3"} |
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
| #Nanoquery | Nanoquery | def countDivisors(n)
if (n < 2)
return 1
end
count = 2
for i in range(2, int(n/2))
if (n % i) = 0
count += 1
end
end
return count
end
maxDiv = 0
count = 0
println "The first 20 anti-primes are:"
for (n = 1) (count < 20) (n += 1)
d = countDivisors(n)
if d > maxDiv
print format("%d ", n)
maxDiv =... |
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
| #Nim | Nim | # First 20 antiprimes
proc countDivisors(n: int): int =
if n < 2:
return 1
var count = 2
for i in countup(2, (n / 2).toInt()):
if n %% i == 0:
count += 1
return count
proc antiPrimes(n: int) =
echo("The first ", n, " anti-primes:")
var maxDiv = 0
var count = ... |
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
| #Objeck | Objeck | class AntiPrimes {
function : Main(args : String[]) ~ Nil {
maxDiv := 0; count := 0;
"The first 20 anti-primes are:"->PrintLine();
for(n := 1; count < 20; ++n;) {
d := CountDivisors(n);
if(d > maxDiv) {
"{$n} "->Print();
maxDiv := d;
count++;
};
};
'\n'->P... |
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.
| #Standard_ML | Standard ML | fun assert cond =
if cond then () else raise Fail "assert"
val () = assert (x = 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.
| #Stata | Stata | assert x<y if z>0 |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Swift | Swift | var a = 5
//...input or change a here
assert(a == 42) // aborts program when a is not 42
assert(a == 42, "Error message") // aborts program
// when a is not 42 with "Error message" for the message
// the error message must be a static string |
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.
| #Tcl | Tcl | package require control
set x 5
control::assert {$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.
| #FP | FP | {square * . [id, id]}
& square: <1,2,3,4,5> |
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.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Sub PrintEx(n As Integer)
Print n, n * n, n * n * n
End Sub
Sub Proc(a() As Integer, callback As Sub(n As Integer))
For i As Integer = LBound(a) To UBound(a)
callback(i)
Next
End Sub
Dim a(1 To 10) As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Print " n", "n^2", "n^3"
Print " -", "---",... |
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... | #Rust | Rust | use std::collections::HashMap;
fn main() {
let mode_vec1 = mode(vec![ 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]);
let mode_vec2 = mode(vec![ 1, 1, 2, 4, 4]);
println!("Mode of vec1 is: {:?}", mode_vec1);
println!("Mode of vec2 is: {:?}", mode_vec2);
assert!( mode_vec1 == [6], "Error in mode calculat... |
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... | #S-lang | S-lang | private variable mx, mxkey, modedat;
define find_max(key) {
if (modedat[key] > mx) {
mx = modedat[key];
mxkey = {key};
}
else if (modedat[key] == mx) {
list_append(mxkey, key);
}
}
define find_mode(indat)
{
% reset [file/module-scope] globals:
mx = 0, mxkey = {}, modedat = Assoc_Type[Int_Typ... |
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 ... | #Java | Java | Map<String, Integer> map = new HashMap<String, Integer>();
map.put("hello", 1);
map.put("world", 2);
map.put("!", 3);
// iterating over key-value pairs:
for (Map.Entry<String, Integer> e : map.entrySet()) {
String key = e.getKey();
Integer value = e.getValue();
System.out.println("key = " + key + ", value... |
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... | #IDL | IDL | x = [3,1,4,1,5,9]
print,mean(x) |
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... | #J | J | mean=: +/ % # |
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.... | #Ring | Ring |
# Project: Attractive Numbers
decomp = []
nump = 0
see "Attractive Numbers up to 120:" + nl
while nump < 120
decomp = []
nump = nump + 1
for i = 1 to nump
if isPrime(i) and nump%i = 0
add(decomp,i)
dec = nump/i
while dec%i = 0
add(decomp,i)
dec = dec/i
end
... |
http://rosettacode.org/wiki/Attractive_numbers | Attractive numbers | A number is an attractive number if the number of its prime factors (whether distinct or not) is also prime.
Example
The number 20, whose prime decomposition is 2 × 2 × 5, is an attractive number because the number of its prime factors (3) is also prime.
Task
Show sequence items up to 120.... | #Ruby | Ruby | require "prime"
p (1..120).select{|n| n.prime_division.sum(&:last).prime? }
|
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 ... | #zkl | zkl | var D=Time.Date;
fcn meanT(t1,t2,etc){
ts:=vm.arglist.apply(fcn(hms){
(D.toFloat(hms.split(":").xplode())*15).toRad()
});
n:=ts.len();
mt:=(ts.apply("sin").sum(0.0)/n)
.atan2(ts.apply("cos").sum(0.0)/n)
.toDeg() /15;
if(mt<0) mt+=24; //-0.204622-->23.7954
D.toHour(mt).concat(":")
... |
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 ... | #NewLISP | NewLISP | ; median.lsp
; oofoe 2012-01-25
(define (median lst)
(sort lst) ; Sorts in place.
(if (empty? lst)
nil
(letn ((n (length lst))
(h (/ (- n 1) 2)))
(if (zero? (mod n 2))
(div (add (lst h) (lst (+ h 1))) 2)
(lst h))
)))
(define (test lst) (printl... |
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... | #Octave | Octave |
A = mean(list); % arithmetic mean
G = mean(list,'g'); % geometric mean
H = mean(list,'a'); % harmonic mean
|
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.... | #zkl | zkl | // The magic number is 269696, so, starting about its square root,
// find the first integer that, when squared, its last six digits are the magic number.
// The last digits are found with modulo, represented here by the % symbol
const N=269696; [500..].filter1(fcn(n){ n*n%0d1_000_000 == 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) ... | #Haskell | Haskell |
isMatching :: String -> Bool
isMatching = null . foldl aut []
where
aut ('[':s) ']' = s
-- aut ('{':s) '}' = s -- automaton could be extended
aut s x = x:s
|
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file | Append a record to the end of a text file | Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment.
This feature is most useful in the case of log files,... | #Racket | Racket |
#lang racket
(define sample1
'("jsmith" "x" 1001 1000
("Joe Smith" "Room 1007" "(234)555-8917" "(234)555-0077" "jsmith@rosettacode.org")
"/home/jsmith" "/bin/bash"))
(define sample2
'("jdoe" "x" 1002 1000
("Jane Doe" "Room 1004" "(234)555-8914" "(234)555-0044" "jdoe@rosettacode.org")
"/home/jd... |
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,... | #Raku | Raku | class record {
has $.name;
has $.password;
has $.UID;
has $.GID;
has $.fullname;
has $.office;
has $.extension;
has $.homephone;
has $.email;
has $.directory;
has $.shell;
method gecos { join ',', $.fullname, $.office, $.extension, $.homephone, $.email }
method gi... |
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... | #ColdFusion | ColdFusion | <cfset myHash = structNew()>
<cfset myHash.key1 = "foo">
<cfset myHash["key2"] = "bar">
<cfset myHash.put("key3","java-style")> |
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
| #Pascal | Pascal | program AntiPrimes;
{$IFdef FPC}
{$MOde Delphi}
{$IFEND}
function getFactorCnt(n:NativeUint):NativeUint;
var
divi,quot,pot,lmt : NativeUint;
begin
result := 1;
divi := 1;
lmt := trunc(sqrt(n));
while divi < n do
Begin
inc(divi);
pot := 0;
repeat
quot := n div divi;
if n <> quot*di... |
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.
| #UNIX_Shell | UNIX Shell | assert() {
if test ! $1; then
[[ $2 ]] && echo "$2" >&2
exit 1
fi
}
x=42
assert "$x -eq 42" "that's not the answer"
((x--))
assert "$x -eq 42" "that's not the answer"
echo "won't get here" |
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.
| #Vala | Vala | int a = 42;
int b = 33;
assert (a == 42);
assert (b == 42); // will break the program with "assertion failed" 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.
| #VBA | VBA | Sub test()
Dim a As Integer
a = 41
Debug.Assert a = 42
End Sub |
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.