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/Bitwise_operations | Bitwise operations |
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 | : (& 6 3)
-> 2
: (& 7 3 1)
-> 1 | 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/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the i... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function Square(x As Double) As Double
Return x * x
End Function
Function AverageSquareDiff(a As Double, predictions As IEnumerable(Of Double)) As Double
Return predictions.Select(Function(x) Square(x - a)).Average()
End Function
Sub DiversityTheorem(truth As Dou... | Give a code snippet in #Visual_Basic_.NET
The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an exp... | 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 ... | #Lua | Lua | -- 2048 for Lua 5.1-5.4, 12/3/2020 db
local unpack = unpack or table.unpack -- for 5.3 +/- compatibility
game = {
cell = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
best = 0,
draw = function(self)
local t = self.cell
print("+----+----+----+----+")
for r=0,12,4 do
print(string.format("|%4d|%4d|%4d|%4d|\n+... | Give a code snippet in #Lua
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 mo... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Radix_sort | Sorting algorithms/Radix 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
... | #zkl | zkl | fcn radixSort(ns){ // ints only, inplace, ns is mutable
b:=(0).pump(20,List,List().copy); // 20 [empty] buckets: -10..10
z:=ns.reduce(fcn(a,b){ a.abs().max(b.abs()) },0); // |max or min of input|
m:=1;
while(z){
ns.apply2('wrap(n){ b[(n/m)%10 +10].append(n) }); // sort on right digit
ns.clear()... | Give a code snippet in #zkl
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/M%C3%B6bius_function | Möbius function | The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics.
There are several ways to implement a Möbius function.
A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It ha... | #ALGOL_68 | ALGOL 68 | BEGIN
# show the first 199 values of the moebius function #
INT sq root = 1 000;
INT mu max = sq root * sq root;
[ 1 : mu max ]INT mu;
FOR i FROM LWB mu TO UPB mu DO mu[ i ] := 1 OD;
FOR i FROM 2 TO sq root DO
IF mu[ i ] = 1 THEN
# for each factor found, swap... | Give a code snippet in #ALGOL_68
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics.
There are several ways to implement a Möbius function.
A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the s... | 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... | #F.23 | F# | printfn "%s" (System.DateTime.Now.ToString("u")) | Give a code snippet in #F.23
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
D... | 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... | #Run_BASIC | Run BASIC | print "MCMXCIX = "; romToDec( "MCMXCIX") '1999
print "MDCLXVI = "; romToDec( "MDCLXVI") '1666
print "XXV = "; romToDec( "XXV") '25
print "CMLIV = "; romToDec( "CMLIV") '954
print "MMXI = "; romToDec( "MMXI") '2011
function romToDec(roman$)
for i = len(roman$) to 1 step -1
x$ = mid$(roman$, ... | Give a code snippet in #Run_BASIC
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/Knapsack_problem/Bounded | Knapsack problem/Bounded | A tourist wants to make a good trip at the weekend with his friends.
They will go to the mountains to see the wonders of nature. So he needs some items during the trip. Food, clothing, etc. He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weight in his knapsack, because th... | #C | C | #include <stdio.h>
#include <stdlib.h>
typedef struct {
char *name;
int weight;
int value;
int count;
} item_t;
item_t items[] = {
{"map", 9, 150, 1},
{"compass", 13, 35, 1},
{"water", 153, 200, 2},
{"sandwich", ... | Give a code snippet in #C
A tourist wants to make a good trip at the weekend with his friends.
They will go to the mountains to see the wonders of nature. So he needs some items during the trip. Food, clothing, etc. He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weight ... | 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... | #XBasic | XBasic |
PROGRAM "sundial"
VERSION "0.0001"
IMPORT "xma"
DECLARE FUNCTION Entry()
FUNCTION Entry()
lat! = SINGLE(INLINE$("Enter latitude => "))
lng! = SINGLE(INLINE$("Enter longitude => "))
ref! = SINGLE(INLINE$("Enter legal meridian => "))
PRINT
slat! = SIN(lat! * $$PI / 180.0)
PRINT " sine of... | Give a code snippet in #XBasic
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/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)
| #Julia | Julia |
const rdev = "/dev/random"
rstream = try
open(rdev, "r")
catch
false
end
if isa(rstream, IOStream)
b = readbytes(rstream, 4)
close(rstream)
i = reinterpret(Int32, b)[1]
println("A hardware random number is: ", i)
else
println("The hardware random number stream, ", rdev, ", was unavailab... | Give a code snippet in #Julia
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 | |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked ... | #Wren | Wren | // create a new map with four entries
var capitals = {
"France": "Paris",
"Germany": "Berlin",
"Russia": "Moscow",
"Spain": "Madrid"
}
// iterate through the map and print out the key/value pairs
for (c in capitals) System.print([c.key, c.value])
System.print()
// iterate though the map and print ou... | Give a code snippet in #Wren
Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Comp... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Closest-pair_problem | Closest-pair problem |
This page uses content from Wikipedia. The original article was at Closest pair of points problem. 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 function to find the closest two p... | #C | C | class Segment
{
public Segment(PointF p1, PointF p2)
{
P1 = p1;
P2 = p2;
}
public readonly PointF P1;
public readonly PointF P2;
public float Length()
{
return (float)Math.Sqrt(LengthSquared());
}
public float LengthSquared()
{
return (P1.X -... | Give a code snippet in #C
This page uses content from Wikipedia. The original article was at Closest pair of points problem. 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 functio... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Lah_numbers | Lah numbers | Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials.
Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly ordered subsets.
Lah numbers a... | #Vlang | Vlang | import math.big
fn main() {
limit := 100
last := 12
unsigned := true
mut l := [][]big.Integer{len: limit+1}
for n := 0; n <= limit; n++ {
l[n] = []big.Integer{len: limit+1}
for k := 0; k <= limit; k++ {
l[n][k] = big.zero_int
}
l[n][n]= big.integer_from_... | Give a code snippet in #Vlang
Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials.
Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Repeat | Repeat | Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
| #Common_Lisp | Common Lisp | (defun repeat (f n)
(dotimes (i n) (funcall f)))
(repeat (lambda () (format T "Example~%")) 5) | Give a code snippet in #Common_Lisp
Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
| 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... | #Pike | Pike | array(int) x = enumerate(1000,1,1);
`+(@(1.0/pow(x[*],2)[*]));
Result: 1.64393 | Give a code snippet in #Pike
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
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Unbias_a_random_generator | Unbias a random generator |
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
Task details
Use your language's random number generator to create a function/method/sub... | #Haskell | Haskell | import Control.Monad.Random
import Control.Monad
import Text.Printf
randN :: MonadRandom m => Int -> m Int
randN n = fromList [(0, fromIntegral n-1), (1, 1)] | Give a code snippet in #Haskell
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
Task details
Use your language's random number generato... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #REXX | REXX | /*REXX program displays a NxN multiplication table (in a boxed grid) to the terminal.*/
parse arg sz . /*obtain optional argument from the CL.*/
if sz=='' | sz=="," then sz= 12 /*Not specified? Then use the default.*/
w= max(3, length(sz**2) ); __= copies('─', w... | Give a code snippet in #REXX
Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| 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
| #Frege | Frege | module HelloWorld where
main _ = println "Hello world!" | Give a code snippet in #Frege
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
... | 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... | #PL.2FI | PL/I | *process source xref attributes or(!);
/*--------------------------------------------------------------------
* 01.07.2014 Walter Pachl
*-------------------------------------------------------------------*/
clist: Proc Options(main);
Dcl (hbound) Builtin;
Dcl sysprint Print;
Dcl abc(3) Char(2) Init('AA','BB','CC... | Give a code snippet in #PL.2FI
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Semiprime | Semiprime | Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chosen as the length of the Arecib... | #AutoHotkey | AutoHotkey | SetBatchLines -1
k := 1
loop, 100
{
m := semiprime(k)
StringSplit, m_m, m, -
if ( m_m1 = "yes" )
list .= k . " "
k++
}
MsgBox % list
list :=
;===================================================================================================================================
k := 1675
loop, 5
{
m := semiprime(k)... | Give a code snippet in #AutoHotkey
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number wa... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file | Bitmap/Write a PPM file | Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
| #R | R |
# View the existing code in the library
library(pixmap)
pixmap::write.pnm
#Usage
write.pnm(theimage, filename)
| Give a code snippet in #R
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment | Runtime evaluation/In an environment | x
x
x
Do so in a way which:
does not involve string manipulation of the input source code
is plausibly extensible to a runtime-chosen set of bindings rather than just x
does not make x a global variable
or note that these are impossible.
See also
For more general examples and language-specific details, see... | #Sidef | Sidef | func eval_with_x(code, x, y) {
var f = eval(code);
x = y;
eval(code) - f;
}
say eval_with_x(x: 3, y: 5, code: '2 ** x'); # => 24 | Give a code snippet in #Sidef
x
x
x
Do so in a way which:
does not involve string manipulation of the input source code
is plausibly extensible to a runtime-chosen set of bindings rather than just x
does not make x a global variable
or note that these are impossible.
See also
For more general examples and... | christopher/rosetta-code | |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #Ada | Ada | with Lumen.Window;
with Lumen.Events;
with Lumen.Events.Animate;
with GL;
with GLU;
procedure OpenGL is
The_Window : Lumen.Window.Handle;
Program_Exit : Exception;
-- simply exit this program
procedure Quit_Handler (Event : in Lumen.Events.Event_Data) is
begin
raise Program_Exit;
end;
... | Give a code snippet in #Ada
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| 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 ... | #Sidef | Sidef | func index_duplicates(str) {
gather {
for k,v in (str.chars.kv) {
var i = str.index(v, k+1)
take([k, i]) if (i != -1)
}
}
}
var strings = [
"", ".", "abcABC", "XYZ ZYX",
"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ",
"01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X",
"... | Give a code snippet in #Sidef
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 leng... | 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... | #Smalltalk | Smalltalk | String extend [
realIsNumeric [
(self first = $+) |
(self first = $-)
ifTrue: [
^ (self allButFirst) isNumeric
]
ifFalse: [
^ self isNumeric
]
]
]
{ '1234'. "true"
'3.14'. '+3.8111'. "true"
'+45'. "true"
'-3.78'. ... | Give a code snippet in #Smalltalk
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:
Metric... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
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.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
S... | #E | E | def makePoint(x, y) {
def point {
to getX() { return x }
to getY() { return y }
}
return point
} | Give a code snippet in #E
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.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Relat... | christopher/rosetta-code | |
http://rosettacode.org/wiki/A%2BB | A+B | A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.
Task
Given two integers, A and B.
Their sum needs to be calculated.
Input data
Two integers are written in the input stream, separated by space(s):
(
−
1000
≤... | #VHDL | VHDL | LIBRARY std;
USE std.TEXTIO.all;
entity test is
end entity test;
architecture beh of test is
begin
process
variable line_in, line_out : line;
variable a,b : integer;
begin
readline(INPUT, line_in);
read(line_in, a);
read(line_in, b);
write(line_out, a+b);
writeline(OUTPUT, line... | Give a code snippet in #VHDL
A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.
Task
Given two integers, A and B.
Their sum needs to be calculated.
Input data
Two integers are written in the input stream, separated... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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)
The Miller–Rabin primality test or Rabin–Miller prima... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | MillerRabin[n_,k_]:=Module[{d=n-1,s=0,test=True},While[Mod[d,2]==0 ,d/=2 ;s++]
Do[
a=RandomInteger[{2,n-1}]; x=PowerMod[a,d,n];
If[x!=1,
For[ r = 0, r < s, r++, If[x==n-1, Continue[]]; x = Mod[x*x, n]; ];
If[ x != n-1, test=False ];
];
,{k}];
Print[test] ] | Give a code snippet in #Mathematica.2FWolfram_Language
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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)
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Named_parameters | Named parameters | Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this.
Note:
Named parameters relies on being able to use the names give... | #Smalltalk | Smalltalk | Object subclass: AnotherClass [
"..."
initWithArray: anArray [ "single argument" ]
initWithArray: anArray andString: aString [
"two args; these two methods in usage resemble
a named argument, with optional andString argument"
]
"..."
] | Give a code snippet in #Smalltalk
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this.
Note:
Named parameters relies ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points | Circles of given radius through two points |
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
Exceptions
r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
If the points are coincident then an infinite number of circles with the point on thei... | #ALGOL_68 | ALGOL 68 | # represents a point #
MODE POINT = STRUCT( REAL x, REAL y );
# returns TRUE if p1 is the same point as p2, FALSE otherwise #
OP = = ( POINT p1, POINT p2 )BOOL: x OF p1 = x OF p2 AND y OF p1 = y OF p2;
# represents a circle with centre c and radius r ... | Give a code snippet in #ALGOL_68
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
Exceptions
r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
If the points are coincident then an infinite number... | 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.
| #BASIC | BASIC | DECLARE a[] = { 1, 2, 3, 4, 5 }
DECLARE b[] = { 6, 7, 8, 9, 10 }
DECLARE c ARRAY UBOUND(a) + UBOUND(b)
FOR x = 0 TO 4
c[x] = a[x]
c[x+5] = b[x]
NEXT | Give a code snippet in #BASIC
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/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... | #Quackery | Quackery | $ "Sweet Boom Pungent Prickle Orange" nest$
witheach [ i times sp echo$ cr ] | Give a code snippet in #Quackery
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
Lo... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Problem_of_Apollonius | Problem of Apollonius |
Task
Implement a solution to the Problem of Apollonius (description on Wikipedia) which is the problem of finding the circle that is tangent to three specified circles (colored black in the diagram below to the right).
There is an algebraic solution which is pretty straightforward.
The solutions to the ... | #FutureBasic | FutureBasic | Problem of Apollonius
include "NSLog.incl"
begin record Circle
CGPoint center
double radius
CFStringRef locator
end record
local fn CircleToString( c as Circle ) as CFStringRef
end fn = fn StringWithFormat( @"%@ Circle( x = %0.3f, y = %0.3f, radius = %0.3f )", c.locator, c.center.x, c.center.y, c.radius ... | Give a code snippet in #FutureBasic
Task
Implement a solution to the Problem of Apollonius (description on Wikipedia) which is the problem of finding the circle that is tangent to three specified circles (colored black in the diagram below to the right).
There is an algebraic solution which is pretty stra... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Jaro_similarity | Jaro similarity | The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that 0 equates to no similarities and 1 is an exact match.
Definition
The... | #zkl | zkl | //-->String of matched characters, ordered
fcn _jaro(str1,str2, matchDistance){
cs:=Sink(String);
foreach i,c in ([0..].zip(str1)){
str2.find(c,(0).max(i - matchDistance),i + matchDistance) :
if(Void!=_) cs.write(c);
}
cs.close()
}
fcn jaro(str1,str2){
s1Len,s2Len,matchDistance := str1.l... | Give a code snippet in #zkl
The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that 0 equates to no similarities and 1 is an e... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation | Horner's rule for polynomial evaluation | A fast scheme for evaluating a polynomial such as:
−
19
+
7
x
−
4
x
2
+
6
x
3
{\displaystyle -19+7x-4x^{2}+6x^{3}\,}
when
x
=
3
{\displaystyle x=3\;}
.
is to arrange the computation as follows:
(
(
(
(
0
)
x
+
6
)
x
+
(
−
4
)
)
x
+
7
)
x
+
(
−
19
)
{\displaystyle ((((0)x+6)x+(-4))x... | #EchoLisp | EchoLisp |
(define (horner x poly)
(foldr (lambda (coeff acc) (+ coeff (* acc x))) 0 poly))
(horner 3 '(-19 7 -4 6)) → 128
| Give a code snippet in #EchoLisp
A fast scheme for evaluating a polynomial such as:
−
19
+
7
x
−
4
x
2
+
6
x
3
{\displaystyle -19+7x-4x^{2}+6x^{3}\,}
when
x
=
3
{\displaystyle x=3\;}
.
is to arrange the computation as follows:
(
(
(
(
0
)
x
+
6
)
x
+
(
−
4
)
)
x
+
7
)
x
+
(
−
19
)
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm | Bitmap/Bresenham's line algorithm | Task
Using the data storage type defined on the Bitmap page for raster graphics images,
draw a line given two points with Bresenham's line algorithm.
| #C.23 | C# | using System;
using System.Drawing;
using System.Drawing.Imaging;
static class Program
{
static void Main()
{
new Bitmap(200, 200)
.DrawLine(0, 0, 199, 199, Color.Black).DrawLine(199,0,0,199,Color.Black)
.DrawLine(50, 75, 150, 125, Color.Blue).DrawLine(150, 75, 50, 125, Color.Blu... | Give a code snippet in #C.23
Task
Using the data storage type defined on the Bitmap page for raster graphics images,
draw a line given two points with Bresenham's line algorithm.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Queue/Usage | Queue/Usage |
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
Create a queue data structure and demonstrate its operations.
(For implementations of queues, see the FIFO task.)
Ope... | #Phix | Phix | with javascript_semantics
printf(1,"empty:%t\n",empty()) -- true
push_item(5)
printf(1,"empty:%t\n",empty()) -- false
push_item(6)
printf(1,"pop_item:%v\n",pop_item()) -- 5
printf(1,"pop_item:%v\n",pop_item()) -- 6
printf(1,"empty:%t\n",empty()) -- true
| Give a code snippet in #Phix
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
Create a queue data structure and demonstrate its operations.
(For implementations of queu... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Rename_a_file | Rename a file | Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type s... | #LiveCode | LiveCode | rename file "input.txt" to "output.txt"
rename folder "docs" to "mydocs"
rename file "/input.txt" to "/output.txt"
rename folder "/docs" to "/mydocs" | Give a code snippet in #LiveCode
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the... | 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.)
| #Tiny_BASIC | Tiny BASIC |
10 REM this is a comment
20
40 REM from above you can see that line numbers with no statement
50 REM and blank lines also are ignored
| Give a code snippet in #Tiny_BASIC
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/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #Python | Python | def is_palindrome(s):
'''
>>> is_palindrome('')
True
>>> is_palindrome('a')
True
>>> is_palindrome('aa')
True
>>> is_palindrome('baa')
False
>>> is_palindrome('baab')
True
>>> is_palindrome('ba_ab')
True
>>> is_p... | Give a code snippet in #Python
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort | Sorting algorithms/Comb sort | Sorting algorithms/Comb sort
You are encouraged to solve this task according to the task description, using any language you may know.
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 algor... | #Julia | Julia | # v0.6
function combsort!(x::Array)::Array
gap, swaps = length(x), true
while gap > 1 || swaps
gap = floor(Int, gap / 1.25)
i, swaps = 0, false
while i + gap < length(x)
if x[i+1] > x[i+1+gap]
x[i+1], x[i+1+gap] = x[i+1+gap], x[i+1]
swaps = t... | Give a code snippet in #Julia
Sorting algorithms/Comb sort
You are encouraged to solve this task according to the task description, using any language you may know.
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 s... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Globally_replace_text_in_several_files | Globally replace text in several files | Task
Replace every occurring instance of a piece of text in a group of text files with another one.
For this task we want to replace the text "Goodbye London!" with "Hello New York!" for a list of files.
| #Jsish | Jsish | /* Global replace in Jsish */
if (console.args.length == 0) {
console.args.push('-');
}
/* For each file, globally replace "Goodbye London!" with "Hello New York!" */
var fn, data, changed;
for (fn of console.args) {
/* No args, or an argument of - uses "stdin" (a special Channel name) */
if (fn == 'stdin... | Give a code snippet in #Jsish
Task
Replace every occurring instance of a piece of text in a group of text files with another one.
For this task we want to replace the text "Goodbye London!" with "Hello New York!" for a list of files.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Knight%27s_tour | Knight's tour |
Task
Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; that is, the knight need not e... | #Racket | Racket |
#lang racket
(define N 8)
(define nexts ; construct the graph
(let ([ds (for*/list ([x 2] [x* '(+1 -1)] [y* '(+1 -1)])
(cons (* x* (+ 1 x)) (* y* (- 2 x))))])
(for*/vector ([i N] [j N])
(filter values (for/list ([d ds])
(let ([i (+ i (car d))] [j (+ j (cdr d))])
... | Give a code snippet in #Racket
Task
Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Multisplit | Multisplit | It is often necessary to split a string into pieces
based on several different (potentially multi-character) separator strings,
while still retaining the information about which separators were present in the input.
This is particularly useful when doing small parsing tasks.
The task is to write code to demonstrate ... | #Ruby | Ruby | text = 'a!===b=!=c'
separators = ['==', '!=', '=']
def multisplit_simple(text, separators)
text.split(Regexp.union(separators))
end
p multisplit_simple(text, separators) # => ["a", "", "b", "", "c"]
| Give a code snippet in #Ruby
It is often necessary to split a string into pieces
based on several different (potentially multi-character) separator strings,
while still retaining the information about which separators were present in the input.
This is particularly useful when doing small parsing tasks.
The task is... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #ALGOL_68 | ALGOL 68 | curses start; # needed before any screen clearing, positioning etc. #
curses clear # clear the screen # | Give a code snippet in #ALGOL_68
Task
Clear the terminal window.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Copy_stdin_to_stdout | Copy stdin to stdout | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| #zkl | zkl | zkl --eval "File.stdout.write(File.stdin.read())" | Give a code snippet in #zkl
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| 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 ... | #Scala | Scala | class Dot[T](v1: Seq[T])(implicit n: Numeric[T]) {
import n._ // import * operator
def dot(v2: Seq[T]) = {
require(v1.size == v2.size)
(v1 zip v2).map{ Function.tupled(_ * _)}.sum
}
}
object Main extends App {
implicit def toDot[T: Numeric](v1: Seq[T]) = new Dot(v1)
val v1 = List(1, 3, -5)
val v... | Give a code snippet in #Scala
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/Move-to-front_algorithm | Move-to-front algorithm | Given a symbol table of a zero-indexed array of all possible input symbols
this algorithm reversibly transforms a sequence
of input symbols into an array of output numbers (indices).
The transform in many cases acts to give frequently repeated input symbols
lower indices which is useful in some compression algorithms... | #Ada | Ada | with Ada.Text_IO;
procedure Move_To_Front is
subtype Lower_Case is Character range 'a' .. 'z';
subtype Index is Integer range 0 .. 25;
type Table is array (Index) of Lower_Case;
Alphabet: constant Table := "abcdefghijklmnopqrstuvwxyz";
type Number_String is array(Positive range <>) of Natural;
... | Give a code snippet in #Ada
Given a symbol table of a zero-indexed array of all possible input symbols
this algorithm reversibly transforms a sequence
of input symbols into an array of output numbers (indices).
The transform in many cases acts to give frequently repeated input symbols
lower indices which is useful i... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture | Euler's sum of powers conjecture | There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.
Euler's (disproved) sum of powers conjecture
At least k positive kth powers are required to sum to a kth power,
except for the trivial case... | #C.2B.2B | C++ | #include <algorithm>
#include <iostream>
#include <cmath>
#include <set>
#include <vector>
using namespace std;
bool find()
{
const auto MAX = 250;
vector<double> pow5(MAX);
for (auto i = 1; i < MAX; i++)
pow5[i] = (double)i * i * i * i * i;
for (auto x0 = 1; x0 < MAX; x0++) {
for (a... | Give a code snippet in #C.2B.2B
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.
Euler's (disproved) sum of powers conjecture
At least k positive kth powers are required to sum to a kth power... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Textonyms | Textonyms | When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.
Assuming the digit keys are mapped to letters as follows:
2 -> ABC
3 -> DEF
4 -> GHI
5 -> JKL
6 -> MNO
7 -> PQRS
8 -> TUV
9 -... | #Sidef | Sidef | var words = ARGF.grep(/^[[:alpha:]]+\z/);
var dials = words.group_by {
.tr('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
'2223334445556667777888999922233344455566677778889999');
}
var textonyms = dials.grep_v { .len > 1 };
say <<-END;
There are #{words.len} words which can be represented... | Give a code snippet in #Sidef
When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.
Assuming the digit keys are mapped to letters as follows:
2 -> ABC
3 -> DEF
4 -> GHI
5 -> JKL
6 -> MNO
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #Factor | Factor | USING: assocs formatting io kernel math math.primes.factors
math.ranges sequences sequences.extras ;
ERROR: nonpositive n ;
: (tau) ( n -- count )
group-factors values [ 1 + ] map-product ; inline
: tau ( n -- count ) dup 0 > [ (tau) ] [ nonpositive ] if ;
"Number of divisors for integers 1-100:" print nl
"... | Give a code snippet in #Factor
Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program ... | #Commodore_BASIC | Commodore BASIC | 10 DATA 49,54,48,32,78,61,51,51,48,13,49,55,48,32,68,73,77,32,65,40,78,41,13
20 DATA 49,56,48,32,70,79,82,32,73,61,48,32,84,79,32,78,13,49,57,48,32,58,32
30 DATA 82,69,65,68,32,65,40,73,41,13,50,48,48,32,78,69,88,84,32,73,13,50,49
40 DATA 48,32,70,79,82,32,73,61,48,32,84,79,32,49,52,32,13,50,50,48,32,58,32
50 DATA 80,8... | Give a code snippet in #Commodore_BASIC
A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to ... | #Oforth | Oforth | [.06, .11, .16, .21, .26, .31, .36, .41, .46, .51, .56, .61, .66, .71, .76, .81, .86, .91, .96, 1.01] const: IN
[.10, .18, .26, .32, .38, .44, .50, .54, .58, .62, .66, .70, .74, .78, .82, .86, .90, .94, .98, 1.00] const: OUT
: priceFraction(f)
| i |
IN size loop: i [ f IN at(i) < ifTrue: [ OUT at(i) return ] ]
... | Give a code snippet in #Oforth
A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. 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 mathematics, Euler's identity is the equality:
... | #Ruby | Ruby |
include Math
E ** (PI * 1i) + 1
# => (0.0+0.0i) | Give a code snippet in #Ruby
This page uses content from Wikipedia. The original article was at Euler's_identity. 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 mathematics, Euler's identity i... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Merge_sort | Sorting algorithms/Merge 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
... | #Lucid | Lucid | msort(a) = if iseod(first next a) then a else merge(msort(b0),msort(b1)) fi
where
p = false fby not p;
b0 = a whenever p;
b1 = a whenever not p;
just(a) = ja
where
ja = a fby if iseod ja then eod else next a fi;
end;
merge(x,y) = if takexx then xx else yy fi
where
xx = (... | Give a code snippet in #Lucid
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/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, a... | #Swift | Swift | class MyClass{
// stored property
var variable : Int
/**
* The constructor
*/
init() {
self.variable = 42
}
/**
* A method
*/
func someMethod() {
self.variable = 1
}
} | Give a code snippet in #Swift
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the cla... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Substring | Substring |
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 |... | #Tailspin | Tailspin | [$s...] | Give a code snippet in #Tailspin
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/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... | #11l | 11l | L(i) (10..0).step(-1)
print(i) | Give a code snippet in #11l
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/Incremen... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #Erlang | Erlang |
-module( date_manipulation ).
-export( [task/0] ).
task() ->
{Date_time, TZ} = date_time_tz_from_string( "March 7 2009 7:30pm EST" ),
Seconds1 = calendar:datetime_to_gregorian_seconds( Date_time ),
Seconds2 = calendar:datetime_to_gregorian_seconds( {calendar:gregorian_days_to_date(0), {12, 0, 0}} ),
Date_time... | Give a code snippet in #Erlang
Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the cha... | #PureBasic | PureBasic |
EnableExplicit
#Separator$ = ","
Define fInput$ = "input.csv"; insert path to input file
Define fOutput$ = "output.csv"; insert path to output file
Define header$, row$, field$
Define nbColumns, sum, i
If OpenConsole()
If Not ReadFile(0, fInput$)
PrintN("Error opening input file")
Goto Finish
EndI... | Give a code snippet in #PureBasic
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Bitcoin/address_validation | Bitcoin/address validation | Bitcoin/address validation
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Write a program that takes a bitcoin address as argument,
and checks whether or not this address is valid.
A bitcoin address uses a base58 encoding, which uses an alphabet of th... | #Scala | Scala | import java.security.MessageDigest
import java.util.Arrays.copyOfRange
import scala.annotation.tailrec
import scala.math.BigInt
object BitcoinAddressValidator extends App {
private def bitcoinTestHarness(address: String, expected: Boolean): Unit =
assert(validateBitcoinAddress(=1J26TeMg6uK9GkoCKkHNeDaKwtFWd... | Give a code snippet in #Scala
Bitcoin/address validation
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Write a program that takes a bitcoin address as argument,
and checks whether or not this address is valid.
A bitcoin address uses a base58 encodin... | christopher/rosetta-code | |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #Locomotive_Basic | Locomotive Basic | 10 mode 1:defint a-z
20 while n<4:input "How many queens (N>=4)";n:wend
30 dim q(n),e(n),o(n)
40 r=n mod 6
50 if r<>2 and r<>3 then gosub 320:goto 220
60 for i=1 to int(n/2)
70 e(i)=2*i
80 next
90 for i=1 to round(n/2)
100 o(i)=2*i-1
110 next
120 if r=2 then gosub 410
130 if r=3 then gosub 460
140 s=1
150 for i=1 to n
... | Give a code snippet in #Locomotive_Basic
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Random_numbers | Random numbers | Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Related task
Standard deviation
| #C.2B.2B | C++ | #include <random>
#include <functional>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
random_device seed;
mt19937 engine(seed());
normal_distribution<double> dist(1.0, 0.5);
auto rnd = bind(dist, engine);
vector<double> v(1000);
generate(v.begin(), v.end(), rnd);
return 0;
} | Give a code snippet in #C.2B.2B
Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Relat... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Entropy/Narcissist | Entropy/Narcissist |
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| #Emacs_Lisp | Emacs Lisp | (defun shannon-entropy (input)
(let ((freq-table (make-hash-table))
(entropy 0)
(length (+ (length input) 0.0)))
(mapcar (lambda (x)
(puthash x
(+ 1 (gethash x freq-table 0))
freq-table))
input)
(maphash (lambda (k v)
(set 'entropy (+ entropy
(* (/ v length)
... | Give a code snippet in #Emacs_Lisp
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Nim_game | Nim game | Nim game
You are encouraged to solve this task according to the task description, using any language you may know.
Nim is a simple game where the second player ─── if they know the trick ─── will always win.
The game has only 3 rules:
start with 12 tokens
each player takes 1, 2, or 3 tokens in tur... | #Action.21 | Action! | BYTE FUNC PlayerTurn(BYTE tokens)
BYTE t,max
IF tokens<3 THEN
max=tokens
ELSE
max=3
FI
DO
PrintF("How many tokens would you like to take (1-%B)? ",max)
t=InputB()
UNTIL t>=1 AND t<=max
OD
PrintF("Player takes %B tokens.%E",t)
t=tokens-t
IF t=0 THEN
PrintE("Player wins.")
FI... | Give a code snippet in #Action.21
Nim game
You are encouraged to solve this task according to the task description, using any language you may know.
Nim is a simple game where the second player ─── if they know the trick ─── will always win.
The game has only 3 rules:
start with 12 tokens
each player ta... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func integer: m (in integer: n) is forward;
const func integer: f (in integer: n) is func
result
var integer: res is 0;
begin
if n = 0 then
res := 1;
else
res := n - m(f(n - 1));
end if;
end func;
const func integer: m (in integer: n) is func
res... | Give a code snippet in #Seed7
Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes | Carmichael 3 strong pseudoprimes | A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it.
The Miller Rabin Test uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this.
The purpose of this task is to investigate such numbers using a met... | #Go | Go | package main
import "fmt"
// Use this rather than % for negative integers
func mod(n, m int) int {
return ((n % m) + m) % m
}
func isPrime(n int) bool {
if n < 2 { return false }
if n % 2 == 0 { return n == 2 }
if n % 3 == 0 { return n == 3 }
d := 5
for d * d <= n {
if n % d == 0 {... | Give a code snippet in #Go
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it.
The Miller Rabin Test uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this.
The purpose of this task is to investig... | christopher/rosetta-code | |
http://rosettacode.org/wiki/GUI_enabling/disabling_of_controls | GUI enabling/disabling of controls | In addition to fundamental GUI component interaction, an application should
dynamically enable and disable GUI components, to give some guidance to the
user, and prohibit (inter)actions which are inappropriate in the current state
of the application.
Task
Similar to the task GUI component interaction, write a progr... | #Liberty_BASIC | Liberty BASIC | nomainwin
textbox #demo.val, 20, 50, 90, 24
button #demo.dec, "Decrement", [btnDecrement], UL, 20, 90, 90, 24
button #demo.inc, "Increment", [btnIncrement], UL, 20, 120, 90, 24
statictext #demo.txt, "Positive or negative whole numbers only.", 20, 170, 240, 24
open "Rosetta Task: GUI enabling/disabli... | Give a code snippet in #Liberty_BASIC
In addition to fundamental GUI component interaction, an application should
dynamically enable and disable GUI components, to give some guidance to the
user, and prohibit (inter)actions which are inappropriate in the current state
of the application.
Task
Similar to the task G... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hickerson_series_of_almost_integers | Hickerson series of almost integers | The following function, due to D. Hickerson, is said to generate "Almost integers" by the
"Almost Integer" page of Wolfram MathWorld, (December 31 2013). (See formula numbered 51.)
The function is:
h
(
n
)
=
n
!
2
(
ln
2
)
n
+
1
{\displaystyle h(n)={\operatorname {n} ! \ove... | #AWK | AWK |
# syntax: GAWK -M -f HICKERSON_SERIES_OF_ALMOST_INTEGERS.AWK
# using GNU Awk 4.1.0, API: 1.0 (GNU MPFR 3.1.2, GNU MP 5.1.2)
BEGIN {
PREC = 100
for (i=1; i<=17; i++) {
h = sprintf("%25.5f",factorial(i) / (2 * log(2) ^ (i + 1)))
msg = (h ~ /\.[09]/) ? "true" : "false"
printf("%2d %s almost int... | Give a code snippet in #AWK
The following function, due to D. Hickerson, is said to generate "Almost integers" by the
"Almost Integer" page of Wolfram MathWorld, (December 31 2013). (See formula numbered 51.)
The function is:
h
(
n
)
=
n
!
2
(
ln
2
)
n
+
1
{\displaystyle h... | 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
... | #SNOBOL4 | SNOBOL4 | * # Sort array in place, return array
define('bubble(a,alen)i,j,ub,tmp') :(bubble_end)
bubble i = 1; ub = alen
outer gt(ub,1) :f(bdone)
j = 1
inner le(a<j>, a<j + 1>) :s(incrj)
tmp = a<j>
a<j> = a<j + 1>
a<j + 1> = tmp
incrj j = lt(j + 1,ub) j + 1 :s(inner)
u... | Give a code snippet in #SNOBOL4
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 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division | Sequence of primes by trial division | Sequence of primes by trial division
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate a sequence of primes by means of trial division.
Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by... | #Scala | Scala | def sieve(nums: Stream[Int]): Stream[Int] =
Stream.cons(nums.head, sieve((nums.tail).filter(_ % nums.head != 0)))
val primes = 2 #:: sieve(Stream.from(3, 2))
println(primes take 10 toList) // //List(2, 3, 5, 7, 11, 13, 17, 19, 23, 29)
println(primes takeWhile (_ < 30) toList) //List(2, 3, 5, 7, 11, ... | Give a code snippet in #Scala
Sequence of primes by trial division
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate a sequence of primes by means of trial division.
Trial division is an algorithm where a candidate number is tested for being a ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Window_creation | Window creation | Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
| #Forth | Forth | include ffl/gsv.fs
\ Open the connection to the gtk-server and load the Gtk2 definitions
s" gtk-server.cfg" s" ffl-fifo" gsv+open 0= [IF]
\ Convert the string event to a widget id
: event>widget
0. 2swap >number 2drop d>s
;
0 value window
: window-creation
gtk_init
\ Create the window
GTK_WINDOW_TOPLE... | Give a code snippet in #Forth
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
| 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... | #PicoLisp | PicoLisp | (load "@lib/http.l")
(de maclookup (M)
(client "api.macvendors.com" 80
M
(while (line))
(line T) ) )
(test
"Intel Corporate"
(maclookup "88:53:2E:67:07:BE") )
(test
"Apple, Inc."
(maclookup "D4:F4:6F:C9:EF:8D") ) | Give a code snippet in #PicoLisp
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 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort | Sorting algorithms/Insertion 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
... | #Ksh | Ksh | #!/bin/ksh
# An insertion sort in ksh
# # Variables:
#
typeset -a arr=( 4 65 2 -31 0 99 2 83 782 1 )
# # Functions:
#
# # Function _insertionSort(array) - Insersion sort of array of integers
#
function _insertionSort {
typeset _arr ; nameref _arr="$1"
typeset _i _j _val ; integer _i _j _val
for (( _i=1;... | Give a code snippet in #Ksh
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/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which ... | #Scheme | Scheme | (define (palindrome? s)
(let ((chars (string->list s)))
(equal? chars (reverse chars)))) | Give a code snippet in #Scheme
A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly a... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Idiomatically_determine_all_the_lowercase_and_uppercase_letters | Idiomatically determine all the lowercase and uppercase letters |
Idiomatically determine all the lowercase and uppercase letters (of the Latin [English] alphabet) being used currently by a computer programming language.
The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).
Task requirements
Display the set of... | #Factor | Factor |
USE: math.ranges
CHAR: A CHAR: Z [a,b] >string print
CHAR: a CHAR: z [a,b] >string print
| Give a code snippet in #Factor
Idiomatically determine all the lowercase and uppercase letters (of the Latin [English] alphabet) being used currently by a computer programming language.
The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).
Task... | christopher/rosetta-code | |
http://rosettacode.org/wiki/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and... | #Component_Pascal | Component Pascal |
MODULE BbtComputeCRC32;
IMPORT ZlibCrc32,StdLog;
PROCEDURE Do*;
VAR
s: ARRAY 128 OF SHORTCHAR;
BEGIN
s := "The quick brown fox jumps over the lazy dog";
StdLog.IntForm(ZlibCrc32.CRC32(0,s,0,LEN(s$)),16,12,'0',TRUE);
StdLog.Ln;
END Do;
END BbtComputeCRC32.
| Give a code snippet in #Component_Pascal
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first orde... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Cheryl%27s_birthday | Cheryl's birthday | Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.
Cheryl gave them a list of ten possible dates:
May 15, May 16, May 19
June 17, June 18
July 14, July 16
August 14, August 15, August 17
Cheryl then tells Albert the month of birth, ... | #Java | Java | import java.time.Month;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class Main {
private static class Birthday {
private Month month;
private int day;
public Birthday(Month month, int day) {
this.month =... | Give a code snippet in #Java
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.
Cheryl gave them a list of ten possible dates:
May 15, May 16, May 19
June 17, June 18
July 14, July 16
August 14, August 15, August 17
Cheryl then tells A... | 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... | #Scala | Scala | val inf = Double.PositiveInfinity //defined as 1.0/0.0
inf.isInfinite; //true | Give a code snippet in #Scala
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/Higher-order_functions | Higher-order functions | Task
Pass a function as an argument to another function.
Related task
First-class functions
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | PassFunc[f_, g_, h_, x_] := f[g[x]*h[x]]
PassFunc[Tan, Cos, Sin, x]
% /. x -> 0.12
PassFunc[Tan, Cos, Sin, 0.12] | Give a code snippet in #Mathematica_.2F_Wolfram_Language
Task
Pass a function as an argument to another function.
Related task
First-class functions
| 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 ... | #Action.21 | Action! | INT FUNC DotProduct(INT ARRAY v1,v2 BYTE len)
BYTE i,res
res=0
FOR i=0 TO len-1
DO
res==+v1(i)*v2(i)
OD
RETURN (res)
PROC PrintVector(INT ARRAY a BYTE size)
BYTE i
Put('[)
FOR i=0 TO size-1
DO
PrintI(a(i))
IF i<size-1 THEN
Put(',)
FI
OD
Put('])
RETURN
PROC Test(INT AR... | Give a code snippet in #Action.21
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to... | #Lambdatalk | Lambdatalk |
{def caesar
{def caesar.alphabet {A.split ABCDEFGHIJKLMNOPQRSTUVWXYZ}}
{def caesar.delta
{lambda {:s :i :a}
{A.get {% {+ {A.in? {A.get :i :a} {caesar.alphabet}} 26 :s} 26}
{caesar.alphabet}}}}
{def caesar.loop
{lambda {:s :a :b :n :i}
{if {> :i :n}
then :b
else {caesar.r :s
... | Give a code snippet in #Lambdatalk
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Program_termination | Program termination |
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks... | #Retro | Retro | problem? [ bye ] if | Give a code snippet in #Retro
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers... | 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
| #Babel | Babel | "Hello world!" << | Give a code snippet in #Babel
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
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Named_parameters | Named parameters | Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this.
Note:
Named parameters relies on being able to use the names give... | #Tcl | Tcl | proc example args {
# Set the defaults
array set opts {-foo 0 -bar 1 -grill "hamburger"}
# Merge in the values from the caller
array set opts $args
# Use the arguments
return "foo is $opts(-foo), bar is $opts(-bar), and grill is $opts(-grill)"
}
# Note that -foo is omitted and -grill precedes -b... | Give a code snippet in #Tcl
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this.
Note:
Named parameters relies on bei... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Here_document | Here document | A here document (or "heredoc") is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text.
Depending on the language being used, a here document is constructed using a command followed by "<<" (or some other symbol) followed by a token string.
The text ... | #Phix | Phix | string ts1 = """
this
"string"\thing"""
string ts2 = """this
"string"\thing"""
string ts3 = """
_____________this
"string"\thing"""
string ts4 = `
this
"string"\thing`
string ts5 = `this
"string"\thing`
string ts6 = `
_____________this
"string"\thing`
string ts7 = "this\n\"string\"... | Give a code snippet in #Phix
A here document (or "heredoc") is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text.
Depending on the language being used, a here document is constructed using a command followed by "<<" (or some other symbol) followed... | 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 ... | #Python | Python | '''Determine if a string has all unique characters'''
from itertools import groupby
# duplicatedCharIndices :: String -> Maybe (Char, [Int])
def duplicatedCharIndices(s):
'''Just the first duplicated character, and
the indices of its occurrence, or
Nothing if there are no duplications.
'''
... | Give a code snippet in #Python
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 len... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Accumulator_factory | Accumulator factory | A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat... | #BBC_BASIC | BBC BASIC | x = FNaccumulator(1)
dummy = FN(x)(5)
dummy = FNaccumulator(3)
PRINT FN(x)(2.3)
END
DEF FNaccumulator(sum)
LOCAL I%, P%, Q%
DIM P% 53 : Q% = !^FNdummy()
FOR I% = 0 TO 49 : P%?I% = Q%?I% : NEXT
P%!I% = P% : sum = FN(P%+I%)(sum)
= P%+I%
DEF FNdum... | Give a code snippet in #BBC_BASIC
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Fibonacci_word/fractal | Fibonacci word/fractal |
The Fibonacci word may be represented as a fractal as described here:
(Clicking on the above website (hal.archives-ouvertes.fr) will leave a cookie.)
For F_wordm start with F_wordCharn=1
Draw a segment forward
If current F_wordChar is 0
Turn left if n is even
Turn right if n is odd
next n and iterate until e... | #R | R |
## Fibonacci word/fractal 2/20/17 aev
## Create Fibonacci word order n
fibow <- function(n) {
t2="0"; t1="01"; t="";
if(n<2) {n=2}
for (i in 2:n) {t=paste0(t1,t2); t2=t1; t1=t}
return(t)
}
## Plot Fibonacci word/fractal:
## n - word order, w - width, h - height, d - segment size, clr - color.
pfibofractal <-... | Give a code snippet in #R
The Fibonacci word may be represented as a fractal as described here:
(Clicking on the above website (hal.archives-ouvertes.fr) will leave a cookie.)
For F_wordm start with F_wordCharn=1
Draw a segment forward
If current F_wordChar is 0
Turn left if n is even
Turn right if n is odd... | 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 .
| #Wren | Wren | import "graphics" for Canvas, Color
import "dome" for Window
var MaxIters = 570
var Zoom = 150
class MandelbrotSet {
construct new(width, height) {
Window.title = "Mandelbrot Set"
Window.resize(width, height)
Canvas.resize(width, height)
_w = width
_h = height
}
... | Give a code snippet in #Wren
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/Literals/Integer | Literals/Integer | Some programming languages have ways of expressing integer literals in bases other than the normal base ten.
Task
Show how integer literals can be expressed in as many bases as your language allows.
Note: this should not involve the calling of any functions/methods, but should be interpreted by the compiler or... | #Verbexx | Verbexx | // Integer Literals:
//
// If present, base prefix must be: 0b 0B (binary) 0o 0O (octal)
// 0x 0X (hex)
//
// If present, length suffix must be: i I i64 I64 (INT64_T)
// u U u64 U64 (UINT64_T)
// ... | Give a code snippet in #Verbexx
Some programming languages have ways of expressing integer literals in bases other than the normal base ten.
Task
Show how integer literals can be expressed in as many bases as your language allows.
Note: this should not involve the calling of any functions/methods, but should ... | 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... | #F.23 | F# | open System.Text.RegularExpressions
let splitRuns s = Regex("""(.)\1*""").Matches(s) |> Seq.cast<Match> |> Seq.map (fun m -> m.Value) |> Seq.toList
printfn "%A" (splitRuns """gHHH5YY++///\""") | Give a code snippet in #F.23
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that ... | #Lobster | Lobster | import std
// Derived from Julia and Python versions
def get_divisors(n: int) -> [int]:
var i = 2
let d = [1, n]
let limit = sqrt(n)
while i <= limit:
if n % i == 0:
let j = n / i
push(d,i)
if i != j:
push(d,j)
i += 1
return d
... | Give a code snippet in #Lobster
Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the div... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #Common_Lisp | Common Lisp | (defun sum-of-squares (vector)
(loop for x across vector sum (expt x 2))) | Give a code snippet in #Common_Lisp
Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Heronian_triangles | Heronian triangles | Hero's formula for the area of a triangle given the length of its three sides a, b, and c is given by:
A
=
s
(
s
−
a
)
(
s
−
b
)
(
s
−
c
)
,
{\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},}
where s is half the perimeter of the triangle; that is,
s
=
a
+
b
+
c
2
.
{\displaystyle s... | #jq | jq | # input should be an array of the lengths of the sides
def hero:
(add/2) as $s
| ($s*($s - .[0])*($s - .[1])*($s - .[2])) as $a2
| if $a2 > 0 then ($a2 | sqrt) else 0 end;
def is_heronian:
hero as $h
| $h > 0 and ($h|floor) == $h;
def gcd3(x; y; z):
# subfunction expects [a,b] as input
def rgcd:
i... | Give a code snippet in #jq
Hero's formula for the area of a triangle given the length of its three sides a, b, and c is given by:
A
=
s
(
s
−
a
)
(
s
−
b
)
(
s
−
c
)
,
{\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},}
where s is half the perimeter of the triangle; that is,
s
=
a
+
b
+... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Logo | Logo | ? make readword readword
julie
12
? show :julie
12 | Give a code snippet in #Logo
Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| 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.
| #Stata | Stata | assert x<y if z>0 | Give a code snippet in #Stata
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/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... | #Scheme | Scheme |
(define (compare-strings fn strs)
(or (null? strs) ; returns #t on empty list
(null? (cdr strs)) ; returns #t on list of size 1
(do ((fst strs (cdr fst))
(snd (cdr strs) (cdr snd)))
((or (null? snd)
(not (fn (car fst) (car... | Give a code snippet in #Scheme
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Execute_Brain**** | Execute Brain**** | Execute Brain**** is an implementation of Brainf***.
Other implementations of Brainf***.
RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages.
Below are links to each of the versions of RCBF.
An implementation need only properly implement the following instructions:... | #dodo0 | dodo0 | #Import some functions
clojure('count', 1) -> size
clojure('nth', 2) -> charAt
clojure('inc', 1) -> inc
clojure('dec', 1) -> dec
clojure('char', 1) -> char
clojure('int', 1) -> int
clojure('read-line', 0) -> readLine
#The characters we will need
charAt("\n", 0) -> newLine
charAt("@", 0) -> exitCommand
charAt("+", 0) ... | Give a code snippet in #dodo0
Execute Brain**** is an implementation of Brainf***.
Other implementations of Brainf***.
RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages.
Below are links to each of the versions of RCBF.
An implementation need only properly implem... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Input_loop | Input loop | Input loop is part of Short Circuit's Console Program Basics selection.
Task
Read from a text stream either word-by-word or line-by-line until the stream runs out of data.
The stream will have an unknown amount of data on it.
| #Fortran | Fortran | program BasicInputLoop
implicit none
integer, parameter :: in = 50, &
linelen = 1000
integer :: ecode
character(len=linelen) :: l
open(in, file="afile.txt", action="read", status="old", iostat=ecode)
if ( ecode == 0 ) then
do
read... | Give a code snippet in #Fortran
Input loop is part of Short Circuit's Console Program Basics selection.
Task
Read from a text stream either word-by-word or line-by-line until the stream runs out of data.
The stream will have an unknown amount of data on it.
| christopher/rosetta-code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.