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 | response_seed stringclasses 1
value | instruction_seed stringlengths 27 14.4k | _source stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
... | #Pyret | Pyret | fun fizzbuzz(n :: NumPositive) -> String:
doc: ```For positive input which is multiples of three return 'Fizz', for the multiples of five return 'Buzz'.
For numbers which are multiples of both three and five return 'FizzBuzz'. Otherwise, return the number itself.```
ask:
| num-modulo(n, 15) == 0 then: "FizzB... | Give a code snippet in #Pyret
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz... | christopher/rosetta-code | |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third... | #Scala | Scala | for { i <- 1 to 100
r = 1 to 100 map (i % _ == 0) reduceLeft (_^_)
} println (i +" "+ (if (r) "open" else "closed")) | Give a code snippet in #Scala
There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ..... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sort_three_variables | Sort three variables |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Jsish | Jsish | #!/usr/bin/env jsish
/* Sort three variables, in Jsish. semi-colon start/end for unit test echo */
var x = 'lions, tigers, and';
var y = 'bears, oh my!';
var z = '(from the "Wizard of OZ")';
var arr = [x,y,z];
arr = arr.sort();
;'As strings, before:';
;x;
;y;
;z;
x = arr.shift();
y = arr.shift();
z = arr.shi... | Give a code snippet in #Jsish
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick so... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being ... | #C.23 | C# | using System;
using System.Linq;
public class Program
{
static void Main
{
string[] input = {"", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"};
foreach (string s in input) {
Console.WriteLine($"\"{s}\" (Length {s.Length}) " +
string.Join(", ",
... | Give a code snippet in #C.23
Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its lengt... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Dining_philosophers | Dining philosophers | The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra.
Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a rou... | #J | J | ". noun define -. CRLF NB. Fixed tacit simulation code...
simulate=.
''"_@:((<@:(1 -~ 1&({::)) 1} ])@:(([ 0 0&$@(1!:2&2)@:(((6j3 ": 9&({::)) , ':
'"_) , ' starts waiting and thinking about hunger.' ,~ 8&({::) {:: 0&({::)))@
:(<@:(6&({::) , 8&({::)) 6} ])@:((<@:((0 (0 {:: ])`(<@:(1 {:: ]))`(2 {:: ])}
])@:(3 8 2&... | Give a code snippet in #J
The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra.
Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating s... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Median_filter | Median filter | The median filter takes in the neighbourhood the median color (see Median filter)
(to test the function below, you can use these input and output solutions)
| #BBC_BASIC | BBC BASIC | INSTALL @lib$+"SORTLIB"
Sort% = FN_sortinit(0,0)
Width% = 200
Height% = 200
DIM out&(Width%-1, Height%-1)
VDU 23,22,Width%;Height%;8,16,16,128
*DISPLAY Lenagrey
OFF
REM Do the median filtering:
DIM pix&(24)
C% = 25
FOR Y% = 2 TO Height%-3
... | Give a code snippet in #BBC_BASIC
The median filter takes in the neighbourhood the median color (see Median filter)
(to test the function below, you can use these input and output solutions)
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume t... | #Euphoria | Euphoria | function int_leftrect(sequence bounds, integer n, integer func_id)
atom h, sum
h = (bounds[2]-bounds[1])/n
sum = 0
for x = bounds[1] to bounds[2]-h by h do
sum += call_func(func_id, {x})
end for
return h*sum
end function
function int_rightrect(sequence bounds, integer n, integer func_i... | Give a code snippet in #Euphoria
Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to... | christopher/rosetta-code | |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program dnsquery.s */
/************************************/
/* Constantes */
/************************************/
.equ STDIN, 0 @ Linux input console
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall END PR... | Give a code snippet in #ARM_Assembly
DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #Julia | Julia | join(sort(filter(sym -> let n=eval(sym); !(isa(n, Function) || isa(n, Type) || isa(n, Module)); end, names(Base))), ", ") | Give a code snippet in #Julia
Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrat... | #zkl | zkl | fcn toWDHMS(sec){ //-->(wk,d,h,m,s)
r,b:=List(),0;
foreach u in (T(60,60,24,7)){
sec,b=sec.divr(u); // aka divmod
r.append(b);
}
r.append(sec).reverse()
} | Give a code snippet in #zkl
Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Munchausen_numbers | Munchausen numbers | A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n.
(Munchausen is also spelled: Münchhausen.)
For instance: 3435 = 33 + 44 + 33 + 55
Task
Find all Munchausen numbers between 1 and 5000.
Also see
The OEIS entry: A046253
The ... | #BASIC | BASIC | 10 DEF FN P(X)=INT(X^X*SGN(X))
20 FOR I=0 TO 5
30 FOR J=0 TO 5
40 FOR K=0 TO 5
50 FOR L=0 TO 5
60 M=FN P(I)+FN P(J)+FN P(K)+FN P(L)
70 N=1000*I+100*J+10*K+L
80 IF M=N AND M>0 THEN PRINT M
90 NEXT L
100 NEXT K
110 NEXT J
120 NEXT I | Give a code snippet in #BASIC
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n.
(Munchausen is also spelled: Münchhausen.)
For instance: 3435 = 33 + 44 + 33 + 55
Task
Find all Munchausen numbers between 1 and 5000.
Also see
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/15_puzzle_game | 15 puzzle game |
Task
Implement the Fifteen Puzzle Game.
The 15-puzzle is also known as:
Fifteen Puzzle
Gem Puzzle
Boss Puzzle
Game of Fifteen
Mystic Square
14-15 Puzzle
and some others.
Related Tasks
15 Puzzle Solver
16 Puzzle Game
| #JavaScript | JavaScript |
var board, zx, zy, clicks, possibles, clickCounter, oldzx = -1, oldzy = -1;
function getPossibles() {
var ii, jj, cx = [-1, 0, 1, 0], cy = [0, -1, 0, 1];
possibles = [];
for( var i = 0; i < 4; i++ ) {
ii = zx + cx[i]; jj = zy + cy[i];
if( ii < 0 || ii > 3 || jj < 0 || jj > 3 ) continue;
... | Give a code snippet in #JavaScript
Task
Implement the Fifteen Puzzle Game.
The 15-puzzle is also known as:
Fifteen Puzzle
Gem Puzzle
Boss Puzzle
Game of Fifteen
Mystic Square
14-15 Puzzle
and some others.
Related Tasks
15 Puzzle Solver
16 Puzzle Game
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pen... | #D | D | import std.stdio, std.bigint;
auto changes(int amount, int[] coins) {
auto ways = new BigInt[amount + 1];
ways[0] = 1;
foreach (coin; coins)
foreach (j; coin .. amount + 1)
ways[j] += ways[j - coin];
return ways[$ - 1];
}
void main() {
changes( 1_00, [25, 10, 5, 1]).writeln... | Give a code snippet in #D
There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pen... | christopher/rosetta-code | |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #PicoLisp | PicoLisp | (setq Str1 "12345678")
(setq Str1 (pack Str1 "9!"))
(println Str1) | Give a code snippet in #PicoLisp
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operatio... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Last_letter-first_letter | Last letter-first letter | A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the ga... | #REXX | REXX | /*REXX program finds the longest path of word's last─letter ───► first─letter. */
@='audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon cresselia croagunk darmanitan',
'deino emboar emolga exeggcute gabite girafarig gulpin haxorus heatmor heatran ivysaur jellicent',
'jumpluff kangask... | Give a code snippet in #REXX
A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the cat... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A... | #Lasso | Lasso |
[
var(
'a' = array(
'John'
,'Bob'
,'Mary'
,'Serena'
)
,'b' = array
);
$b->insert( 'Jim' ); // Alternate method of populating array
$b->insert( 'Mary' );
$b->insert( 'John' );
$b->insert( 'Bob' );
$a->sort( true ); // arrays must be sorted (true = ascending) for difference... | Give a code snippet in #Lasso
Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\dis... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Multifactorial | Multifactorial | The factorial of a number, written as
n
!
{\displaystyle n!}
, is defined as
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\displaystyle n!=n(n-1)(n-2)...(2)(1)}
.
Multifactorials generalize factorials as follows:
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\displaystyle n!=n(n-1)(n-2)...(2)(... | #C | C |
/* Include statements and constant definitions */
#include <stdio.h>
#define HIGHEST_DEGREE 5
#define LARGEST_NUMBER 10
/* Recursive implementation of multifactorial function */
int multifact(int n, int deg){
return n <= deg ? n : n * multifact(n - deg, deg);
}
/* Iterative implementation of multifactorial fun... | Give a code snippet in #C
The factorial of a number, written as
n
!
{\displaystyle n!}
, is defined as
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\displaystyle n!=n(n-1)(n-2)...(2)(1)}
.
Multifactorials generalize factorials as follows:
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\display... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Reverse_a_string | Reverse a string | Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
... | #Zoea_Visual | Zoea Visual |
var s = "socat".*;
std.mem.reverse(u8, &s);
| Give a code snippet in #Zoea_Visual
Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The ba... | #Objeck | Objeck | stack := IntStack->New();
stack->Push(13);
stack->Push(7);
(stack->Pop() + stack->Pop())->PrintLine();
stack->IsEmpty()->PrintLine(); | Give a code snippet in #Objeck
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is a... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Repeat_a_string | Repeat a string | Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****").
Other tasks re... | #Brainf.2A.2A.2A | Brainf*** | +++++ +++++ init first as 10 counter
[-> +++++ +++++<] we add 10 to second each loopround
Now we want to loop 5 times to follow std
+++++
[-> ++++ . ----- -- . +++<] print h and a each loop
and a newline because I'm kind and it looks good
+++++ +++++ +++ . --- . | Give a code snippet in #Brainf.2A.2A.2A
Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-cha... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Repeat_a_string | Repeat a string | Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****").
Other tasks re... | #IS-BASIC | IS-BASIC | 10 PRINT STRING$("ha",5)
100 DEF STRING$(S$,N)
105 LET ST$=""
110 FOR I=1 TO N
120 LET ST$=ST$&S$
130 NEXT
140 LET STRING$=ST$
150 END DEF | Give a code snippet in #IS-BASIC
Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Random_number_generator_(included) | Random number generator (included) | The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not t... | #UNIX_Shell | UNIX Shell | echo $RANDOM | Give a code snippet in #UNIX_Shell
The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the alg... | christopher/rosetta-code | |
http://rosettacode.org/wiki/HTTPS | HTTPS | Task
Send a GET request to obtain the resource located at the URL "https://www.w3.org/", then print it to the console.
Checking the host certificate for validity is recommended.
Do not authenticate. That is the subject of other tasks.
Readers may wish to contrast with the HTTP Request task, and also the task on HTT... | #Ol | Ol |
(import (lib curl))
(define curl (make-curl))
(curl 'url "https://www.w3.org/")
(curl 'perform)
| Give a code snippet in #Ol
Task
Send a GET request to obtain the resource located at the URL "https://www.w3.org/", then print it to the console.
Checking the host certificate for validity is recommended.
Do not authenticate. That is the subject of other tasks.
Readers may wish to contrast with the HTTP Request ta... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Send_email | Send email | Task
Write a function to send an email.
The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details.
If appropriate, explain what notifications of problems/success are given.
Solutions using libraries or f... | #Emacs_Lisp | Emacs Lisp | (defun my-send-email (from to cc subject text)
(with-temp-buffer
(insert "From: " from "\n"
"To: " to "\n"
"Cc: " cc "\n"
"Subject: " subject "\n"
mail-header-separator "\n"
text)
(funcall send-mail-function)))
(my-send-email "from@example.com" "to... | Give a code snippet in #Emacs_Lisp
Task
Write a function to send an email.
The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details.
If appropriate, explain what notifications of problems/success are gi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #FOCAL | FOCAL | 01.10 S C=1;S S=1;S Q=1;S R=1;S N=1
01.20 I (N-30)1.3,1.3,1.8
01.30 S S=Q*Q
01.40 I (S-C)1.6,1.7,1.5
01.50 S R=R+1;S C=R*R*R;G 1.4
01.60 S N=N+1;T %4,S,!
01.70 S Q=Q+1;G 1.2
01.80 Q | Give a code snippet in #FOCAL
Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| christopher/rosetta-code | |
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)
}
}
... | Give a code snippet in #Kotlin
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Extensible_prime_generator | Extensible prime generator | Task
Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime.
The routine should demonstrably rely on either:
Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In thi... | #Ring | Ring |
see "first twenty primes : "
i = 1
nr = 0
while i <= 20
nr += 1
if isPrime(nr) see " " + nr i += 1 ok
end
see "primes between 100 and 150 : "
for nr = 100 to 150
if isPrime(nr) see " " + nr ok
next
see nl
see "primes between 7,700 and 8,000 : "
i = 0
for nr = 7700 to 8000
if isPrime(nr) i... | Give a code snippet in #Ring
Task
Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime.
The routine should demonstrably rely on either:
Being based on an open-ended counter set to count without upper limit other than system or progr... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Totient_function | Totient function | The totient function is also known as:
Euler's totient function
Euler's phi totient function
phi totient function
Φ function (uppercase Greek phi)
φ function (lowercase Greek phi)
Definitions (as per number theory)
The totient function:
counts the integers up to a given positiv... | #Shale | Shale | #!/usr/local/bin/shale
primes library
init dup var {
pl sieve type primes::()
100000 0 pl generate primes::()
} =
go dup var {
i var
c0 var
c1 var
c2 var
c3 var
p var
" N Phi Is prime" println
i 1 =
{ i 25 <= } {
i pl isprime primes::() { "True" } { "False" } if i pl phi primes::() i "%2... | Give a code snippet in #Shale
The totient function is also known as:
Euler's totient function
Euler's phi totient function
phi totient function
Φ function (uppercase Greek phi)
φ function (lowercase Greek phi)
Definitions (as per number theory)
The totient function:
counts the... | christopher/rosetta-code | |
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... | #Raku | Raku | constant MAX_N = 20;
constant TRIALS = 100;
for 1 .. MAX_N -> $N {
my $empiric = TRIALS R/ [+] find-loop(random-mapping($N)).elems xx TRIALS;
my $theoric = [+]
map -> $k { $N ** ($k + 1) R/ [*] flat $k**2, $N - $k + 1 .. $N }, 1 .. $N;
FIRST say " N empiric theoric (error)";
FI... | Give a code snippet in #Raku
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 t... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Dining_philosophers | Dining philosophers | The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra.
Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a rou... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | names = <|1 -> "Aristotle", 2 -> "Kant", 3 -> "Spinoza", 4 -> "Marx", 5 -> "Russell"|>;
n = Length[names];
rp := Pause[RandomReal[4]];
PrintTemporary[Dynamic[Array[forks, n]]];
Clear[forks]; forks[_] := Null;
With[{nf = n},
ParallelDo[
With[{i1 = i, i2 = Mod[i + 1, nf, 1]},
Do[Print[names[i], " thinking"]; rp;... | Give a code snippet in #Mathematica_.2F_Wolfram_Language
The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra.
Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend t... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file | Read a specific line from a file | Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (fo... | #TorqueScript | TorqueScript | %file = new fileObject();
%file.openForRead("File/Path.txt");
$seventhLine = "";
while(!%file.isEOF())
{
%line++;
if(%line == 7)
{
$seventhLine = %file.readLine();
if($seventhLine $= "")
{
error("Line 7 of the file is blank!");
}
}
}
%file.close();
%file.delete();
if(%line < 7... | Give a code snippet in #TorqueScript
Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and sto... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Synchronous_concurrency | Synchronous concurrency | The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th... | #Swift | Swift | //
// Reader.swift
//
import Foundation
class Reader: NSObject {
let inputPath = "~/Desktop/input.txt".stringByExpandingTildeInPath
var gotNumberOfLines = false
override init() {
super.init()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "linesPrinted:",
... | Give a code snippet in #Swift
The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with differe... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Anonymous_recursion | Anonymous recursion | While implementing a recursive function, it often happens that we must resort to a separate helper function to handle the actual recursion.
This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects, and/or the f... | #MATLAB | MATLAB |
function v = fibonacci(n)
assert(n >= 0)
v = fibonacci(n,0,1);
% nested function
function a = fibonacci(n,a,b)
if n ~= 0
a = fibonacci(n-1,b,a+b);
end
end
end
| Give a code snippet in #MATLAB
While implementing a recursive function, it often happens that we must resort to a separate helper function to handle the actual recursion.
This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwan... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterat... | #Io | Io | 3 factorial | Give a code snippet in #Io
Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a numb... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Euler_method | Euler method | Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.
The ODE has to be provided in the following form:
d
y
(
t
)
d
t
=
f... | #C.23 | C# | using System;
namespace prog
{
class MainClass
{
const float T0 = 100f;
const float TR = 20f;
const float k = 0.07f;
readonly static float[] delta_t = {2.0f,5.0f,10.0f};
const int n = 100;
public delegate float func(float t);
static float NewtonCooling(float t)
{
return -k * (t-TR);
}
... | Give a code snippet in #C.23
Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.
The ODE has to be provided in the following form:
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of... | #ALGOL_W | ALGOL W | begin
real y; real array a( 0 :: 10 );
real procedure f( real value t );
sqrt(abs(t))+5*t*t*t;
for i:=0 until 10 do read( a(i) );
r_format := "A"; r_w := 9; r_d := 4;
for i:=10 step -1 until 0 do
begin
y:=f(a(i));
if y > 400 then write( "TOO LARGE" )
else write( y );
... | Give a code snippet in #ALGOL_W
The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #C.23 | C# | using System;
using System.Globalization;
struct LimitedInt : IComparable, IComparable<LimitedInt>, IConvertible, IEquatable<LimitedInt>, IFormattable
{
const int MIN_VALUE = 1;
const int MAX_VALUE = 10;
public static readonly LimitedInt MinValue = new LimitedInt(MIN_VALUE);
public static readonly L... | Give a code snippet in #C.23
Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Brace_expansion | Brace expansion | Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified.
Task[edit]
W... | #PHP | PHP | function getitem($s,$depth=0) {
$out = [''];
while ($s) {
$c = $s[0];
if ($depth && ($c == ',' || $c == '}')) {
return [$out, $s];
}
if ($c == '{') {
$x = getgroup(substr($s, 1), $depth + 1);
if($x) {
$tmp = [];
... | Give a code snippet in #PHP
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had be... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers | Luhn test of credit card numbers | The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
Reverse the order of the digits in the number.
Tak... | #PL.2FI | PL/I | test: procedure options (main);
declare (cardnumber, rcn) character (20) varying;
declare (i, k, s1, s2) fixed binary;
get edit (cardnumber) (L);
cardnumber = trim(cardnumber);
rcn = reverse(cardnumber);
s1, s2 = 0;
/* Sum the odd-numbered digits */
do i = 1 to length(rcn) by 2;
s1 = s... | Give a code snippet in #PL.2FI
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
Reverse the order o... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Nested_function | Nested function | In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function.
Task
Write a program consisting of two nested functions that prints t... | #Elixir | Elixir | defmodule Nested do
def makeList(separator) do
counter = 1
makeItem = fn {}, item ->
{"#{counter}#{separator}#{item}\n", counter+1}
{result, counter}, item ->
{result <> "#{counter}#{separator}#{item}\n", counter+1}
end
{} |>... | Give a code snippet in #Elixir
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function.
Task
Write a program consisting of tw... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Algebraic_data_types | Algebraic data types | Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly.
Task
As an example, implement insertion in a red-bla... | #Tcl | Tcl | # From http://wiki.tcl.tk/9547
package require Tcl 8.5
package provide datatype 0.1
namespace eval ::datatype {
namespace export define match matches
namespace ensemble create
# Datatype definitions
proc define {type = args} {
set ns [uplevel 1 { namespace current }]
fore... | Give a code snippet in #Tcl
Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly.
Task
As an example, imp... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Yahoo!_search_interface | Yahoo! search interface | Create a class for searching Yahoo! results.
It must implement a Next Page method, and read URL, Title and Content from results.
| #Phix | Phix | constant glyphs = {{"\xC2\xB7 ","*"}, -- bullet point
{"'",`'`}, -- single quote
{""",`"`}, -- double quote
{"&","&"}, -- ampersand
{"\xE2\x94\xAC\xC2\xAB","[R]"}, -- registered
... | Give a code snippet in #Phix
Create a class for searching Yahoo! results.
It must implement a Next Page method, and read URL, Title and Content from results.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Generic_swap | Generic swap | Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in t... | #Nial | Nial | |reverse 1 2
=2 1 | Give a code snippet in #Nial
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Logo | Logo | to mandelbrot :left :bottom :side :size
cs setpensize [1 1]
make "inc :side/:size
make "zr :left
repeat :size [
make "zr :zr + :inc
make "zi :bottom
pu
setxy repcount - :size/2 minus :size/2
pd
repeat :size [
make "zi :zi + :inc
setpencolor count.color calc :zr :zi
fd ... | Give a code snippet in #Logo
Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Lucas-Lehmer_test | Lucas-Lehmer test | Lucas-Lehmer Test:
for
p
{\displaystyle p}
an odd prime, the Mersenne number
2
p
−
1
{\displaystyle 2^{p}-1}
is prime if and only if
2
p
−
1
{\displaystyle 2^{p}-1}
divides
S
(
p
−
1
)
{\displaystyle S(p-1)}
where
S
(
n
+
1
)
=
(
S
(
n
)
)
2
−
2
{\displaystyle S(n+1)=(... | #Common_Lisp | Common Lisp |
(defun or-f (&optional a b) (or a b));necessary for reduce, as 'or' is implemented as a macro
(defun prime-p (n)
(cond ((< n 4) (>= n 2))
((zerop (rem n 2)) nil)
(t (not (reduce #'or-f (mapcar (lambda (x) (zerop (rem n x))) (loop for i from 3 to (sqrt n) collect i)))))))
(defun mersenne-p (p)
... | Give a code snippet in #Common_Lisp
Lucas-Lehmer Test:
for
p
{\displaystyle p}
an odd prime, the Mersenne number
2
p
−
1
{\displaystyle 2^{p}-1}
is prime if and only if
2
p
−
1
{\displaystyle 2^{p}-1}
divides
S
(
p
−
1
)
{\displaystyle S(p-1)}
where
S
(
n
+
1
)
=
(
S
(
n
)
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime | Add a variable to a class instance at runtime | Demonstrate how to dynamically add variables to an object (a class instance) at runtime.
This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re... | #XBS | XBS | set Object = {}
Object.Hello = "World";
log(Object.Hello); | Give a code snippet in #XBS
Demonstrate how to dynamically add variables to an object (a class instance) at runtime.
This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprog... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the ... | #Common_Lisp | Common Lisp | (defun max-licenses (&optional (logfile "mlijobs.txt"))
(with-open-file (log logfile :direction :input)
(do ((current-logs 0) (max-logs 0) (max-log-times '())
(line #1=(read-line log nil nil) #1#))
((null line)
(format t "~&Maximum simultaneous license use is ~w at the ~
... | Give a code snippet in #Common_Lisp
A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records... | christopher/rosetta-code | |
http://rosettacode.org/wiki/MAC_Vendor_Lookup | MAC Vendor Lookup | Every connected device around the world comes with a unique Media Access Control address, or a MAC address.
A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.
Task
Interface with one (or numerous) APIs that exist on the i... | #AutoHotkey | AutoHotkey | macLookup(MAC){
WebRequest := ComObjCreate("WinHttp.WinHttpRequest.5.1")
WebRequest.Open("GET", "http://api.macvendors.com/" MAC)
WebRequest.Send()
return WebRequest.ResponseText
} | Give a code snippet in #AutoHotkey
Every connected device around the world comes with a unique Media Access Control address, or a MAC address.
A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.
Task
Interface with one (o... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #PicoLisp | PicoLisp |
declare i fixed binary (7), /* occupies 1 byte */
j fixed binary (15), /* occupies 2 bytes */
k fixed binary (31), /* occupies 4 bytes */
l fixed binary (63); /* occupies 8 bytes */
declare d fixed decimal (1), /* occupies 1 byte */
e fixed decimal (3), ... | Give a code snippet in #PicoLisp
Task
Demonstrate how to specify the minimum size of a variable or a data type.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/Wrong_ranges | Loops/Wrong ranges | Loops/Wrong ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment.
The purpose of this task is to select the range syntax/functi... | #Common_Lisp | Common Lisp |
(dolist (lst '((-2 2 1 "Normal") ; Iterate the parameters list `start' `stop' `increment' and `comment'
(-2 2 0 "Zero increment")
(-2 2 -1 "Increments away from stop value")
(-2 2 10 "First increment is beyond stop value")
( 2 -2 1 "Start more than stop: positive increment")
... | Give a code snippet in #Common_Lisp
Loops/Wrong ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment.
The purpose of this task... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ... | #Lingo | Lingo | on fib (n)
if n<2 then return n
return fib(n-1)+fib(n-2)
end | Give a code snippet in #Lingo
The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Increment_a_numerical_string | Increment a numerical string | Task
Increment a numerical string.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | Public Sub Main()
Dim vInput As Variant = "12345"
Inc vInput
Print vInput
End | Give a code snippet in #F.C5.8Drmul.C3.A6
Task
Increment a numerical string.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #Perl | Perl | use bignum qw(e);
$e = 2;
$f = 1;
do {
$e0 = $e;
$n++;
$f *= 2*$n * (1 + 2*$n);
$e += (2*$n + 2) / $f;
} until ($e-$e0) < 1.0e-39;
print "Computed " . substr($e, 0, 41), "\n";
print "Built-in " . e, "\n"; | Give a code snippet in #Perl
Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Creat... | #Scratch | Scratch | 'Animation, by rbytes and Dutchman
word$="Hello World! "
'use button window with text
SET BUTTONS CUSTOM
SET BUTTONS FONT SIZE 40
DRAW COLOR 0,0,0
DO 'the button is redrawn each loop
BUTTON "anim" TEXT word$ AT 130,100
PAUSE .1
'touching the button reverses the scrolling
IF BUTTON_PRESSED("anim") THEN flag=1-flag
IF fl... | Give a code snippet in #Scratch
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Command-line_arguments | Command-line arguments | Command-line arguments is part of Short Circuit's Console Program Basics selection.
Scripted main
See also Program name.
For parsing command line arguments intelligently, see Parsing command-line arguments.
Example command line:
myprogram -c "alpha beta" -h "gamma"
| #Raven | Raven | ARGS print
stack (6 items)
0 => "raven"
1 => "myprogram"
2 => "-c"
3 => "alpha beta"
4 => "-h"
5 => "gamma" | Give a code snippet in #Raven
Command-line arguments is part of Short Circuit's Console Program Basics selection.
Scripted main
See also Program name.
For parsing command line arguments intelligently, see Parsing command-line arguments.
Example command line:
myprogram -c "alpha beta" -h "gamma"
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include ... | #Bori | Bori |
if (i == 0)
return "zero";
elif (i % 2)
return "odd";
else
return "even";
| Give a code snippet in #Bori
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common c... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Cop... | #Liberty_BASIC | Liberty BASIC |
DATA "PI", "0123", "-0123", "12.30", "-12.30", "123!", "0"
DATA "0.0", ".123", "-.123", "12E3", "12E-3", "12+3", "end"
while n$ <> "end"
read n$
print n$, IsNumber(n$)
wend
end
function IsNumber(string$)
on error goto [NotNumber]
string$ = trim$(string$)
'check for float overflow
n = val... | Give a code snippet in #Liberty_BASIC
Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Me... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #C | C | #include <stdlib.h>
#include <stdio.h>
int main() {
puts(getenv("HOME"));
puts(getenv("PATH"));
puts(getenv("USER"));
return 0;
}
| Give a code snippet in #C
Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Fantom | Fantom |
class Main
{
public static Void main ()
{
p := Process (["ls"])
p.run
}
}
| Give a code snippet in #Fantom
Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Non-continuous_subsequences | Non-continuous subsequences | Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.)
A subsequence contains some subset of the elements of this sequence, in the same order.
A continuous subsequence is one in which no elements are missing between the first and last elements of the subseque... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func array bitset: ncsub (in bitset: seq, in integer: s) is func
result
var array bitset: subseq is 0 times {};
local
var bitset: x is {};
var bitset: xs is {};
var bitset: ys is {};
begin
if seq <> {} then
x := {min(seq)};
xs := seq - x;
for... | Give a code snippet in #Seed7
Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.)
A subsequence contains some subset of the elements of this sequence, in the same order.
A continuous subsequence is one in which no elements are missing between the first an... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Letter_frequency | Letter frequency | Task
Open a text file and count the occurrences of each letter.
Some of these programs count all characters (including punctuation),
but some only count letters A to Z.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequen... | #Ruby | Ruby | def letter_frequency(file)
letters = 'a' .. 'z'
File.read(file) .
split(//) .
group_by {|letter| letter.downcase} .
select {|key, val| letters.include? key} .
collect {|key, val| [key, val.length]}
end
letter_frequency(ARGV[0]).sort_by {|key, val| -val}.each {|pair| p pair} | Give a code snippet in #Ruby
Task
Open a text file and count the occurrences of each letter.
Some of these programs count all characters (including punctuation),
but some only count letters A to Z.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Infinity | Infinity | Task
Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity. Otherwise, return the largest possible po... | #RLaB | RLaB |
>> x = inf()
inf
>> isinf(x)
1
>> inf() > 10
1
>> -inf() > 10
0
| Give a code snippet in #RLaB
Task
Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity. Otherwise, ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort | Sorting algorithms/Sleep sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Objeck | Objeck |
use System.Concurrency;
use Collection;
bundle Default {
class Item from Thread {
@value : Int;
New(value : Int) {
Parent();
@value := value;
}
method : public : Run(param : System.Base) ~ Nil {
Sleep(1000 * @value);
@value->PrintLine();
}
}
class SleepSort {
... | Give a code snippet in #Objeck
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick s... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ... | #TSE_SAL | TSE SAL |
// library: math: get: series: fibonacci <description></description> <version control></version control> <version>1.0.0.0.3</version> <version control></version control> (filenamemacro=getmasfi.s) [<Program>] [<Research>] [kn, ri, su, 20-01-2013 22:04:02]
INTEGER PROC FNMathGetSeriesFibonacciI( INTEGER nI )
//
/... | Give a code snippet in #TSE_SAL
The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions a... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Jensen%27s_Device | Jensen's Device | Jensen's Device
You are encouraged to solve this task according to the task description, using any language you may know.
This task is an exercise in call by name.
Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL 60 Report.
The following pr... | #VBA | VBA |
Private Function sum(i As String, ByVal lo As Integer, ByVal hi As Integer, term As String) As Double
Dim temp As Double
For k = lo To hi
temp = temp + Evaluate(Replace(term, i, k))
Next k
sum = temp
End Function
Sub Jensen_Device()
Debug.Print sum("i", 1, 100, "1/i")
Debug.Print sum("... | Give a code snippet in #VBA
Jensen's Device
You are encouraged to solve this task according to the task description, using any language you may know.
This task is an exercise in call by name.
Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL... | christopher/rosetta-code | |
http://rosettacode.org/wiki/String_concatenation | String concatenation | String concatenation
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a string variable equal to any text value.
Create another string variable whose value is the original variable concatenated with another string literal.
To illustrate the operat... | #HicEst | HicEst | CHARACTER s = "hello", sl*100
WRITE() s // " literal"
sl = s // " literal"
WRITE() sl | Give a code snippet in #HicEst
String concatenation
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a string variable equal to any text value.
Create another string variable whose value is the original variable concatenated with another string li... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
... | #zig | zig | const std = @import("std");
const time = std.time;
const warn = std.debug.warn;
pub fn main() void {
warn("Sleeping...\n");
time.sleep(1000000000); // `sleep` uses nanoseconds
warn("Awake!\n");
} | Give a code snippet in #zig
Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread f... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Program_name | Program name | The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A... | #Dart | Dart | #!/usr/bin/env dart
main() {
var program = new Options().script;
print("Program: ${program}");
} | Give a code snippet in #Dart
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script n... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Death_Star | Death Star |
Task
Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction.
(This will basically produce a shape like a "death star".)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
| #Wren | Wren | import "dome" for Window
import "graphics" for Canvas, Color, ImageData
import "math" for Vector
var Normalize = Fn.new{ |vec|
var invLen = 1 / vec.dot(vec).sqrt
vec.x = vec.x * invLen
vec.y = vec.y * invLen
vec.z = vec.z * invLen
}
class Sphere {
construct new(cx, cy, cz, r) {
_cx = cx
... | Give a code snippet in #Wren
Task
Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction.
(This will basically produce a shape like a "death star".)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
write language nam... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity | Rosetta Code/Rank languages by popularity | Rosetta Code/Rank languages by popularity
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Sort the most popular computer programming languages based in number of members in Rosetta Code categories.
Sample output on 01 juin 2022 at 14:13 +02
Rank: 1 (1,... | #D | D | void main() {
import std.stdio, std.algorithm, std.conv, std.array, std.regex,
std.typecons, std.net.curl;
immutable r1 = `"title":"Category:([^"]+)"`;
const languages = get("www.rosettacode.org/w/api.php?action=query"~
"&list=categorymembers&cmtitle=Category:Pro"~
... | Give a code snippet in #D
Rosetta Code/Rank languages by popularity
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Sort the most popular computer programming languages based in number of members in Rosetta Code categories.
Sample output on 01 juin 2022... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if ... | #PARI.2FGP | PARI/GP | multMM(A,B)=matrix(#A[,1],#A,i,j,A[i,j]*B[i,j]);
divMM(A,B)=matrix(#A[,1],#A,i,j,A[i,j]/B[i,j]);
powMM(A,B)=matrix(#A[,1],#A,i,j,A[i,j]^B[i,j]); | Give a code snippet in #PARI.2FGP
This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
e... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sum_of_a_series | Sum of a series | Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
S
n
=
∑
k
=
1
n
1
k
2
{\displa... | #Eiffel | Eiffel |
note
description: "Compute the n-th term of a series"
class
SUM_OF_SERIES_EXAMPLE
inherit
MATH_CONST
create
make
feature -- Initialization
make
local
approximated, known: REAL_64
do
known := Pi^2 / 6
approximated := sum_until (agent g, 1001)
print ("%Nzeta function exact value: %N")
... | Give a code snippet in #Eiffel
Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
S
n
=
∑
k
=
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hailstone_sequence | Hailstone sequence | The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conje... | #Sidef | Sidef | func hailstone (n) {
var sequence = [n]
while (n > 1) {
sequence << (
n.is_even ? n.div!(2)
: n.mul!(3).add!(1)
)
}
return(sequence)
}
# The hailstone sequence for the number 27
var arr = hailstone(var nr = 27)
say "#{nr}: #{arr.first(4)} ... #{arr.las... | Give a code snippet in #Sidef
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/String_concatenation | String concatenation | String concatenation
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a string variable equal to any text value.
Create another string variable whose value is the original variable concatenated with another string literal.
To illustrate the operat... | #Tailspin | Tailspin |
def a: 'Hello';
'$a;, World!' -> !OUT::write
| Give a code snippet in #Tailspin
String concatenation
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a string variable equal to any text value.
Create another string variable whose value is the original variable concatenated with another string ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Address_of_a_variable | Address of a variable |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Z80_Assembly | Z80 Assembly | foo equ &C000
bar equ &C001
ld (foo),a ;store A into memory location &C000
ld a,b ;copy B to A
ld (bar),a ;store "B" into memory location &C001 | Give a code snippet in #Z80_Assembly
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Oper... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Topological_sort | Topological sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Scheme | Scheme |
(import (chezscheme))
(import (srfi srfi-1))
(define (remove-self-dependency pair)
(let ((key (car pair))
(value (cdr pair)))
(cons key (remq key value))))w
(define (remove-self-dependencies alist)
(map remove-self-dependency alist))
(define (add-missing-items dependencies)
(let loop ((items... | Give a code snippet in #Scheme
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick s... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Mind_boggling_card_trick | Mind boggling card trick | Mind boggling card trick
You are encouraged to solve this task according to the task description, using any language you may know.
Matt Parker of the "Stand Up Maths channel" has a YouTube video of a card trick that creates a semblance of order from chaos.
The task is to simulate the trick in a way that mimics th... | #Julia | Julia | const rbdeck = split(repeat('R', 26) * repeat('B', 26), "")
shuffledeck() = shuffle(rbdeck)
function deal!(deck, dpile, bpile, rpile)
while !isempty(deck)
if (topcard = pop!(deck)) == "R"
push!(rpile, pop!(deck))
else
push!(bpile, pop!(deck))
end
push!(dpile... | Give a code snippet in #Julia
Mind boggling card trick
You are encouraged to solve this task according to the task description, using any language you may know.
Matt Parker of the "Stand Up Maths channel" has a YouTube video of a card trick that creates a semblance of order from chaos.
The task is to simulate th... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot ... | #FunL | FunL | import lists.zipWith
def dot( a, b )
| a.length() == b.length() = sum( zipWith((*), a, b) )
| otherwise = error( "Vector sizes must match" )
println( dot([1, 3, -5], [4, -2, -1]) ) | Give a code snippet in #FunL
Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For... | #OOC | OOC |
main: func {
value := 1024
while (value > 0) {
value toString() println()
value /= 2
}
}
| Give a code snippet in #OOC
Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Harshad_or_Niven_series | Harshad or Niven series | The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits.
For example, 42 is a Harshad number as 42 is divisible by (4 + 2) without remainder.
Assume that the series is defined as the numbers in increasing order.
Task
The task is to create a function/method/... | #BCPL | BCPL | get "libhdr"
let dsum(n) = n=0 -> 0, n rem 10 + dsum(n/10)
let next(n) = harshad(n+1) and harshad(n) = n rem dsum(n)=0 -> n, next(n)
let start() be
$( let n = 0
writes("First 20:")
for i = 1 to 20 do
$( n := next(n)
writef(" %N", n)
$)
writef("*NFirst above 1000: %N*N", next(1000))
$) | Give a code snippet in #BCPL
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits.
For example, 42 is a Harshad number as 42 is divisible by (4 + 2) without remainder.
Assume that the series is defined as the numbers in increasing order.
Task
The task i... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Julia_set | Julia set |
Task
Generate and draw a Julia set.
Related tasks
Mandelbrot Set
| #Ruby | Ruby | def julia(c_real, c_imag)
puts Complex(c_real, c_imag)
-1.0.step(1.0, 0.04) do |v|
puts -1.4.step(1.4, 0.02).map{|h| judge(c_real, c_imag, h, v)}.join
end
end
def judge(c_real, c_imag, x, y)
50.times do
z_real = (x * x - y * y) + c_real
z_imag = x * y * 2 + c_imag
return " " if z_real**2 > 10... | Give a code snippet in #Ruby
Task
Generate and draw a Julia set.
Related tasks
Mandelbrot Set
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
... | #Picat | Picat | go =>
foreach(N in 1..4)
sierpinski(N),
nl
end,
nl.
sierpinski(N) =>
Size = 2**N,
foreach(Y in Size-1..-1..0)
printf("%s", [' ' : _I in 1..Y]),
foreach(X in 0..Size-Y-1)
printf("%s ", cond(X /\ Y == 0, "*", " "))
end,
nl
end. | Give a code snippet in #Picat
Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #Kotlin | Kotlin | // version 1.0.6
// In Kotlin all Exception classes derive from Throwable and, by convention, end with the word 'Exception'
class MyException (override val message: String?): Throwable(message)
fun foo() {
throw MyException("Bad foo!")
}
fun goo() {
try {
foo()
}
catch (me: MyException) {... | Give a code snippet in #Kotlin
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exception... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Elixir | Elixir | defmodule Arithmetic_Integer do
# Function to remove line breaks and convert string to int
defp get_int(msg) do
IO.gets(msg) |> String.strip |> String.to_integer
end
def task do
# Get user input
a = get_int("Enter your first integer: ")
b = get_int("Enter your second integer: ")
IO.puts... | Give a code snippet in #Elixir
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hello_world/Text | Hello world/Text | Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
| #Lilypond | Lilypond | \version "2.18.2"
global = {
\time 4/4
\key c \major
\tempo 4=100
}
\relative c''{ g e e( g2)
}
\addlyrics {
Hel -- lo, World!
} | Give a code snippet in #Lilypond
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard erro... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Jsish | Jsish | /* Runtime evaluation, in Jsish */
var foo = eval('{value: 42}');
eval('var bar = "Hello, world!";');
;typeof foo;
;foo.value;
;typeof bar;
;bar;
/*
=!EXPECTSTART!=
typeof foo ==> object
foo.value ==> 42
typeof bar ==> string
bar ==> Hello, world!
=!EXPECTEND!=
*/ | Give a code snippet in #Jsish
Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applica... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Population_count | Population count | Population count
You are encouraged to solve this task according to the task description, using any language you may know.
The population count is the number of 1s (ones) in the binary representation of a non-negative integer.
Population count is also known as:
pop count
popcount
sideways sum
... | #Free_Pascal | Free Pascal | program populationCount(input, output, stdErr);
var
// general advice: iterator variables are _signed_
iterator: int64;
// the variable we’d like to count the set bits in
number: qWord;
// how many evil numbers we’ve already found
evilCount: int64;
// odious numbers
odiousNumber: array[1..30] of qWord;
odiousI... | Give a code snippet in #Free_Pascal
Population count
You are encouraged to solve this task according to the task description, using any language you may know.
The population count is the number of 1s (ones) in the binary representation of a non-negative integer.
Population count is also known as:
pop... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits | Largest number divisible by its digits | Task
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as Lynch-Bell numbers, numbers n such that the
(base ten) digits are all different (and do not include zero) and n is divisible by each of it... | #Lua | Lua | function isDivisible(n)
local t = n
local a = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
while t ~= 0 do
local r = t % 10
if r == 0 then
return false
end
if n % r ~= 0 then
return false
end
if a[r + 1] > 0 then
return false
en... | Give a code snippet in #Lua
Task
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as Lynch-Bell numbers, numbers n such that the
(base ten) digits are all different (and do not include zero) and n... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. 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)
Task
Provide a list of precedence and associativity... | #AppleScript | AppleScript | print 2 + 3 * 5 ; same as 2 + (3 * 5)
print 3 * 5 + 2 ; same as 3 * (5 + 2) | Give a code snippet in #AppleScript
This page uses content from Wikipedia. The original article was at Operators in C and C++. 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)
Task
Provide a list ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Roman_numerals/Decode | Roman numerals/Decode | Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decima... | #PowerShell | PowerShell |
Filter FromRoman {
$output = 0
if ($_ -notmatch '^(M{1,3}|)(CM|CD|D?C{0,3}|)(XC|XL|L?X{0,3}|)(IX|IV|V?I{0,3}|)$') {
throw 'Incorrect format'
}
$current = 1000
$subtractor = 'M'
$whole = $False
$roman = $_
'C','D','X','L','I','V',' ' `
| %{
if ($whole = !$whole) {
$current /= 10
$subtractor = $_... | Give a code snippet in #PowerShell
Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Reduced_row_echelon_form | Reduced row echelon form | Reduced row echelon form
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Show how to compute the reduced row echelon form
(a.k.a. row canonical form) of a matrix.
The matrix can be stored in any datatype that is convenient
(for most languages, this wil... | #FreeBASIC | FreeBASIC | #include once "matmult.bas"
sub rowswap( byval M as Matrix, i as uinteger, j as uinteger )
dim as integer k
for k = 0 to ubound(M.m, 2)
swap M.m(j, k), M.m(i, k)
next k
end sub
function rowech(byval M as Matrix) as Matrix
dim as uinteger lead = 0, rowCount = 1+ubound(M.m, 1), colCount = 1+ub... | Give a code snippet in #FreeBASIC
Reduced row echelon form
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Show how to compute the reduced row echelon form
(a.k.a. row canonical form) of a matrix.
The matrix can be stored in any datatype that is conve... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Compare_a_list_of_strings | Compare a list of strings | Task
Given a list of arbitrarily many strings, show how to:
test if they are all lexically equal
test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order)
Each of those two tests should result in a single true or false value, which could be used as t... | #PicoLisp | PicoLisp | (= "AA" "AA" "AA")
-> T
(= "AA" "AA" "Aa")
-> NIL
(< "AA" "AA")
-> NIL
(< "AA" "Aa")
-> T
(< "1" "A" "B" "Z" "c" )
-> T
(> "A" "B" "Z" "C")
-> NIL | Give a code snippet in #PicoLisp
Task
Given a list of arbitrarily many strings, show how to:
test if they are all lexically equal
test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order)
Each of those two tests should result in a single true or fal... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Fractal_tree | Fractal tree | Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
| #Wren | Wren | import "graphics" for Canvas, Color
import "dome" for Window
import "math" for Math
var Radians = Fn.new { |d| d * Num.pi / 180 }
class FractalTree {
construct new(width, height) {
Window.title = "Fractal Tree"
Window.resize(width, height)
Canvas.resize(width, height)
_fore = Col... | Give a code snippet in #Wren
Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Dutch_national_flag_problem | Dutch national flag problem |
The Dutch national flag is composed of three coloured bands in the order:
red (top)
then white, and
lastly blue (at the bottom).
The problem posed by Edsger Dijkstra is:
Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national fla... | #Action.21 | Action! | INCLUDE "D2:SORT.ACT" ;from the Action! Tool Kit
PROC PrintArray(BYTE ARRAY a BYTE len)
CHAR ARRAY colors(3)=['R 'W 'B]
BYTE i,index
FOR i=0 TO len-1
DO
index=a(i)
Put(colors(index))
OD
RETURN
BYTE FUNC IsSorted(BYTE ARRAY a BYTE len)
BYTE i
IF len<=1 THEN
RETURN (1)
FI
FOR i=0 TO ... | Give a code snippet in #Action.21
The Dutch national flag is composed of three coloured bands in the order:
red (top)
then white, and
lastly blue (at the bottom).
The problem posed by Edsger Dijkstra is:
Given a number of red, blue and white balls in random order, arrange them in the order of th... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Idiomatically_determine_all_the_characters_that_can_be_used_for_symbols | Idiomatically determine all the characters that can be used for symbols | Idiomatically determine all the characters that can be used for symbols.
The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to name, ... | #Python | Python | [ $ "0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrS"
$ QsTtUuVvWwXxYyZz()[]{}<>~=+-*/^\|_.,:;?!'"`%@&#$Q
join ] constant is tokenchars ( --> $ )
( The first non-whitespace character after the word $
(pronounced "string") is deemed to be the delimiter
for the string that... | Give a code snippet in #Python
Idiomatically determine all the characters that can be used for symbols.
The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hello_world/Standard_error | Hello world/Standard error | Hello world/Standard error is part of Short Circuit's Console Program Basics selection.
A common practice in computing is to send error messages
to a different output stream than normal text console messages.
The normal messages print to what is called "standard output" or "standard out".
The error messages print to ... | #OCaml | OCaml | prerr_endline "Goodbye, World!"; (* this is how you print a string with newline to stderr *)
Printf.eprintf "Goodbye, World!\n"; (* this is how you would use printf with stderr *) | Give a code snippet in #OCaml
Hello world/Standard error is part of Short Circuit's Console Program Basics selection.
A common practice in computing is to send error messages
to a different output stream than normal text console messages.
The normal messages print to what is called "standard output" or "standard out"... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams | Anagrams/Deranged anagrams | Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words.
Task[edit]
Use the word list at uni... | #Pascal | Pascal | program Anagrams_Deranged;
{$IFDEF FPC}
{$MODE Delphi}
{$Optimization ON,ALL}
uses
SysUtils,
Classes;
{$ELSE}
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Classes,
{$R *.res}
{$ENDIF}
function Sort(const s: string):string;
//insertion sort
var
pRes : pchar;
i, j, aLength: NativeInt;
tmpc: Cha... | Give a code snippet in #Pascal
Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words.
Tas... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #AWK | AWK | { # read every line into an array
line[NR] = $0
}
END { # sort it with bubble sort
do {
haschanged = 0
for(i=1; i < NR; i++) {
if ( line[i] > line[i+1] ) {
t = line[i]
line[i] = line[i+1]
line[i+1] = t
haschanged = 1
}
}
} while ( haschanged == 1 )
# print it
for(i=1; i <= NR; i++)... | Give a code snippet in #AWK
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: ... | #Maple | Maple | > nums := seq( 1 .. 10 );
nums := 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
> foldl( `+`, 0, nums ); # compute sum using foldl
55
> foldr( `*`, 1, nums ); # compute product using foldr
3628800 | Give a code snippet in #Maple
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Smith_numbers | Smith numbers | Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1.
By definition, all primes are excluded as they (naturally) satisfy this condition!
Smith numbers are also known as joke numbers.... | #Arturo | Arturo | digitSum: function [v][
n: new v
result: new 0
while [n > 0][
'result + n % 10
'n / 10
]
return result
]
smith?: function [z][
return
(prime? z) ? -> false
-> (digitSum z) = sum map factors.prime z 'num [digitSum num]
]
found: 0
loop 1..10000 'x [
... | Give a code snippet in #Arturo
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1.
By definition, all primes are excluded as they (naturally) satisfy this condition!
Smith numbers are... | christopher/rosetta-code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.