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/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... | #Go | Go | package main
import (
"fmt"
"math"
)
func main() {
sum, sumr, prod := 0., 0., 1.
for n := 1.; n <= 10; n++ {
sum += n
sumr += 1 / n
prod *= n
}
a, g, h := sum/10, math.Pow(prod, .1), 10/sumr
fmt.Println("A:", a, "G:", g, "H:", h)
fmt.Println("A >= G >= H:", a ... |
http://rosettacode.org/wiki/Balanced_ternary | Balanced ternary | Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1.
Examples
Decimal 11 = 32 + 31 − 30, thus it can be written as "++−"
Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0"
... | #Lua | Lua | function to_bt(n)
local d = { '0', '+', '-' }
local v = { 0, 1, -1 }
local b = ""
while n ~= 0 do
local r = n % 3
if r < 0 then
r = r + 3
end
b = b .. d[r + 1]
n = n - v[r + 1]
n = math.floor(n / 3)
end
return b:reverse()
end
... |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p.... | #PILOT | PILOT | Remark:Lines identified as "remarks" are intended for the human reader, and will be ignored by the machine.
Remark:A "compute" instruction gives a value to a variable.
Remark:We begin by making the variable n equal to 2.
Compute:n = 2
Remark:Lines beginning with asterisks are labels. We can instruct the machine to "jum... |
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.... | #Plain_English | Plain English | To run:
Start up.
Put 1 into a number.
Loop.
Divide the number times the number by 1000000 giving a quotient and a remainder.
If the remainder is 269696, break.
Bump the number.
Repeat.
Write "The answer is " then the number on the console.
Wait for the escape key.
Shut down. |
http://rosettacode.org/wiki/Approximate_equality | Approximate equality | Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the
difference in floating point calculations between different language implementations becomes significant.
For example, a difference between 32 bit and 64 bit floating point calculations may appear by
about the 8t... | #Delphi | Delphi |
program Approximate_Equality;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Math;
const
EPSILON: Double = 1E-18;
procedure Test(a, b: Double; Expected: Boolean);
var
result: Boolean;
const
STATUS: array[Boolean] of string = ('FAIL', 'OK');
begin
result := SameValue(a, b, EPSILON);
Write(a, ' '... |
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) ... | #C.2B.2B | C++ | #include <algorithm>
#include <iostream>
#include <string>
std::string generate(int n, char left = '[', char right = ']')
{
std::string str(std::string(n, left) + std::string(n, right));
std::random_shuffle(str.begin(), str.end());
return str;
}
bool balanced(const std::string &str, char left = '[', cha... |
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,... | #Action.21 | Action! | PROC CreateLog(CHAR ARRAY fname)
CHAR ARRAY header="account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell"
BYTE dev=[1]
Close(dev)
Open(dev,fname,8)
PrintDE(dev,header)
Close(dev)
RETURN
PROC AppendLog(CHAR ARRAY fname,line)
BYTE dev=[1]
Close(dev)
Open(dev,fname,9)
... |
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... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */
/* program hashmap64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../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... | #E | E | #!/usr/bin/env rune
pragma.syntax("0.9")
def pi := (-1.0).acos()
def makeEPainter := <unsafe:com.zooko.tray.makeEPainter>
def colors := <awt:makeColor>
# --------------------------------------------------------------
# --- Definitions
/** Execute 'task' repeatedly as long 'indicator' is unresolved. */
def doWhile... |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #C.2B.2B | C++ | #include <cassert> // assert.h also works
int main()
{
int a;
// ... input or change a here
assert(a == 42); // Aborts program if a is not 42, unless the NDEBUG macro was defined
// when including <cassert>, in which case it has no effect
} |
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.
| #Clojure | Clojure |
(let [i 42]
(assert (= i 42)))
|
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Common_Lisp | Common Lisp | (let ((x 42))
(assert (and (integerp x) (= 42 x)) (x))) |
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.
| #6502_Assembly | 6502 Assembly | define SRC_LO $00
define SRC_HI $01
define DEST_LO $02
define DEST_HI $03
define temp $04 ;temp storage used by foo
;some prep work since easy6502 doesn't allow you to define arbitrary bytes before runtime.
SET_TABLE:
TXA
STA $1000,X
INX
BNE SET_TABLE
;stores the identity table at memory address $1000-$10FF... |
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.
| #68000_Assembly | 68000 Assembly | LEA MyArray,A0
MOVE.W #(MyArray_End-MyArray)-1,D7 ;Len(MyArray)-1
MOVEQ #0,D0 ;sanitize D0-D2 to ensure nothing from any previous work will affect our math.
MOVEQ #0,D1
MOVEQ #0,D2
loop:
MOVE.B (A0),D0
MOVE.B D0,D1
MOVE.B D0,D2
MULU D1,D2
MOVE.B D2,(A0)+
dbra d7,loop
jmp * ;halt the CPU
MyArray:
DC.B 1,2,3,4... |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat... | #K | K | mode: {(?x)@&n=|/n:#:'=x}
mode 1 1 1 1 2 2 2 3 3 3 3 4 4 3 2 4 4 4
3 4 |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat... | #Kotlin | Kotlin | fun <T> modeOf(a: Array<T>) {
val sortedByFreq = a.groupBy { it }.entries.sortedByDescending { it.value.size }
val maxFreq = sortedByFreq.first().value.size
val modes = sortedByFreq.takeWhile { it.value.size == maxFreq }
if (modes.size == 1)
println("The mode of the collection is ${modes.first().... |
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 ... | #ATS | ATS | ; Create an associative array
obj := Object("red", 0xFF0000, "blue", 0x0000FF, "green", 0x00FF00)
enum := obj._NewEnum()
While enum[key, value]
t .= key "=" value "`n"
MsgBox % t |
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 ... | #AutoHotkey | AutoHotkey | ; Create an associative array
obj := Object("red", 0xFF0000, "blue", 0x0000FF, "green", 0x00FF00)
enum := obj._NewEnum()
While enum[key, value]
t .= key "=" value "`n"
MsgBox % t |
http://rosettacode.org/wiki/Apply_a_digital_filter_(direct_form_II_transposed) | Apply a digital filter (direct form II transposed) | Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [1]
Task
Filt... | #C | C |
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
#define MAX_LEN 1000
typedef struct{
float* values;
int size;
}vector;
vector extractVector(char* str){
vector coeff;
int i=0,count = 1;
char* token;
while(str[i]!=00){
if(str[i++]==' ')
count++;
}
coeff.values = (float*)malloc(count*sizeo... |
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... | #bc | bc | define m(a[], n) {
auto i, s
for (i = 0; i < n; i++) {
s += a[i]
}
return(s / n)
} |
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... | #Befunge | Befunge | &:0\:!v!:-1<
@./\$_\&+\^ |
http://rosettacode.org/wiki/Associative_array/Merging | Associative array/Merging | Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Merge these into a new associativ... | #Icon_and_Unicon | Icon and Unicon | procedure main()
local base, update, master, f, k
base := table()
base["name"] := "Rocket Skates"
base["price"] := 12.75
base["color"] := "yellow"
update := table()
update["price"] := 15.25
update["color"] := "red"
update["year"] := 1974
master := table()
every k := key... |
http://rosettacode.org/wiki/Associative_array/Merging | Associative array/Merging | Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Merge these into a new associativ... | #J | J |
merge=: ,. NB. use: update merge original
compress=: #"1~ ~:@:keys
keys=: {.
values=: {:
get=: [: > ((i.~ keys)~ <)~ { values@:] NB. key get (associative array)
pair=: [: |: <;._2;._2
|
http://rosettacode.org/wiki/Average_loop_length | Average loop length | Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t... | #Java | Java | import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class AverageLoopLength {
private static final int N = 100000;
//analytical(n) = sum_(i=1)^n (n!/(n-i)!/n**i)
private static double analytical(int n) {
double[] factorial = new double[n + 1];
double[] power... |
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an avera... | #R | R | #concat concatenates the new values to the existing vector of values, then discards any values that are too old.
lastvalues <- local(
{
values <- c();
function(x, len)
{
values <<- c(values, x);
lenv <- length(values);
if(lenv > len) values <<- values[(len-lenv):-1]
values
}
})
... |
http://rosettacode.org/wiki/Attractive_numbers | Attractive numbers | A number is an attractive number if the number of its prime factors (whether distinct or not) is also prime.
Example
The number 20, whose prime decomposition is 2 × 2 × 5, is an attractive number because the number of its prime factors (3) is also prime.
Task
Show sequence items up to 120.... | #F.23 | F# | // attractive_numbers.fsx
// taken from Primality by trial division
let rec primes =
let next_state s = Some(s, s + 2)
Seq.cache
(Seq.append
(seq[ 2; 3; 5 ])
(Seq.unfold next_state 7
|> Seq.filter is_prime))
and is_prime number =
let rec is_prime_core number curre... |
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 ... | #jq | jq | # input: array of "h:m:s"
def mean_time_of_day:
def pi: 4 * (1|atan);
def to_radians: pi * . /(12*60*60);
def from_radians: (. * 12*60*60) / pi;
def secs2time: # produce "hh:mm:ss" string
def pad: tostring | (2 - length) * "0" + .;
"\(./60/60 % 24 | pad):\(./60 % 60 | pad):\(. % 60 | pad)";
def... |
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 ... | #Julia | Julia | using Statistics
function meantime(times::Array, dlm::String=":")
c = π / (12 * 60 * 60)
a = map(x -> parse.(Int, x), split.(times, dlm))
ϕ = collect(3600t[1] + 60t[2] + t[3] for t in a)
d = angle(mean(exp.(c * im * ϕ))) / 2π # days
if d < 0 d += 1 end
# Convert to h:m:s
h = trunc(Int, d *... |
http://rosettacode.org/wiki/AVL_tree | AVL tree |
This page uses content from Wikipedia. The original article was at AVL tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In computer science, an AVL tree is a self-balancing binary search tree.... | #Kotlin | Kotlin | class AvlTree {
private var root: Node? = null
private class Node(var key: Int, var parent: Node?) {
var balance: Int = 0
var left : Node? = null
var right: Node? = null
}
fun insert(key: Int): Boolean {
if (root == null)
root = Node(key, null)
els... |
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 ... | #J | J | avgAngleD=: 360|(_1 { [: (**|)&.+.@(+/ % #)&.(*.inv) 1,.])&.(1r180p1&*) |
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 ... | #Java | Java | import java.util.Arrays;
public class AverageMeanAngle {
public static void main(String[] args) {
printAverageAngle(350.0, 10.0);
printAverageAngle(90.0, 180.0, 270.0, 360.0);
printAverageAngle(10.0, 20.0, 30.0);
printAverageAngle(370.0);
printAverageAngle(180.0);
}
... |
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 ... | #D | D | import std.stdio, std.algorithm;
T median(T)(T[] nums) pure nothrow {
nums.sort();
if (nums.length & 1)
return nums[$ / 2];
else
return (nums[$ / 2 - 1] + nums[$ / 2]) / 2.0;
}
void main() {
auto a1 = [5.1, 2.6, 6.2, 8.8, 4.6, 4.1];
writeln("Even median: ", a1.median);
auto... |
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... | #Groovy | Groovy | def arithMean = { list ->
list == null \
? null \
: list.empty \
? 0 \
: list.sum() / list.size()
}
def geomMean = { list ->
list == null \
? null \
: list.empty \
? 1 \
: list.inject(1) { prod, item -> prod*item } ** (1 / list.si... |
http://rosettacode.org/wiki/Balanced_ternary | Balanced ternary | Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1.
Examples
Decimal 11 = 32 + 31 − 30, thus it can be written as "++−"
Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0"
... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | frombt = FromDigits[StringCases[#, {"+" -> 1, "-" -> -1, "0" -> 0}],
3] &;
tobt = If[Quotient[#, 3, -1] == 0,
"", #0@Quotient[#, 3, -1]] <> (Mod[#,
3, -1] /. {1 -> "+", -1 -> "-", 0 -> "0"}) &;
btnegate = StringReplace[#, {"+" -> "-", "-" -> "+"}] &;
btadd = StringReplace[
StringJoin[
Fold[S... |
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.... | #PL.2FI | PL/I |
/* Babbage might have used a difference engine to compute squares. */
/* The algorithm used here uses only additions to form successive squares. */
/* Since there is no guarantee that the final square will not exceed a */
/* 32-bit integer word, modulus is formed to limit the magnitude of the */
/* squ... |
http://rosettacode.org/wiki/Approximate_equality | Approximate equality | Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the
difference in floating point calculations between different language implementations becomes significant.
For example, a difference between 32 bit and 64 bit floating point calculations may appear by
about the 8t... | #Factor | Factor | USING: formatting generalizations kernel math math.functions ;
100000000000000.01 100000000000000.011
100.01 100.011
10000000000000.001 10000.0 /f 1000000000.0000001000
0.001 0.0010000001
0.000000000000000000000101 0.0
2 sqrt dup * 2.... |
http://rosettacode.org/wiki/Approximate_equality | Approximate equality | Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the
difference in floating point calculations between different language implementations becomes significant.
For example, a difference between 32 bit and 64 bit floating point calculations may appear by
about the 8t... | #Forth | Forth |
: test-f~ ( f1 f2 -- )
1e-18 \ epsilon
f~ \ AproximateEqual
if ." True" else ." False" then
;
|
http://rosettacode.org/wiki/Approximate_equality | Approximate equality | Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the
difference in floating point calculations between different language implementations becomes significant.
For example, a difference between 32 bit and 64 bit floating point calculations may appear by
about the 8t... | #Fortran | Fortran | program main
implicit none
integer :: i
double precision, allocatable :: vals(:)
vals = [ 100000000000000.01d0, 100000000000000.011d0, &
& 100.01d0, 100.011d0, &
& 10000000000000.001d0/10000d0, 1000000000.0000001000d0, &
... |
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) ... | #Ceylon | Ceylon | import com.vasileff.ceylon.random.api {
platformRandom,
Random
}
"""Run the example code for Rosetta Code ["Balanced brackets" task] (http://rosettacode.org/wiki/Balanced_brackets)."""
shared void run() {
value rnd = platformRandom();
for (len in (0..10)) {
value c = generate(rnd, len);
... |
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,... | #Ada | Ada |
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Strings.Bounded;
procedure Main is
package data_string is new Ada.Strings.Bounded.Generic_Bounded_Length(80);
use data_string;
type GCOSE_Rec is record
Full_Name : Bounded_String;
Office : Bounde... |
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... | #ActionScript | ActionScript | var map:Object = {key1: "value1", key2: "value2"};
trace(map['key1']); // outputs "value1"
// Dot notation can also be used
trace(map.key2); // outputs "value2"
// More keys and values can then be added
map['key3'] = "value3";
trace(map['key3']); // outputs "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
| #11l | 11l | V max_divisors = 0
V c = 0
V n = 1
L
V divisors = 1
L(i) 1 .. n I/ 2
I n % i == 0
divisors++
I divisors > max_divisors
max_divisors = divisors
print(n, end' ‘ ’)
c++
I c == 20
L.break
n++ |
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... | #Erlang | Erlang | [1,2,3,4,5,6,7,8,9,10] = 55
[1,3,4,7,2,5,13,8,4,8] = 55
[6,13,6,0,8,3,1,0,8,10] = 55
[8,0,9,0,5,9,8,8,8,0] = 55
[8,11,9,3,1,12,8,0,0,3] = 55
[13,4,3,8,1,5,10,4,5,2] = 55
[6,6,9,5,6,5,6,1,5,6] = 55
[20,7,5,0,5,0,0,10,8,0] = 55
[2,10,0,10,0,4,8,3,15,3] = 55
[0,11,7,0,4,16,7,0,10,0] = 55
|
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... | #Euphoria | Euphoria | function move(sequence s, integer amount, integer src, integer dest)
if src < 1 or src > length(s) or dest < 1 or dest > length(s) or amount < 0 then
return -1
else
if src != dest and amount then
if amount > s[src] then
amount = s[src]
end if
s... |
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.
| #Component_Pascal | Component Pascal |
MODULE Assertions;
VAR
x: INTEGER;
PROCEDURE DoIt*;
BEGIN
x := 41;
ASSERT(x = 42);
END DoIt;
END Assertions.
Assertions.DoIt
|
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.
| #Crystal | Crystal | class AssertionError < Exception
end
def assert(predicate : Bool, msg = "The asserted condition was false")
raise AssertionError.new(msg) unless predicate
end
assert(12 == 42, "It appears that 12 doesn't equal 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.
| #D | D | import std.exception: enforce;
int foo(in bool condition) pure nothrow
in {
// Assertions are used in contract programming.
assert(condition);
} out(result) {
assert(result > 0);
} body {
if (condition)
return 42;
// assert(false) is never stripped from the code, it generates an
// e... |
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.
| #8th | 8th |
[ 1 , 2, 3 ]
' n:sqr
a:map
|
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.
| #ACL2 | ACL2 | (defun apply-to-each (xs)
(if (endp xs)
nil
(cons (fn-to-apply (first xs))
(sq-each (rest xs)))))
(defun fn-to-apply (x)
(* x x))
|
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... | #Lasso | Lasso | define getmode(a::array)::array => {
local(mmap = map, maxv = 0, modes = array)
// store counts
with e in #a do => { #mmap->keys >> #e ? #mmap->find(#e) += 1 | #mmap->insert(#e = 1) }
// get max value
with e in #mmap->keys do => { #mmap->find(#e) > #maxv ? #maxv = #mmap->find(#e) }
// get modes with max value
wi... |
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... | #Liberty_BASIC | Liberty BASIC |
a$ = "1 3 6 6 6 6 7 7 12 12 17"
b$ = "1 2 4 4 1"
print "Modes for ";a$
print modes$(a$)
print "Modes for ";b$
print modes$(b$)
function modes$(a$)
'get array size
n=0
t$ = "*"
while t$<>""
n=n+1
t$=word$(a$, n)
'print n, t$
wend
n=n-1
'print "n=", n
'dim array
'read... |
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 ... | #AWK | AWK | BEGIN {
a["hello"] = 1
a["world"] = 2
a["!"] = 3
# iterate over keys, undefined order
for(key in a) {
print key, a[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 ... | #Babel | Babel | births (('Washington' 1732) ('Lincoln' 1809) ('Roosevelt' 1882) ('Kennedy' 1917)) ls2map ! < |
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... | #C.23 | C# | using System;
namespace ApplyDigitalFilter {
class Program {
private static double[] Filter(double[] a, double[] b, double[] signal) {
double[] result = new double[signal.Length];
for (int i = 0; i < signal.Length; ++i) {
double tmp = 0.0;
for (int j... |
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... | #blz | blz |
:mean(vec)
vec.fold_left(0, (x, y -> x + y)) / vec.length()
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... | #Bracmat | Bracmat |
(mean1=
sum length n
. 0:?sum:?length
& whl
' ( !arg:%?n ?arg
& 1+!length:?length
& !n+!sum:?sum
)
& !sum*!length^-1
);
(mean2=
sum length n
. 0:?sum:?length
& !arg
: ?
( #%@?n
& 1+!length:?length
& !n+!sum:?sum
& ~
... |
http://rosettacode.org/wiki/Associative_array/Merging | Associative array/Merging | Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Merge these into a new associativ... | #Java | Java | import java.util.*;
class MergeMaps {
public static void main(String[] args) {
Map<String, Object> base = new HashMap<>();
base.put("name", "Rocket Skates");
base.put("price", 12.75);
base.put("color", "yellow");
Map<String, Object> update = new HashMap<>();
update.... |
http://rosettacode.org/wiki/Associative_array/Merging | Associative array/Merging | Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Merge these into a new associativ... | #JavaScript | JavaScript | (() => {
'use strict';
console.log(JSON.stringify(
Object.assign({}, // Fresh dictionary.
{ // Base.
"name": "Rocket Skates",
"price": 12.75,
"color": "yellow"
}, { // Update.
"price": 15.25,
"color... |
http://rosettacode.org/wiki/Average_loop_length | Average loop length | Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t... | #Julia | Julia | using Printf
analytical(n::Integer) = sum(factorial(n) / big(n) ^ i / factorial(n - i) for i = 1:n)
function test(n::Integer, times::Integer = 1000000)
c = 0
for i = range(0, times)
x, bits = 1, 0
while (bits & x) == 0
c += 1
bits |= x
x = 1 << rand(0:(n -... |
http://rosettacode.org/wiki/Average_loop_length | Average loop length | Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t... | #Kotlin | Kotlin | const val NMAX = 20
const val TESTS = 1000000
val rand = java.util.Random()
fun avg(n: Int): Double {
var sum = 0
for (t in 0 until TESTS) {
val v = BooleanArray(NMAX)
var x = 0
while (!v[x]) {
v[x] = true
sum++
x = rand.nextInt(n)
}
}
... |
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an avera... | #Racket | Racket | #lang racket
(require data/queue)
(define (simple-moving-average period)
(define queue (make-queue))
(define sum 0.0)
(lambda (x)
(enqueue! queue x)
(set! sum (+ sum x))
(when (> (queue-length queue) period)
(set! sum (- sum (dequeue! queue))))
(/ sum (queue-length queue))))
;; Tests... |
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.... | #Factor | Factor | USING: formatting grouping io math.primes math.primes.factors
math.ranges sequences ;
"The attractive numbers up to and including 120 are:" print
120 [1,b] [ factors length prime? ] filter 20 <groups>
[ [ "%4d" printf ] each nl ] each |
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.... | #Fortran | Fortran |
program attractive_numbers
use iso_fortran_env, only: output_unit
implicit none
integer, parameter :: maximum=120, line_break=20
integer :: i, counter
write(output_unit,'(A,x,I0,x,A)') "The attractive numbers up to and including", maximum, "are:"
counter = 0
do i = 1, ma... |
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 ... | #Kotlin | Kotlin | // version 1.0.6
fun meanAngle(angles: DoubleArray): Double {
val sinSum = angles.sumByDouble { Math.sin(it * Math.PI / 180.0) }
val cosSum = angles.sumByDouble { Math.cos(it * Math.PI / 180.0) }
return Math.atan2(sinSum / angles.size, cosSum / angles.size) * 180.0 / Math.PI
}
/* time string assumed t... |
http://rosettacode.org/wiki/AVL_tree | AVL tree |
This page uses content from Wikipedia. The original article was at AVL tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In computer science, an AVL tree is a self-balancing binary search tree.... | #Lua | Lua | AVL={balance=0}
AVL.__mt={__index = AVL}
function AVL:new(list)
local o={}
setmetatable(o, AVL.__mt)
for _,v in ipairs(list or {}) do
o=o:insert(v)
end
return o
end
function AVL:rebalance()
local rotated=false
if self.balance>1 then
if self.right.balance<0 then
self.right, self.right... |
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 ... | #JavaScript | JavaScript | function sum(a) {
var s = 0;
for (var i = 0; i < a.length; i++) s += a[i];
return s;
}
function degToRad(a) {
return Math.PI / 180 * a;
}
function meanAngleDeg(a) {
return 180 / Math.PI * Math.atan2(
sum(a.map(degToRad).map(Math.sin)) / a.length,
sum(a.map(degToRad).map(Math.cos... |
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 ... | #Delphi | Delphi | program AveragesMedian;
{$APPTYPE CONSOLE}
uses Generics.Collections, Types;
function Median(aArray: TDoubleDynArray): Double;
var
lMiddleIndex: Integer;
begin
TArray.Sort<Double>(aArray);
lMiddleIndex := Length(aArray) div 2;
if Odd(Length(aArray)) then
Result := aArray[lMiddleIndex]
else
Res... |
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... | #Haskell | Haskell | import Data.List (genericLength)
import Control.Monad (zipWithM_)
mean :: Double -> [Double] -> Double
mean 0 xs = product xs ** (1 / genericLength xs)
mean p xs = (1 / genericLength xs * sum (map (** p) xs)) ** (1/p)
main = do
let ms = zipWith ((. flip mean [1..10]). (,)) "agh" [1, 0, -1]
mapM_ (\(t,m) -> putS... |
http://rosettacode.org/wiki/Balanced_ternary | Balanced ternary | Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1.
Examples
Decimal 11 = 32 + 31 − 30, thus it can be written as "++−"
Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0"
... | #.D0.9C.D0.9A-61.2F52 | МК-61/52 | ЗН П2 Вx |x| П0 0 П3 П4 1 П5
ИП0 /-/ x<0 80
ИП0 ^ ^ 3 / [x] П0 3 * - П1
ИП3 x#0 54
ИП1 x=0 38 ИП2 ПП 88 0 П3 БП 10
ИП1 1 - x=0 49 ИП2 /-/ ПП 88 БП 10
0 ПП 88 БП 10
ИП1 x=0 62 0 ПП 88 БП 10
ИП1 1 - x=0 72 ИП2 ПП 88 БП 10
ИП2 /-/ ПП 88 1 П3 БП 10
ИП3 x#0 86 ИП2 ПП 88 ИП4 С/П
8 + ИП5 * ИП4 + П4 ИП5 1 ... |
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.... | #PowerShell | PowerShell |
###########################################################################################
#
# Definitions:
#
# Lines that begin with the "#" symbol are comments: they will be ignored by the machine.
#
# -----------------------------------------------------------------------------------------
#
# While
#
# Run... |
http://rosettacode.org/wiki/Approximate_equality | Approximate equality | Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the
difference in floating point calculations between different language implementations becomes significant.
For example, a difference between 32 bit and 64 bit floating point calculations may appear by
about the 8t... | #FreeBASIC | FreeBASIC | #include "string.bi"
Dim Shared As Double epsilon = 1
Sub eq_approx(a As Double,b As Double)
Dim As Boolean tmp = Abs(a - b) < epsilon
Print Using "& & &";tmp;a;b
End Sub
While (1 + epsilon <> 1)
epsilon /= 2
Wend
Print "epsilon = "; Format(epsilon, "0.000000000000000e-00")
Print
eq_approx(100000000... |
http://rosettacode.org/wiki/Approximate_equality | Approximate equality | Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the
difference in floating point calculations between different language implementations becomes significant.
For example, a difference between 32 bit and 64 bit floating point calculations may appear by
about the 8t... | #Go | Go | package main
import (
"fmt"
"log"
"math/big"
)
func max(a, b *big.Float) *big.Float {
if a.Cmp(b) > 0 {
return a
}
return b
}
func isClose(a, b *big.Float) bool {
relTol := big.NewFloat(1e-9) // same as default for Python's math.isclose() function
t := new(big.Float)
t.... |
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) ... | #Clojure | Clojure | (defn gen-brackets [n]
(->> (concat (repeat n \[) (repeat n \]))
shuffle
(apply str ,)))
(defn balanced? [s]
(loop [[first & coll] (seq s)
stack '()]
(if first
(if (= first \[)
(recur coll (conj stack \[))
(when (= (peek stack) \[)
(recur coll (pop stack))))
(zero? (count stac... |
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,... | #AWK | AWK |
# syntax: GAWK -f APPEND_A_RECORD_TO_THE_END_OF_A_TEXT_FILE.AWK
BEGIN {
fn = "\\etc\\passwd"
# create and populate file
print("account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell") >fn
print("jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettaco... |
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... | #Ada | Ada | with Ada.Containers.Ordered_Maps;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO;
procedure Associative_Array is
-- Instantiate the generic package Ada.Containers.Ordered_Maps
package Associative_Int is new Ada.Containers.Ordered_Maps(Unbounded_String, Integer);
use Associative_I... |
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
| #8086_Assembly | 8086 Assembly | puts: equ 9 ; MS-DOS print string syscall
amount: equ 20 ; Amount of antiprimes to find
cpu 8086
org 100h
xor si,si ; SI = current number
xor cx,cx ; CH = max # of factors, CL = # of antiprimes
cand: inc si
mov di,si ; DI = maximum factor to test
shr di,1
mov bp,1 ; BP = current candidate
xor bl,bl ; BL = fa... |
http://rosettacode.org/wiki/Atomic_updates | Atomic updates |
Task
Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to:
get the current value of any bucket
remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the t... | #F.23 | F# |
open System.Threading
type Buckets(n) =
let rand = System.Random()
let mutex = Array.init n (fun _ -> new Mutex())
let bucket = Array.init n (fun _ -> 100)
member this.Count = n
member this.Item n = bucket.[n]
member private this.Lock is k =
let is = Seq.sort is
for i in is do
mutex.... |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Dart | Dart |
main() {
var i = 42;
assert( i == 42 );
}
|
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Delphi | Delphi | Assert(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.
| #DWScript | DWScript | Assert(a = 42, 'Not 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.
| #ActionScript | ActionScript | package
{
public class ArrayCallback
{
public function main():void
{
var nums:Array = new Array(1, 2, 3);
nums.map(function(n:Number, index:int, arr:Array):void { trace(n * n * n); });
// You can also pass a function reference
nums.map(cube);
... |
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... | #Lua | Lua | function mode(tbl) -- returns table of modes and count
assert(type(tbl) == 'table')
local counts = { }
for _, val in pairs(tbl) do
-- see http://lua-users.org/wiki/TernaryOperator
counts[val] = counts[val] and counts[val] + 1 or 1
end
local modes = { }
local modeCount = 0
for key, val in pairs(counts) do
i... |
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 ... | #BaCon | BaCon | DECLARE associative ASSOC STRING
associative("abc") = "first three"
associative("mn") = "middle two"
associative("xyz") = "last three"
LOOKUP associative TO keys$ SIZE amount
FOR i = 0 TO amount - 1
PRINT keys$[i], ":", associative(keys$[i])
NEXT |
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... | #C.2B.2B | C++ | #include <vector>
#include <iostream>
using namespace std;
void Filter(const vector<float> &b, const vector<float> &a, const vector<float> &in, vector<float> &out)
{
out.resize(0);
out.resize(in.size());
for(int i=0; i < in.size(); i++)
{
float tmp = 0.;
int j=0;
out[i] = 0.f;
for(j=0; j < b.size(); j... |
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... | #Brat | Brat | mean = { list |
true? list.empty?, 0, { list.reduce(0, :+) / list.length }
}
p mean 1.to 10 #Prints 5.5 |
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... | #Burlesque | Burlesque |
blsq ) {1 2 2.718 3 3.142}av
2.372
blsq ) {}av
NaN
|
http://rosettacode.org/wiki/Associative_array/Merging | Associative array/Merging | Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Merge these into a new associativ... | #jq | jq | julia> dict1 = Dict("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow")
Dict{String,Any} with 3 entries:
"name" => "Rocket Skates"
"price" => 12.75
"color" => "yellow"
julia> dict2 = Dict("price" => 15.25, "color" => "red", "year" => 1974)
Dict{String,Any} with 3 entries:
"price" => 15.25
"yea... |
http://rosettacode.org/wiki/Associative_array/Merging | Associative array/Merging | Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Merge these into a new associativ... | #Julia | Julia | julia> dict1 = Dict("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow")
Dict{String,Any} with 3 entries:
"name" => "Rocket Skates"
"price" => 12.75
"color" => "yellow"
julia> dict2 = Dict("price" => 15.25, "color" => "red", "year" => 1974)
Dict{String,Any} with 3 entries:
"price" => 15.25
"yea... |
http://rosettacode.org/wiki/Associative_array/Merging | Associative array/Merging | Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Merge these into a new associativ... | #Kotlin | Kotlin |
fun main() {
val base = HashMap<String,String>()
val update = HashMap<String,String>()
base["name"] = "Rocket Skates"
base["price"] = "12.75"
base["color"] = "yellow"
update["price"] = "15.25"
update["color"] = "red"
update["year"] = "1974"
val merged = HashMap(base)
mer... |
http://rosettacode.org/wiki/Average_loop_length | Average loop length | Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t... | #Liberty_BASIC | Liberty BASIC |
MAXN = 20
TIMES = 10000'00
't0=time$("ms")
FOR n = 1 TO MAXN
avg = FNtest(n, TIMES)
theory = FNanalytical(n)
diff = (avg / theory - 1) * 100
PRINT n, avg, theory, using("##.####",diff); "%"
NEXT
't1=time$("ms")
'print t1-t0; " ms"
END
function FNanalytical(n)
FOR i = 1 TO n
s = s+ FNfa... |
http://rosettacode.org/wiki/Average_loop_length | Average loop length | Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t... | #Lua | Lua | function average(n, reps)
local count = 0
for r = 1, reps do
local f = {}
for i = 1, n do f[i] = math.random(n) end
local seen, x = {}, 1
while not seen[x] do
seen[x], x, count = true, f[x], count+1
end
end
return count / reps
end
function analytical(n)
local s, t = 1, 1
for i = ... |
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an avera... | #Raku | Raku | sub sma-generator (Int $P where * > 0) {
sub ($x) {
state @a = 0 xx $P;
@a.push($x).shift;
@a.sum / $P;
}
}
# Usage:
my &sma = sma-generator 3;
for 1, 2, 3, 2, 7 {
printf "append $_ --> sma = %.2f (with period 3)\n", sma $_;
} |
http://rosettacode.org/wiki/Attractive_numbers | Attractive numbers | A number is an attractive number if the number of its prime factors (whether distinct or not) is also prime.
Example
The number 20, whose prime decomposition is 2 × 2 × 5, is an attractive number because the number of its prime factors (3) is also prime.
Task
Show sequence items up to 120.... | #FreeBASIC | FreeBASIC |
Const limite = 120
Declare Function esPrimo(n As Integer) As Boolean
Declare Function ContandoFactoresPrimos(n As Integer) As Integer
Function esPrimo(n As Integer) As Boolean
If n < 2 Then Return false
If n Mod 2 = 0 Then Return n = 2
If n Mod 3 = 0 Then Return n = 3
Dim As Integer d = 5
Whil... |
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 ... | #Liberty_BASIC | Liberty BASIC |
global pi
pi = acs(-1)
Print "Average of:"
for i = 1 to 4
read t$
print t$
a=time2angle(t$)
ss=ss+sin(a)
sc=sc+cos(a)
next
a=atan2(ss,sc)
if a<0 then a=a+2*pi
print "is ";angle2time$(a)
end
data "23:00:17", "23:40:20", "00:12:45", "00:17:19"
function nn$(n)
nn$=right$("0";n, 2)
end func... |
http://rosettacode.org/wiki/AVL_tree | AVL tree |
This page uses content from Wikipedia. The original article was at AVL tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In computer science, an AVL tree is a self-balancing binary search tree.... | #Nim | Nim | #[ AVL tree adapted from Julienne Walker's presentation at
http://eternallyconfuzzled.com/tuts/datastructures/jsw_tut_avl.aspx.
Uses bounded recursive versions for insertion and deletion.
]#
type
# Objects strored in the tree must be comparable.
Comparable = concept x, y
(x == y) is bool
(x < y)... |
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 ... | #jq | jq | def pi: 4 * (1|atan);
def deg2rad: . * pi / 180;
def rad2deg: if . == null then null else . * 180 / pi end;
# Input: [x,y] (special handling of x==0)
# Output: [r, theta] where theta may be null
def to_polar:
if .[0] == 0
then [1, if .[1] > 5e-14 then pi/2 elif .[1] < -5e-14 then -pi/2 else null end]
else [... |
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 ... | #Julia | Julia | using Statistics
meandegrees(degrees) = rad2deg(atan(mean(sind.(degrees)), mean(cosd.(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 ... | #E | E | def median(list) {
def sorted := list.sort()
def count := sorted.size()
def mid1 := count // 2
def mid2 := (count - 1) // 2
if (mid1 == mid2) { # avoid inexact division
return sorted[mid1]
} else {
return (sorted[mid1] + sorted[mid2]) / 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... | #HicEst | HicEst | AGH = ALIAS( A, G, H ) ! named vector elements
AGH = (0, 1, 0)
DO i = 1, 10
A = A + i
G = G * i
H = H + 1/i
ENDDO
AGH = (A/10, G^0.1, 10/H)
WRITE(ClipBoard, Name) AGH, "Result = " // (A>=G) * (G>=H) |
http://rosettacode.org/wiki/Balanced_ternary | Balanced ternary | Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1.
Examples
Decimal 11 = 32 + 31 − 30, thus it can be written as "++−"
Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0"
... | #Nim | Nim | import strformat
import tables
type
# Trit definition.
Trit = range[-1'i8..1'i8]
# Balanced ternary number as a sequence of trits stored in little endian way.
BTernary = seq[Trit]
const
# Textual representation of trits.
Trits: array[Trit, char] = ['-', '0', '+']
# Symbolic names used for trit... |
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.