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/ISBN13_check_digit | ISBN13 check digit | Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
978-1734314502 (good)
... | #Java | Java | public static void main(){
System.out.println(isISBN13("978-1734314502"));
System.out.println(isISBN13("978-1734314509"));
System.out.println(isISBN13("978-1788399081"));
System.out.println(isISBN13("978-1788399083"));
}
public static boolean isISBN13(String in){
int pre = In... | Give a code snippet in #Java
Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
9... | christopher/rosetta-code | |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retr... | #Swift | Swift | import Foundation
var ⌚️ = NSDate()
println(⌚️) | Give a code snippet in #Swift
Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Levenshtein_distance | Levenshtein distance |
This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In information theory and computer science, the Levenshtein ... | #TSE_SAL | TSE SAL | // library: math: get: damerau: levenshtein <description></description> <version>1.0.0.0.23</version> <version control></version control> (filenamemacro=getmadle.s) [kn, ri, th, 08-09-2011 23:04:55]
INTEGER PROC FNMathGetDamerauLevenshteinDistanceI( STRING s1, STRING s2 )
INTEGER L1 = Length( s1 )
INTEGER L2 = Length... | Give a code snippet in #TSE_SAL
This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In information theory and c... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #R | R |
a1 <- c(1, 2, 3)
a2 <- c(3, 4, 5)
a3 <- c(a1, a2)
| Give a code snippet in #R
Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #PL.2FI | PL/I | /* The short method: */
declare A(m, n) float, B (n,m) float defined (A(2sub, 1sub));
/* Any reference to B gives the transpose of matrix A. */ | Give a code snippet in #PL.2FI
Transpose an arbitrarily sized rectangular Matrix.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Modular_inverse | Modular inverse | From Wikipedia:
In modular arithmetic, the modular multiplicative inverse of an integer a modulo m is an integer x such that
a
x
≡
1
(
mod
m
)
.
{\displaystyle a\,x\equiv 1{\pmod {m}}.}
Or in other words, such that:
∃
k
∈
Z
,
a
x
=
1
+
k
m
{\displaystyle \exists k\in \math... | #Haskell | Haskell | -- Given a and m, return Just x such that ax = 1 mod m.
-- If there is no such x return Nothing.
modInv :: Int -> Int -> Maybe Int
modInv a m
| 1 == g = Just (mkPos i)
| otherwise = Nothing
where
(i, _, g) = gcdExt a m
mkPos x
| x < 0 = x + m
| otherwise = x
-- Extended Euclidean algorithm.
... | Give a code snippet in #Haskell
From Wikipedia:
In modular arithmetic, the modular multiplicative inverse of an integer a modulo m is an integer x such that
a
x
≡
1
(
mod
m
)
.
{\displaystyle a\,x\equiv 1{\pmod {m}}.}
Or in other words, such that:
∃
k
∈
Z
,
a
x
=
1
+
k
m
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out... | #Logo | Logo | print ascii "a ; 97
print char 97 ; a | Give a code snippet in #Logo
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conve... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Runge-Kutta_method | Runge-Kutta method | Given the example Differential equation:
y
′
(
t
)
=
t
×
y
(
t
)
{\displaystyle y'(t)=t\times {\sqrt {y(t)}}}
With initial condition:
t
0
=
0
{\displaystyle t_{0}=0}
and
y
0
=
y
(
t
0
)
=
y
(
0
)
=
1
{\displaystyle y_{0}=y(t_{0})=y(0)=1}
This equation has an exact solution:
... | #FreeBASIC | FreeBASIC | ' version 03-10-2015
' compile with: fbc -s console
' translation of BBC BASIC
Dim As Double y = 1, t, actual, k1, k2, k3, k4
Print
For i As Integer = 0 To 100
t = i / 10
If t = Int(t) Then
actual = ((t ^ 2 + 4) ^ 2) / 16
Print "y("; Str(t); ") ="; y ; Tab(27); "Error = "; actual - y
... | Give a code snippet in #FreeBASIC
Given the example Differential equation:
y
′
(
t
)
=
t
×
y
(
t
)
{\displaystyle y'(t)=t\times {\sqrt {y(t)}}}
With initial condition:
t
0
=
0
{\displaystyle t_{0}=0}
and
y
0
=
y
(
t
0
)
=
y
(
0
)
=
1
{\displaystyle y_{0}=y(t_{0})=y(0)=1}
Thi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Levenshtein_distance | Levenshtein distance |
This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In information theory and computer science, the Levenshtein ... | #Objective-C | Objective-C | @interface NSString (levenshteinDistance)
- (NSUInteger)levenshteinDistanceToString:(NSString *)string;
@end
@implementation NSString (levenshteinDistance)
- (NSUInteger)levenshteinDistanceToString:(NSString *)string {
NSUInteger sl = [self length];
NSUInteger tl = [string length];
NSUInteger *d = calloc(... | Give a code snippet in #Objective-C
This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In information theory a... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Search_a_list_of_records | Search a list of records | Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/et... | #Kotlin | Kotlin | // version 1.1.2
class City(val name: String, val pop: Double)
val cities = listOf(
City("Lagos", 21.0),
City("Cairo", 15.2),
City("Kinshasa-Brazzaville", 11.3),
City("Greater Johannesburg", 7.55),
City("Mogadishu", 5.85),
City("Khartoum-Omdurman", 4.98),
City("Dar Es Salaam", 4.7),
... | Give a code snippet in #Kotlin
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Collections | Collections | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Collections are abstractions to represent sets of values.
In statically-typed languages, the values are typically of a common data type.
Task
Create a collection, and add a fe... | #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
collection=*
DATA apple
DATA banana
DATA orange
morestuff=*
DATA peaches
DATA apple
collection=APPEND(collection,morestuff)
TRACE *collection
| Give a code snippet in #TUSCRIPT
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Collections are abstractions to represent sets of values.
In statically-typed languages, the values are typically of a common data type.
Task
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem | Dinesman's multiple-dwelling problem | Task
Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below.
Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of... | #Elixir | Elixir | defmodule Dinesman do
def problem do
names = ~w( Baker Cooper Fletcher Miller Smith )a
predicates = [fn(c)-> :Baker != List.last(c) end,
fn(c)-> :Cooper != List.first(c) end,
fn(c)-> :Fletcher != List.first(c) && :Fletcher != List.last(c) end,
fn(c)-> floo... | Give a code snippet in #Elixir
Task
Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below.
Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #SQL | SQL | SELECT * FROM mytable -- Selects all columns and rows | Give a code snippet in #SQL
Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an 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 |... | #Lambdatalk | Lambdatalk |
{def factors
{def factors.r
{lambda {:num :i :N}
{if {> :i :N}
then
else {if {= {% :num :i} 0}
then :i
{if {not {= {/ :num :i} :i}}
then {/ :num :i}
else}
else}
{factors.r :num {+ :i 1} :N} }}}
{lambda {:n}
{S.sort < {fa... | Give a code snippet in #Lambdatalk
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 Operat... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of point... | #Lua | Lua | t, n = {}, 0
for y=1,31 do t[y]={} for x=1,31 do t[y][x]=" " end end
repeat
x, y = math.random(-15,15), math.random(-15,15)
rsq = x*x + y*y
if rsq>=100 and rsq<=225 and t[y+16][x+16]==" " then
t[y+16][x+16], n = "██", n+1
end
until n==100
for y=1,31 do print(table.concat(t[y])) end | Give a code snippet in #Lua
Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circl... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Function_composition | Function composition | Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose... | #Nemerle | Nemerle | using System;
using System.Console;
using System.Math;
module Composition
{
Compose[T](f : T -> T, g : T -> T, x : T) : T
{
f(g(x))
}
Main() : void
{
def SinAsin = Compose(Sin, Asin, _);
WriteLine(SinAsin(0.5));
}
} | Give a code snippet in #Nemerle
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #Visual_Basic_.NET | Visual Basic .NET | Imports System
Imports System.Console
Imports BI = System.Numerics.BigInteger
Module Module1
Function isqrt(ByVal x As BI) As BI
Dim t As BI, q As BI = 1, r As BI = 0
While q <= x : q <<= 2 : End While
While q > 1 : q >>= 2 : t = x - r - q : r >>= 1
If t >= 0 Then x = t : r += ... | Give a code snippet in #Visual_Basic_.NET
Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in y... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #Sather | Sather | class MAIN is
main is
a :ARRAY{INT} := |10, 5, 5, 20, 60, 100|;
sum, prod :INT;
loop sum := sum + a.elt!; end;
prod := 1;
loop prod := prod * a.elt!; end;
#OUT + sum + " " + prod + "\n";
end;
end; | Give a code snippet in #Sather
Task
Compute the sum and product of an array of integers.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Angle_difference_between_two_bearings | Angle difference between two bearings | Finding the angle between two bearings is often confusing.[1]
Task
Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings.
Input bearings are expressed in the range -180 to +180 degrees.
The result is also expressed in the range -180 to +180 degrees.
... | #Ada | Ada |
-----------------------------------------------------------------------
-- Angle difference between two bearings
-----------------------------------------------------------------------
with Ada.Text_IO; use Ada.Text_IO;
procedure Bearing_Angles is
type Real is digits 8;
Package Real_Io is new Ada.Text_IO.Floa... | Give a code snippet in #Ada
Finding the angle between two bearings is often confusing.[1]
Task
Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings.
Input bearings are expressed in the range -180 to +180 degrees.
The result is also expressed in the range -1... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
Fo... | #ALGOL_68 | ALGOL 68 | BEGIN
# returns s with ", " added between each change of character #
PROC split on characters = ( STRING s )STRING:
IF s = "" THEN
# empty string #
""
ELSE
# allow for 3 times as many characters as in the string #
# this would handle a string of ... | Give a code snippet in #ALGOL_68
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/LZW_compression | LZW compression | The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression.
You can read a complete description of it in the Wikipedia article on the subject. It was patented, but it entered the public domain in 2004.
| #Perl | Perl | # Compress a string to a list of output symbols.
sub compress {
my $uncompressed = shift;
# Build the dictionary.
my $dict_size = 256;
my %dictionary = map {chr $_ => chr $_} 0..$dict_size-1;
my $w = "";
my @result;
foreach my $c (split '', $uncompressed) {
my $wc = $w . $c;
... | Give a code snippet in #Perl
The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression.
You can read a complete description of it in the Wikipedia article on the subject. It was patented, but it entered the public domain in 2004.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Patience_sort | Sorting algorithms/Patience 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
... | #Raku | Raku | multi patience(*@deck) {
my @stacks;
for @deck -> $card {
with @stacks.first: $card before *[*-1] -> $stack {
$stack.push: $card;
}
else {
@stacks.push: [$card];
}
}
gather while @stacks {
take .pop given min :by(*[*-1]), @stacks;
@... | Give a code snippet in #Raku
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 sor... | christopher/rosetta-code | |
http://rosettacode.org/wiki/AVL_tree | AVL tree |
This page uses content from Wikipedia. The original article was at AVL tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In computer science, an AVL tree is a self-balancing binary search tree.... | #Go | Go | package avl
// AVL tree adapted from Julienne Walker's presentation at
// http://eternallyconfuzzled.com/tuts/datastructures/jsw_tut_avl.aspx.
// This port uses similar indentifier names.
// The Key interface must be supported by data stored in the AVL tree.
type Key interface {
Less(Key) bool
Eq(Key) bool
... | Give a code snippet in #Go
This page uses content from Wikipedia. The original article was at AVL tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In computer science, an AVL tree is a self-b... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Knapsack_problem/Continuous | Knapsack problem/Continuous |
A thief burgles a butcher's shop, where he can select from some items.
The thief knows the weights and prices of each items. Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized. He may cut the items; the item has a reduced price after... | #PL.2FI | PL/I | *process source xref attributes;
KNAPSACK_CONTINUOUS: Proc Options(main);
/*--------------------------------------------------------------------
* 19.09.2014 Walter Pachl translated from FORTRAN
*-------------------------------------------------------------------*/
Dcl (divide,float,hbound,repeat) Builtin;
Dcl ... | Give a code snippet in #PL.2FI
A thief burgles a butcher's shop, where he can select from some items.
The thief knows the weights and prices of each items. Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized. He may cut the items; th... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Linear_congruential_generator | Linear congruential generator | The linear congruential generator is a very simple example of a random number generator.
All linear congruential generators use this formula:
r
n
+
1
=
a
×
r
n
+
c
(
mod
m
)
{\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}}
Where:
r
0
{\displaystyle r_{0}}
is a seed.
r
1
... | #Julia | Julia | using Printf
function getlgc(r::Integer, a::Integer, c::Integer, m::Integer, sh::Integer)
state = r
return function lgcrand()
state = mod(a * state + c, m)
return state >> sh
end
end
seed, nrep = 0, 10
bsdrand = getlgc(seed, 1103515245, 12345, 2 ^ 31, 0)
println("The first $nrep result... | Give a code snippet in #Julia
The linear congruential generator is a very simple example of a random number generator.
All linear congruential generators use this formula:
r
n
+
1
=
a
×
r
n
+
c
(
mod
m
)
{\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}}
Where:
r
0
{\displaystyle r... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to st... | #AutoHotkey | AutoHotkey | Animals := [["fly", "I don't know why she swallowed the "]
, ["spider", "That wriggled and jiggled and tickled inside her"]
, ["bird", "Quite absurd"]
, ["cat", "Fancy that"]
, ["dog", "What a hog"]
, ["pig", "Her mouth was so big"]
, ["goat", "She just opened her throat"]
, ["cow", "I don't know h... | Give a code snippet in #AutoHotkey
Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical o... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Entropy | Entropy | Task
Calculate the Shannon entropy H of a given input string.
Given the discrete random variable
X
{\displaystyle X}
that is a string of
N
{\displaystyle N}
"symbols" (total characters) consisting of
n
{\displaystyle n}
different characters (n=2 for binary), the Shannon entropy of X in bit... | #Pascal | Pascal |
PROGRAM entropytest;
USES StrUtils, Math;
TYPE FArray = ARRAY of CARDINAL;
VAR strng: STRING = '1223334444';
// list unique characters in a string
FUNCTION uniquechars(str: STRING): STRING;
VAR n: CARDINAL;
BEGIN
uniquechars := '';
FOR n := 1 TO length(str) DO
IF (PosEx(str[n],str,n)>0)
AND (Po... | Give a code snippet in #Pascal
Task
Calculate the Shannon entropy H of a given input string.
Given the discrete random variable
X
{\displaystyle X}
that is a string of
N
{\displaystyle N}
"symbols" (total characters) consisting of
n
{\displaystyle n}
different characters (n=2 for binary),... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort | Sorting algorithms/Bead 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
... | #Tcl | Tcl | package require Tcl 8.5
proc beadsort numList {
# Special case: empty list is empty when sorted.
if {![llength $numList]} return
# Set up the abacus...
foreach n $numList {
for {set i 0} {$i<$n} {incr i} {
dict incr vals $i
}
}
# Make the beads fall...
foreach n [dict values $vals] ... | Give a code snippet in #Tcl
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/Priority_queue | Priority queue | A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insert... | #M2000_Interpreter | M2000 Interpreter |
Module UnOrderedArray {
Class PriorityQueue {
Private:
Dim Item()
many=0, level=0, first
cmp = lambda->0
Module Reduce {
if .many<.first*2 then exit
If .level<.many/2 then .many/=2 : Dim .Item(.many)
}
Pu... | Give a code snippet in #M2000_Interpreter
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the q... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Superpermutation_minimisation | Superpermutation minimisation | A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'... | #FreeBASIC | FreeBASIC | ' version 28-06-2018
' compile with: fbc -s console
Function superpermsize(n As UInteger) As UInteger
Dim As UInteger x, y, sum, fac
For x = 1 To n
fac = 1
For y = 1 To x
fac *= y
Next
sum += fac
Next
Function = sum
End Function
Function superperm(n ... | Give a code snippet in #FreeBASIC
A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose t... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort | Sorting Algorithms/Circle 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
... | #ZX_Spectrum_Basic | ZX Spectrum Basic |
10 DIM a(100): DIM s(32): RANDOMIZE : LET p=1: GO SUB 3000: GO SUB 2000: GO SUB 4000
20 STOP
1000 IF b=e THEN RETURN
1010 LET s(p)=b: LET s(p+1)=e
1020 IF a(s(p))>a(e) THEN LET t=a(s(p)): LET a(s(p))=a(e): LET a(e)=t: LET c=1
1030 LET s(p)=s(p)+1: LET e=e-1: IF s(p)<e THEN GO TO 1020
1040 LET p=p+2: GO SUB... | Give a code snippet in #ZX_Spectrum_Basic
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 sor... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Factorions | Factorions |
Definition
A factorion is a natural number that equals the sum of the factorials of its digits.
Example
145 is a factorion in base 10 because:
1! + 4! + 5! = 1 + 24 + 120 = 145
It can be shown (see talk page) that no factorion in base 10 can exceed 1,499,999.
Task
Write a progr... | #Perl | Perl | use strict;
use warnings;
use ntheory qw/factorial todigits/;
my $limit = 1500000;
for my $b (9 .. 12) {
print "Factorions in base $b:\n";
$_ == factorial($_) and print "$_ " for 0..$b-1;
for my $i (1 .. int $limit/$b) {
my $sum;
my $prod = $i * $b;
for (reverse todigits($i, ... | Give a code snippet in #Perl
Definition
A factorion is a natural number that equals the sum of the factorials of its digits.
Example
145 is a factorion in base 10 because:
1! + 4! + 5! = 1 + 24 + 120 = 145
It can be shown (see talk page) that no factorion in base 10 can exceed 1,4... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hello_world/Newbie | Hello world/Newbie | Task
Guide a new user of a language through the steps necessary
to install the programming language and selection of a text editor if needed,
to run the languages' example in the Hello world/Text task.
Assume the language-newbie is a programmer in another language.
Assume the language-newbie is competent in install... | #AutoHotkey | AutoHotkey | MsgBox, Hello World! | Give a code snippet in #AutoHotkey
Task
Guide a new user of a language through the steps necessary
to install the programming language and selection of a text editor if needed,
to run the languages' example in the Hello world/Text task.
Assume the language-newbie is a programmer in another language.
Assume the lan... | 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
... | #Explore | Explore |
## இந்த நிரல் தரப்படும் சரம் ஒன்றைத் தலைகீழாகத் திருப்பி அச்சிடும்
## உதாரணமாக "abc" என்ற சரம் தரப்பட்டால் அதனைத் திருப்பி "cba" என அச்சிடும்
## "எழில்" மொழியின்மூலம் இரண்டு வகைகளில் இதனைச் செய்யலாம். இரண்டு உதாரணங்களும் இங்கே தரப்பட்டுள்ளன
நிரல்பாகம் திருப்புக (சரம்1)
## முதல் வகை
சரம்2 = ""
@(... | Give a code snippet in #Explore
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
Emp... | christopher/rosetta-code | |
http://rosettacode.org/wiki/2048 | 2048 | Task
Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values.
Rules of the game
The rules are that on each turn the player must choose a direction (up, down, left or right).
All tiles move as far as possible in that direction, some move more than others.
Two ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | SetOptions[InputNotebook[],NotebookEventActions->{
"LeftArrowKeyDown":>(stat=Coalesce[stat];AddNew[]),
"RightArrowKeyDown":>(stat=Reverse/@Coalesce[Reverse/@stat];AddNew[]),
"UpArrowKeyDown":>(stat=Coalesce[stat\[Transpose]]\[Transpose];AddNew[]),
"DownArrowKeyDown":>(stat=(Reverse/@(Coalesce[Reverse/@(stat\[Transpose]... | Give a code snippet in #Mathematica.2FWolfram_Language
Task
Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values.
Rules of the game
The rules are that on each turn the player must choose a direction (up, down, left or right).
All tiles move as far as possible... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects ... | #Ruby | Ruby | class Delegator
attr_accessor :delegate
def operation
if @delegate.respond_to?(:thing)
@delegate.thing
else
'default implementation'
end
end
end
class Delegate
def thing
'delegate implementation'
end
end
if __FILE__ == $PROGRAM_NAME
# No delegate
a = ... | Give a code snippet in #Ruby
A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Horizontal_sundial_calculations | Horizontal sundial calculations | Task
Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location.
For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island, aka Ernest Legouve Reef), wit... | #Racket | Racket | #lang racket
;; print the table for a given latitude and longitude-offset,
;; given in degrees
(define (print-table lat long-offset)
;; print the table header
(display
(~a " sine of latitude: "
(~r (sin (deg->rad lat)) #:precision '(= 3))
"\n"
" diff longitude: "
(~r long-o... | Give a code snippet in #Racket
Task
Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location.
For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Islan... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Formal_power_series | Formal power series | A power series is an infinite sum of the form
a
0
+
a
1
⋅
x
+
a
2
⋅
x
2
+
a
3
⋅
x
3
+
⋯
{\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots }
The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of ... | #EchoLisp | EchoLisp |
(require 'math)
;; converts a finite polynomial (a_0 a_1 .. a_n) to an infinite serie (a_0 ..a_n 0 0 0 ...)
(define (poly->stream list)
(make-stream (lambda(n) (cons (if (< n (length list)) (list-ref list n) 0) (1+ n))) 0))
;; c = a + b , c_n = a_n + b_n
(define (s-add a b)
(make-stream (lambda (n) (cons (+ (str... | Give a code snippet in #EchoLisp
A power series is an infinite sum of the form
a
0
+
a
1
⋅
x
+
a
2
⋅
x
2
+
a
3
⋅
x
3
+
⋯
{\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots }
The ai are called the coefficients of the series. Such sums can be added, multiplied et... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Dijkstra%27s_algorithm | Dijkstra's algorithm | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path pro... | #Java | Java |
import java.io.*;
import java.util.*;
public class Dijkstra {
private static final Graph.Edge[] GRAPH = {
new Graph.Edge("a", "b", 7),
new Graph.Edge("a", "c", 9),
new Graph.Edge("a", "f", 14),
new Graph.Edge("b", "c", 10),
new Graph.Edge("b", "d", 15),
new Graph.Edge("c", "d"... | Give a code snippet in #Java
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the s... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also known as:
taxi numbers
tax... | #REXX | REXX | /*REXX program displays the specified first (lowest) taxicab numbers (for three ranges).*/
parse arg L.1 H.1 L.2 H.2 L.3 H.3 . /*obtain optional arguments from the CL*/
if L.1=='' | L.1=="," then L.1= 1 /*L1 is the low part of 1st range. */
if H.1=='' | H.1=="," then H.1= 25 ... | Give a code snippet in #REXX
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also kno... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sierpinski_carpet | Sierpinski carpet | Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #zkl | zkl | fcn drawPat(x0,y0,s,img){ // Draw 3x3 pattern with hole in middle
foreach y,x in (3,3){
if(x.isEven or y.isEven){ // don't draw middle pattern
if(s>1) self.fcn(x*s + x0, y*s + y0, s/3, img); // recurse
else img[x + x0, y + y0]=0xff0000; // red
}
}
} | Give a code snippet in #zkl
Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## #... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter | Compiler/virtual machine interpreter | A virtual machine implements a computer in software.
Task[edit]
Write a virtual machine interpreter. This interpreter should be able to run virtual
assembly language programs created via the task. This is a
byte-coded, 32-bit word stack based virtual machine.
The program should read input from a file and/or stdin, an... | #ObjectIcon | ObjectIcon | # -*- ObjectIcon -*-
#
# The Rosetta Code virtual machine in Object Icon.
#
# See https://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
#
import io
procedure main(args)
local f_inp, f_out
local vm
if 3 <= *args then {
write("Usage: ", &progname, " [INPUT_FILE [OUTPUT_FILE]]")
exit(1)
}... | Give a code snippet in #ObjectIcon
A virtual machine implements a computer in software.
Task[edit]
Write a virtual machine interpreter. This interpreter should be able to run virtual
assembly language programs created via the task. This is a
byte-coded, 32-bit word stack based virtual machine.
The program should rea... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pancake_numbers | Pancake numbers | Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size... | #Raku | Raku | # 20201110 Raku programming solution
sub pancake(\n) {
my ($gap,$sum,$adj) = 2, 2, -1;
while ($sum < n) { $sum += $gap = $gap * 2 - 1 and $adj++ }
return n + $adj;
}
for (1..20).rotor(5) { say [~] @_».&{ sprintf "p(%2d) = %2d ",$_,pancake $_ } } | Give a code snippet in #Raku
Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stac... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. 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
Create a simple demonstrative example of Currying in a specific la... | #Python | Python | def addN(n):
def adder(x):
return x + n
return adder | Give a code snippet in #Python
This page uses content from Wikipedia. The original article was at Currying. 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
Create a simple demonstrative exam... | 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... | #Oberon-2 | Oberon-2 | MODULE hailst;
IMPORT Out;
CONST maxCard = MAX (INTEGER) DIV 3;
List = 1;
Count = 2;
Max = 3;
VAR a : INTEGER;
PROCEDURE HailStone (start, type : INTEGER) : INTEGER;
VAR n, max, count : INTEGER;
BEGIN
coun... | Give a code snippet in #Oberon-2
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) +... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body... | #FBSL | FBSL | #APPTYPE CONSOLE
FOR DIM i = 10 DOWNTO 0
PRINT i
NEXT
PAUSE
| Give a code snippet in #FBSL
Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increme... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Bioinformatics/base_count | Bioinformatics/base count | Given this string representing ordered DNA bases:
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTG... | #Haskell | Haskell | import Data.List (group, sort)
import Data.List.Split (chunksOf)
import Text.Printf (printf, IsChar(..), PrintfArg(..), fmtChar, fmtPrecision, formatString)
data DNABase = A | C | G | T deriving (Show, Read, Eq, Ord)
type DNASequence = [DNABase]
instance IsChar DNABase where
toChar = head . show
fromC... | Give a code snippet in #Haskell
Given this string representing ordered DNA bases:
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAA... | 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... | #11l | 11l | F ncsub(seq, s = 0)
I seq.empty
R I s >= 3 {[[Int]()]} E [[Int]]()
E
V x = seq[0.<1]
V xs = seq[1..]
V p2 = s % 2
V p1 = !p2
R ncsub(xs, s + p1).map(ys -> @x + ys) [+] ncsub(xs, s + p2)
print(ncsub(Array(1..3)))
print(ncsub(Array(1..4)))
print(ncsub(Array(1..5))) | Give a code snippet in #11l
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 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Fusc_sequence | Fusc sequence |
Definitions
The fusc integer sequence is defined as:
fusc(0) = 0
fusc(1) = 1
for n>1, the nth term is defined as:
if n is even; fusc(n) = fusc(n/2)
if n is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)
Note that MathWorld's definition starts with unity, not zero. Th... | #AppleScript | AppleScript | on fusc(n)
if (n < 2) then
return n
else if (n mod 2 is 0) then
return fusc(n div 2)
else
return fusc((n - 1) div 2) + fusc((n + 1) div 2)
end if
end fusc
set sequence to {}
set longestSoFar to 0
repeat with i from 0 to 60
set fuscNumber to fusc(i)
set end of sequence t... | Give a code snippet in #AppleScript
Definitions
The fusc integer sequence is defined as:
fusc(0) = 0
fusc(1) = 1
for n>1, the nth term is defined as:
if n is even; fusc(n) = fusc(n/2)
if n is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)
Note that MathWorld's definit... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures | Sort an array of composite structures |
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
... | #ooRexx | ooRexx |
a = .array~new
a~append(.pair~new("06-07", "Ducks"))
a~append(.pair~new("00-01", "Avalanche"))
a~append(.pair~new("02-03", "Devils"))
a~append(.pair~new("01-02", "Red Wings"))
a~append(.pair~new("03-04", "Lightning"))
a~append(.pair~new("04-05", "lockout"))
a~append(.pair~new("05-06", "Hurricanes"))
a~append(.pair~... | Give a code snippet in #ooRexx
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/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurren... | #Go | Go | package main
import (
"bufio"
"bytes"
"fmt"
"log"
"math/rand"
"os"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
answers := [...]string{
"It is certain", "It is decidedly so", "Without a doubt",
"Yes, definitely", "You may rely on it", "As I see it, yes",
"Most likely", "Outlook good", "Sig... | Give a code snippet in #Go
Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatic... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #AWK | AWK | BEGIN { # this code does something
# do something
} | Give a code snippet in #AWK
Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
... | #Arturo | Arturo | parts: ["abc" "ABC" [1 2 3]]
loop 0..2 'x ->
print ~"|parts\0\[x]||parts\1\[x]||parts\2\[x]|" | Give a code snippet in #Arturo
Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this exa... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #UNIX_Shell | UNIX Shell | assert() {
if test ! $1; then
[[ $2 ]] && echo "$2" >&2
exit 1
fi
}
x=42
assert "$x -eq 42" "that's not the answer"
((x--))
assert "$x -eq 42" "that's not the answer"
echo "won't get here" | Give a code snippet in #UNIX_Shell
Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin... | #SenseTalk | SenseTalk | put the average of [12,92,-17,66,128]
put average(empty)
| Give a code snippet in #SenseTalk
Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo... | #Raku | Raku | sub Chinese-zodiac ( Int $year ) {
my @heaven = <甲 jiă 乙 yĭ 丙 bĭng 丁 dīng 戊 wù 己 jĭ 庚 gēng 辛 xīn 壬 rén 癸 gŭi>.pairup;
my @earth = <子 zĭ 丑 chŏu 寅 yín 卯 măo 辰 chén 巳 sì 午 wŭ 未 wèi 申 shēn 酉 yŏu 戌 xū 亥 hài>.pairup;
my @animal = <Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog Pig>;
my @el... | Give a code snippet in #Raku
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results... | christopher/rosetta-code | |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retr... | #OCaml | OCaml | #load "unix.cma";;
open Unix;;
let {tm_sec = sec;
tm_min = min;
tm_hour = hour;
tm_mday = mday;
tm_mon = mon;
tm_year = year;
tm_wday = wday;
tm_yday = yday;
tm_isdst = isdst} = localtime (time ());;
Printf.printf "%04d-%02d-%02d %02d:%02d:%02d\n" (year + 1900) (mon + 1) mday hou... | Give a code snippet in #OCaml
Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
... | 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... | #CMake | CMake | function(factorial var n)
set(product 1)
foreach(i RANGE 2 ${n})
math(EXPR product "${product} * ${i}")
endforeach(i)
set(${var} ${product} PARENT_SCOPE)
endfunction(factorial)
factorial(f 12)
message("12! = ${f}") | Give a code snippet in #CMake
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 n... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Greatest_common_divisor | Greatest common divisor | Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related tas... | #Modula-3 | Modula-3 | MODULE GCD EXPORTS Main;
IMPORT IO, Fmt;
PROCEDURE GCD(a, b: CARDINAL): CARDINAL =
BEGIN
IF a = 0 THEN
RETURN b;
ELSIF b = 0 THEN
RETURN a;
ELSIF a > b THEN
RETURN GCD(b, a MOD b);
ELSE
RETURN GCD(a, b MOD a);
END;
END GCD;
BEGIN
IO.Put("GCD of 100, 5 is " & Fmt.I... | Give a code snippet in #Modula-3
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and great... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hello_world/Newbie | Hello world/Newbie | Task
Guide a new user of a language through the steps necessary
to install the programming language and selection of a text editor if needed,
to run the languages' example in the Hello world/Text task.
Assume the language-newbie is a programmer in another language.
Assume the language-newbie is competent in install... | #PHP | PHP | <?php
echo 'Hello, world!';
?>
| Give a code snippet in #PHP
Task
Guide a new user of a language through the steps necessary
to install the programming language and selection of a text editor if needed,
to run the languages' example in the Hello world/Text task.
Assume the language-newbie is a programmer in another language.
Assume the language-n... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for... | #Lua | Lua | t={monday=1, tuesday=2, wednesday=3, thursday=4, friday=5, saturday=6, sunday=0, [7]="fooday"}
for key, value in pairs(t) do
print(value, key)
end | Give a code snippet in #Lua
Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/D... | 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:
*
* *
* *
* * * *
* *
* * * *
... | #TI-83_BASIC | TI-83 BASIC | PROGRAM:SIRPNSKI
:ClrHome
:Output(1,8,"^")
:{0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0}→L1
:{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}→L2
:L2→L3
:For(X,2,8,1)
:For(Y,2,17,1)
:If L1(Y-1)
:Then
:4→N
:End
:If L1(Y)
:Then
:N+2→N
:End
:If L1(Y+1)
:Then
:N+1→N
:End
:If N=1 or N=3 or N=4 or N=6
:Then
:1→L2(Y)
:Output(X,Y-1,"^")
:End
:0→N
:End
:... | Give a code snippet in #TI-83_BASIC
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/Include_a_file | Include a file | Task
Demonstrate the language's ability to include source code from other files.
See Also
Compiler/Simple file inclusion pre processor
| #AArch64_Assembly | AArch64 Assembly |
'file constant include : includeConstantesARM64.inc'
/*******************************************/
/* Constantes */
/*******************************************/
.equ STDIN, 0 // Linux input console
.equ STDOUT, 1 // linux output console
.equ OPEN, 56 ... | Give a code snippet in #AArch64_Assembly
Task
Demonstrate the language's ability to include source code from other files.
See Also
Compiler/Simple file inclusion pre processor
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
... | #Haskell | Haskell | import Data.List ((\\))
comb :: Int -> [a] -> [[a]]
comb 0 _ = [[]]
comb _ [] = []
comb k (x:xs) = map (x:) (comb (k-1) xs) ++ comb k xs
partitions :: [Int] -> [[[Int]]]
partitions xs = p [1..sum xs] xs
where p _ [] = [[]]
p xs (k:ks) = [ cs:rs | cs <- comb k xs, rs <- p (xs \\ cs) ks ]
... | Give a code snippet in #Haskell
In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["AB... | #Pascal | Pascal |
program CommaQuibbling;
uses
SysUtils,
Classes,
StrUtils;
const
OuterBracket =['[', ']'];
type
{$IFNDEF FPC}
SizeInt = LongInt;
{$ENDIF}
{ TCommaQuibble }
TCommaQuibble = class(TStringList)
private
function GetCommaquibble: string;
procedure SetCommaQuibble(AValue: string);
p... | Give a code snippet in #Pascal
Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An i... | 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,... | #Go | Go | package main
import (
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
)
var baseQuery = "http://rosettacode.org/mw/api.php?action=query" +
"&format=xml&list=categorymembers&cmlimit=500"
func req(u string, foundCm func(string)) string {
resp, err :=... | Give a code snippet in #Go
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 202... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Include_a_file | Include a file | Task
Demonstrate the language's ability to include source code from other files.
See Also
Compiler/Simple file inclusion pre processor
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | #with the module system:
!import!foo
#passing a file name (only works with compiled bytecode files):
!run-file "/path/file.vu" | Give a code snippet in #D.C3.A9j.C3.A0_Vu
Task
Demonstrate the language's ability to include source code from other files.
See Also
Compiler/Simple file inclusion pre processor
| 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... | #PureBasic | PureBasic | q)3*2+1
9
q)(3*2)+1 / Brackets give the usual order of precedence
7
q)x:5
q)(x+5; x:20; x-5)
25 20 0 | Give a code snippet in #PureBasic
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... | 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... | #BBC_BASIC | BBC BASIC | *FLOAT64
@% = &1010
PRINT FNfactorial(18)
END
DEF FNfactorial(n)
IF n <= 1 THEN = 1 ELSE = n * FNfactorial(n-1) | Give a code snippet in #BBC_BASIC
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out... | #Bracmat | Bracmat | ( put
$ ( str
$ ( "\nLatin a
ISO-9959-1: "
asc$a
" = "
chr$97
"
UTF-8: "
utf$a
" = "
chu$97
\n
"Cyrillic а (UTF-8): "
utf$а
" = "
chu$1072
\n
)
)
) | Give a code snippet in #Bracmat
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Co... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Modular_inverse | Modular inverse | From Wikipedia:
In modular arithmetic, the modular multiplicative inverse of an integer a modulo m is an integer x such that
a
x
≡
1
(
mod
m
)
.
{\displaystyle a\,x\equiv 1{\pmod {m}}.}
Or in other words, such that:
∃
k
∈
Z
,
a
x
=
1
+
k
m
{\displaystyle \exists k\in \math... | #Seed7 | Seed7 | const func bigInteger: modInverse (in var bigInteger: a,
in var bigInteger: b) is func
result
var bigInteger: modularInverse is 0_;
local
var bigInteger: b_bak is 0_;
var bigInteger: x is 0_;
var bigInteger: y is 1_;
var bigInteger: lastx is 1_;
var bigInteger: lasty is 0_;
var bigIn... | Give a code snippet in #Seed7
From Wikipedia:
In modular arithmetic, the modular multiplicative inverse of an integer a modulo m is an integer x such that
a
x
≡
1
(
mod
m
)
.
{\displaystyle a\,x\equiv 1{\pmod {m}}.}
Or in other words, such that:
∃
k
∈
Z
,
a
x
=
1
+
k
m
{\... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Run-length_encoding | Run-length encoding | Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression... | #Fortran | Fortran | program RLE
implicit none
integer, parameter :: bufsize = 100 ! Sets maximum size of coded and decoded strings, adjust as necessary
character(bufsize) :: teststr = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
character(bufsize) :: codedstr = "", decodedstr = ""
call Encode(tests... | Give a code snippet in #Fortran
Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a fu... | 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... | #OCaml | OCaml | let () =
print_endline Sys.executable_name;
print_endline Sys.argv.(0) | Give a code snippet in #OCaml
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 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/URL_encoding | URL encoding | Task
Provide a function or mechanism to convert a provided string into URL encoding representation.
In URL encoding, special characters, control characters and extended characters
are converted into a percent symbol followed by a two digit hexadecimal code,
So a space character encodes into %20 within the string.
Fo... | #Raku | Raku | my $url = 'http://foo bar/';
say $url.subst(/<-alnum>/, *.ord.fmt("%%%02X"), :g); | Give a code snippet in #Raku
Task
Provide a function or mechanism to convert a provided string into URL encoding representation.
In URL encoding, special characters, control characters and extended characters
are converted into a percent symbol followed by a two digit hexadecimal code,
So a space character encodes i... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin... | #Nemerle | Nemerle | using System;
using System.Console;
using Nemerle.Collections;
module Mean
{
ArithmeticMean(x : list[int]) : double
{
|[] => 0.0
|_ =>(x.FoldLeft(0, _+_) :> double) / x.Length
}
Main() : void
{
WriteLine("Mean of [1 .. 10]: {0}", ArithmeticMean($[1 .. 10]));
}
} | Give a code snippet in #Nemerle
Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an es... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Ruby | Ruby |
%w(north east south west).sample # => "west"
(1..100).to_a.sample(2) # => [17, 79] | Give a code snippet in #Ruby
Demonstrate how to pick a random element from a list.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Nonoblock | Nonoblock | Nonoblock is a chip off the old Nonogram puzzle.
Given
The number of cells in a row.
The size of each, (space separated), connected block of cells to fit in the row, in left-to right order.
Task
show all possible positions.
show the number of positions of the blocks for the following cases within the row. ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[SpacesDistributeOverN, Possibilities]
SpacesDistributeOverN[s_, p_] :=
Flatten[
Permutations /@ (Join[#, ConstantArray[0, p - Length[#]]] & /@
IntegerPartitions[s, p]), 1]
Possibilities[hint_, len_] :=
Module[{p = hint, l = len, b = Length[hint], Spaces, out},
Spaces = # + (Prepend[Append[Constan... | Give a code snippet in #Mathematica.2FWolfram_Language
Nonoblock is a chip off the old Nonogram puzzle.
Given
The number of cells in a row.
The size of each, (space separated), connected block of cells to fit in the row, in left-to right order.
Task
show all possible positions.
show the number of position... | 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 |... | #ERRE | ERRE |
........
A%=100
ADDR=VARPTR(A%)
.......
| Give a code snippet in #ERRE
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
C... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort | Sorting algorithms/Quicksort |
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
... | #Elena | Elena | import extensions;
import system'routines;
import system'collections;
extension op
{
quickSort()
{
if (self.isEmpty()) { ^ self };
var pivot := self[0];
auto less := new ArrayList();
auto pivotList := new ArrayList();
auto more := new ArrayList();
self.for... | Give a code snippet in #Elena
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/Humble_numbers | Humble numbers | Humble numbers are positive integers which have no prime factors > 7.
Humble numbers are also called 7-smooth numbers, and sometimes called highly composite,
although this conflicts with another meaning of highly composite numbers.
Another way to express the above is:
humble = 2i × 3j × 5k... | #zkl | zkl | var [const] BI=Import("zklBigNum"); // libGMP
var one = BI(1), two = BI(2), three = BI(3),
five = BI(5), seven = BI(7);
fcn humble(n){ // --> List of BigInt Humble numbers
h:=List.createLong(n); h.append(one);
next2,next3 := two.copy(), three.copy();
next5,next7 := five.copy(), seven.copy();
... | Give a code snippet in #zkl
Humble numbers are positive integers which have no prime factors > 7.
Humble numbers are also called 7-smooth numbers, and sometimes called highly composite,
although this conflicts with another meaning of highly composite numbers.
Another way to express the above i... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hello_world/Newbie | Hello world/Newbie | Task
Guide a new user of a language through the steps necessary
to install the programming language and selection of a text editor if needed,
to run the languages' example in the Hello world/Text task.
Assume the language-newbie is a programmer in another language.
Assume the language-newbie is competent in install... | #SETL | SETL | setl 'print("Hello, world!");' | Give a code snippet in #SETL
Task
Guide a new user of a language through the steps necessary
to install the programming language and selection of a text editor if needed,
to run the languages' example in the Hello world/Text task.
Assume the language-newbie is a programmer in another language.
Assume the language-... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "chartype.s7i";
const func char: doChar (in boolean: doReverse) is func
result
var char: delimiter is ' ';
local
var char: ch is ' ';
begin
ch := getc(IN);
if ch in letter_char then
if doReverse then
delimiter := doChar(doReverse);
write(... | Give a code snippet in #Seed7
Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only on... | christopher/rosetta-code | |
http://rosettacode.org/wiki/AKS_test_for_primes | AKS test for primes | The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles.
The theorem on which the test is based can be stated as follows:
a number
p
{\displaystyle p}
is prime if and only if all the coefficients of the polynomial ... | #Idris | Idris | import Data.Vect
-- Computes Binomial Coefficients
binCoef : Nat -> Nat -> Nat
binCoef _ Z = (S Z)
binCoef (S n) (S k) =
if n == k then (S Z) else ((S n) * (binCoef n k)) `div` (S k)
-- Binomial Expansion Of (x - 1)^p
expansion : (n : Nat) -> Vect (S n) Integer
expansion n = expansion' n 1
where
expansi... | Give a code snippet in #Idris
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles.
The theorem on which the test is based can be stated as follows:
a number
p
{\displaystyle p}
is prime if and only if all the ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Cistercian_numerals | Cistercian numerals | Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999.
How they work
All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyp... | #Kotlin | Kotlin | import java.io.StringWriter
class Cistercian() {
constructor(number: Int) : this() {
draw(number)
}
private val size = 15
private var canvas = Array(size) { Array(size) { ' ' } }
init {
initN()
}
private fun initN() {
for (row in canvas) {
row.fill... | Give a code snippet in #Kotlin
Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999.
How they work
All Cistercian numerals begin with a vertical line segment, which by itself rep... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip... | #Arturo | Arturo | db: open.sqlite "addresses.db"
query db {!sql
CREATE TABLE address (
addrID INTEGER PRIMARY KEY AUTOINCREMENT,
addrStreet TEXT NOT NULL,
addrCity TEXT NOT NULL,
addrState TEXT NOT NULL,
addrZIP TEXT NOT NULL
)
}
close db | Give a code snippet in #Arturo
Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state c... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
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.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operation... | #Phixmonti | Phixmonti | include ..\Utilitys.pmt
def push /# l i -- l&i #/
0 put
enddef
def empty? /# l -- flag #/
len 0 ==
enddef
def pop /# l -- l-1 #/
empty? if
"Empty"
else
head swap tail nip swap
endif
enddef
( ) /# empty queue #/
1 push 2 push 3 push
pop ? pop ? pop ? pop ? | Give a code snippet in #Phixmonti
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.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in t... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Fraction_reduction | Fraction reduction | There is a fine line between numerator and denominator. ─── anonymous
A method to "reduce" some reducible fractions is to cross out a digit from the
numerator and the denominator. An example is:
16 16
──── and then (simp... | #Phix | Phix | with javascript_semantics
function to_n(sequence digits, integer remove_digit=0)
if remove_digit!=0 then
digits = deep_copy(digits)
integer d = find(remove_digit,digits)
digits[d..d] = {}
end if
integer res = digits[1]
for i=2 to length(digits) do
res = res*10+digits[i]
... | Give a code snippet in #Phix
There is a fine line between numerator and denominator. ─── anonymous
A method to "reduce" some reducible fractions is to cross out a digit from the
numerator and the denominator. An example is:
16 16... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Logo | Logo | Give a code snippet in #Logo
Task
Create the simplest possible program that is still considered "correct."
| christopher/rosetta-code | ||
http://rosettacode.org/wiki/Modular_inverse | Modular inverse | From Wikipedia:
In modular arithmetic, the modular multiplicative inverse of an integer a modulo m is an integer x such that
a
x
≡
1
(
mod
m
)
.
{\displaystyle a\,x\equiv 1{\pmod {m}}.}
Or in other words, such that:
∃
k
∈
Z
,
a
x
=
1
+
k
m
{\displaystyle \exists k\in \math... | #Wren | Wren | import "/big" for BigInt
var a = BigInt.new(42)
var b = BigInt.new(2017)
System.print(a.modInv(b)) | Give a code snippet in #Wren
From Wikipedia:
In modular arithmetic, the modular multiplicative inverse of an integer a modulo m is an integer x such that
a
x
≡
1
(
mod
m
)
.
{\displaystyle a\,x\equiv 1{\pmod {m}}.}
Or in other words, such that:
∃
k
∈
Z
,
a
x
=
1
+
k
m
{\d... | 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 ... | #Oz | Oz | proc {PrintParity X}
if {IsEven X} then
{Show even}
elseif {IsOdd X} then
{Show odd}
else
{Show 'should not happen'}
end
end | Give a code snippet in #Oz
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 con... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Haskell | Haskell | import System.IO
import System.Directory
main = do
removeFile "output.txt"
removeDirectory "docs"
removeFile "/output.txt"
removeDirectory "/docs" | Give a code snippet in #Haskell
Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an avera... | #JavaScript | JavaScript | function simple_moving_averager(period) {
var nums = [];
return function(num) {
nums.push(num);
if (nums.length > period)
nums.splice(0,1); // remove the first element of the array
var sum = 0;
for (var i in nums)
sum += nums[i];
var n = period;
... | Give a code snippet in #JavaScript
Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving averag... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Racket | Racket |
(terminal-port? (current-output-port))
| Give a code snippet in #Racket
Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| 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: ... | #Objeck | Objeck |
use Collection;
class Reducer {
function : Main(args : String[]) ~ Nil {
values := IntVector->New([1, 2, 3, 4, 5]);
values->Reduce(Add(Int, Int) ~ Int)->PrintLine();
values->Reduce(Mul(Int, Int) ~ Int)->PrintLine();
}
function : Add(a : Int, b : Int) ~ Int {
return a + b;
}
function : ... | Give a code snippet in #Objeck
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/Longest_common_substring | Longest common substring | Task
Write a function that returns the longest common substring of two strings.
Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing".
Note that substrings are consecutive characters within a string.... | #Yabasic | Yabasic | sub LCS$(a$, b$)
if len(a$) = 0 or len(b$) = 0 then return "" : endif
while len(b$)
for j = len(b$) to 1 step -1
if instr(a$, left$(b$, j)) then return left$(b$, j) : endif
next j
b$ = mid$(b$, 2)
wend
end sub
print LCS$("thisisatest", "testing123testing")
end | Give a code snippet in #Yabasic
Task
Write a function that returns the longest common substring of two strings.
Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing".
Note that substrings are consec... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Forward_difference | Forward difference | Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer elem... | #Icon_and_Unicon | Icon and Unicon | procedure main(A) # Compute all forward difference orders for argument list
every order := 1 to (*A-1) do showList(order, fdiff(A, order))
end
procedure fdiff(A, order)
every 1 to order do {
every put(B := [], A[i := 2 to *A] - A[i-1])
A := B
}
return A
end
procedure showList(o... | Give a code snippet in #Icon_and_Unicon
Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - A... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Formatted_numeric_output | Formatted numeric output | Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
| #Gambas | Gambas | Public Sub Main()
Print Format("7.125", "00000.000")
End | Give a code snippet in #Gambas
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if ... | #BBC_BASIC | BBC BASIC | FOR col% = 0 TO 14
COLOUR col% : REM foreground
COLOUR 128+(15-col%) : REM background
PRINT "Rosetta Code"
NEXT | Give a code snippet in #BBC_BASIC
Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How... | 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:
*
* *
* *
* * * *
* *
* * * *
... | #Cowgol | Cowgol | include "cowgol.coh";
include "argv.coh";
var order: uint8 := 4; # default order
# Read order from command line if there is an argument
ArgvInit();
var argmt := ArgvNext();
if argmt != 0 as [uint8] then
var a: int32;
(a, argmt) := AToI(argmt);
if a<3 or 7<a then
print("Order must be between 3 a... | Give a code snippet in #Cowgol
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/Random_number_generator_(device) | Random number generator (device) | Task
If your system has a means to generate random numbers involving not only a software algorithm (like the /dev/urandom devices in Unix), then:
show how to obtain a random 32-bit number from that mechanism.
Related task
Random_number_generator_(included)
| #EchoLisp | EchoLisp |
(random-seed "simon")
(random (expt 2 32)) → 2275215386
(random-seed "simon")
(random (expt 2 32)) → 2275215386 ;; the same
(random-seed (current-time-milliseconds ))
(random (expt 2 32)) → 4061857345
(random-seed (current-time-milliseconds ))
(random (expt 2 32)) → 1322611152
| Give a code snippet in #EchoLisp
Task
If your system has a means to generate random numbers involving not only a software algorithm (like the /dev/urandom devices in Unix), then:
show how to obtain a random 32-bit number from that mechanism.
Related task
Random_number_generator_(included)
| christopher/rosetta-code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.