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/Synchronous_concurrency | Synchronous concurrency | The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th... | #Visual_Basic_.NET | Visual Basic .NET | Imports System.Threading
Module Module1
Sub Main()
Dim t1 As New Thread(AddressOf Reader)
Dim t2 As New Thread(AddressOf Writer)
t1.Start()
t2.Start()
t1.Join()
t2.Join()
End Sub
Sub Reader()
For Each line In IO.File.ReadAllLines("input.txt")
m_... | Give a code snippet in #Visual_Basic_.NET
The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute z... | #Gambas | Gambas | Public Sub Form_Open()
Dim fKelvin As Float
fKelvin = InputBox("Enter a Kelvin value", "Kelvin converter")
Print "Kelvin =\t" & Format(Str(fKelvin), "#.00")
Print "Celsius =\t" & Format(Str(fKelvin - 273.15), "#.00")
Print "Fahrenheit =\t" & Format(Str(fKelvin * 1.8 - 459.67), "#.00")
Print "Rankine =\t" & Format(S... | Give a code snippet in #Gambas
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15... | 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... | #8th | 8th |
\ return "extended gcd" of a and b; The result satisfies the equation:
\ a*x + b*y = gcd(a,b)
: n:xgcd \ a b -- gcd x y
dup 0 n:= if
1 swap \ -- a 1 0
else
tuck n:/mod
-rot recurse
tuck 4 roll
n:* n:neg n:+
then ;
\ Return modular inverse of n modulo mod, or null if it does... | Give a code snippet in #8th
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
{\di... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/Do-while | Loops/Do-while | Start with a value at 0. Loop while value mod 6 is not equal to 0.
Each time through the loop, add 1 to the value then print it.
The loop must execute at least once.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loo... | #Chapel | Chapel | var val = 0;
do {
val += 1;
writeln(val);
} while val % 6 > 0; | Give a code snippet in #Chapel
Start with a value at 0. Loop while value mod 6 is not equal to 0.
Each time through the loop, add 1 to the value then print it.
The loop must execute at least once.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Stable_marriage_problem | Stable marriage problem | Solve the Stable marriage problem using the Gale/Shapley algorithm.
Problem description
Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.
A stable set of engagements for marriage is o... | #EchoLisp | EchoLisp |
(lib 'hash)
;; input data
(define M-RANKS
'(( abe abi eve cath ivy jan dee fay bea hope gay)
( bob cath hope abi dee eve fay bea jan ivy gay)
( col hope eve abi dee bea fay ivy gay cath jan)
( dan ivy fay dee gay hope eve jan bea cath abi)
( ed jan dee bea cath fay eve abi ivy hope gay)
( fred bea abi dee gay e... | Give a code snippet in #EchoLisp
Solve the Stable marriage problem using the Gale/Shapley algorithm.
Problem description
Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.
A stable se... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Multiple_regression | Multiple regression | Task
Given a set of data vectors in the following format:
y
=
{
y
1
,
y
2
,
.
.
.
,
... | #ERRE | ERRE | PROGRAM MULTIPLE_REGRESSION
!$DOUBLE
CONST N=14,M=2,Q=3 ! number of points and M.R. polynom degree
DIM X[N],Y[N] ! data points
DIM S[N],T[N] ! linear system coefficient
DIM A[M,Q] ! sistem to be solved
BEGIN
DATA(1.47,1.50,1.52,1.55,1.57,1.60,1.63,1.65,1.68,1.70,1.73,1.75,1.78,1.80,1.83)
... | Give a code snippet in #ERRE
Task
Given a set of data vectors in the following format:
y
=
{
y
1
,
y
2
,
.
.
.... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ... | #PowerShell | PowerShell |
function FibonacciNumber ( $count )
{
$answer = @(0,1)
while ($answer.Length -le $count)
{
$answer += $answer[-1] + $answer[-2]
}
return $answer
}
| Give a code snippet in #PowerShell
The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solution... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle | Pascal's triangle/Puzzle | This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers.
[ 151]
[ ][ ]
[40][ ][ ]
[ ][ ][ ][ ]
[ X][11][ Y][ 4][ Z]
Each brick of the pyramid is the sum of the two bricks situated below it.
Of the three missing numbers at the base of the pyramid,
the... | #F.23 | F# |
#load"Packages\MathNet.Numerics.FSharp\MathNet.Numerics.fsx"
open MathNet.Numerics.LinearAlgebra
let A = matrix [
[ 1.; 1.; 0.; 0.; 0.; 0.; 0.; 0.; 0.; 0.; 0. ]
[ -1.; 0.; 1.; 0.; 0.; 0.; 0.; 0.; 0.; 0.; 0. ]
[ 0.; -1.; 1.; 1.; 0.; 0.; 0.; 0.; 0.; 0.; 0... | Give a code snippet in #F.23
This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers.
[ 151]
[ ][ ]
[40][ ][ ]
[ ][ ][ ][ ]
[ X][11][ Y][ 4][ Z]
Each brick of the pyramid is the sum of the two bricks situated below it.
Of the three missing numbers a... | 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... | #MAXScript | MAXScript | for i in 10 to 0 by -1 do print i | Give a code snippet in #MAXScript
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/In... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Integer_comparison | Integer comparison |
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 |... | #MUMPS | MUMPS | INTCOMP
NEW A,B
INTCOMPREAD
READ !,"Enter an integer to test: ",A
READ !,"Enter another integer: ",B
IF (+A\1'=A)!(+B\1'=B) WRITE !!,"Please enter two integers.",! GOTO INTCOMPREAD
IF A<B WRITE !,A," is less than ",B
IF A=B WRITE !,A," is equal to ",B
IF A>B WRITE !,A," is greater than ",B
KILL A,B
QUIT | Give a code snippet in #MUMPS
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Jewels_and_stones | Jewels and stones | Jewels and stones
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.
Both strings can contain any number of upper or lower case letters. However, in the case ... | #J | J |
NB. jewels sums a raveled equality table
NB. use: x jewels y x are the stones, y are the jewels.
intersect =: -.^:2
jewels =: ([: +/ [: , =/~) ~.@:intersect&Alpha_j_
'aAAbbbb ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz' jewels&>&;: 'aA ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'... | Give a code snippet in #J
Jewels and stones
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.
Both strings can contain any number of upper or lower case let... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Distributed_programming | Distributed programming | Write two programs (or one program with two modes) which run on networked computers, and send some messages between them.
The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed just for the particular example ... | #D | D | import arsd.rpc;
struct S1 {
int number;
string name;
}
struct S2 {
string name;
int number;
}
interface ExampleNetworkFunctions {
string sayHello(string name);
int add(in int a, in int b) const pure nothrow;
S2 structTest(S1);
void die();
}
// The server must implement the inter... | Give a code snippet in #D
Write two programs (or one program with two modes) which run on networked computers, and send some messages between them.
The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed just ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/N%27th | N'th | Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to show here the output for at least t... | #Java | Java | public class Nth {
public static String ordinalAbbrev(int n){
String ans = "th"; //most of the time it should be "th"
if(n % 100 / 10 == 1) return ans; //teens are all "th"
switch(n % 10){
case 1: ans = "st"; break;
case 2: ans = "nd"; break;
case 3: ans = "rd"; break;
}
return ans;
}
public sta... | Give a code snippet in #Java
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to show ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Jensen%27s_Device | Jensen's Device | Jensen's Device
You are encouraged to solve this task according to the task description, using any language you may know.
This task is an exercise in call by name.
Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL 60 Report.
The following pr... | #zkl | zkl | fcn sum(ri, lo,hi, term){
temp:=0.0; ri.set(lo);
do{ temp+=term(ri); } while(ri.inc()<hi); // inc return previous value
return(temp);
}
sum(Ref(0), 1,100, fcn(ri){ 1.0/ri.value }).println(); | Give a code snippet in #zkl
Jensen's Device
You are encouraged to solve this task according to the task description, using any language you may know.
This task is an exercise in call by name.
Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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... | #Scilab | Scilab | answer = factorial(N) | Give a code snippet in #Scilab
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 ... | 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
| #LIL | LIL | #
# Hello world in lil
#
print "Hello, world!" | Give a code snippet in #LIL
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/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file... | #Modula-2 | Modula-2 | MODULE MorseCode;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE WriteMorseCode(str : ARRAY OF CHAR);
VAR i : CARDINAL;
BEGIN
WriteString(str);
WriteLn;
FOR i:=0 TO HIGH(str) DO
CASE CAP(str[i]) OF
'A': WriteString(".-");
| 'B': WriteString("-...");
... | Give a code snippet in #Modula-2
Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ign... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #C.2B.2B | C++ | #include <iostream>
int main() {
const int max_it = 13;
const int max_it_j = 10;
double a1 = 1.0, a2 = 0.0, d1 = 3.2;
std::cout << " i d\n";
for (int i = 2; i <= max_it; ++i) {
double a = a1 + (a1 - a2) / d1;
for (int j = 1; j <= max_it_j; ++j) {
double x = 0.0;... | Give a code snippet in #C.2B.2B
Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| 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
| #FreeBASIC | FreeBASIC | ? "Hello world!"
sleep | Give a code snippet in #FreeBASIC
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 err... | christopher/rosetta-code | |
http://rosettacode.org/wiki/SEDOLs | SEDOLs | Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
... | #Cach.C3.A9_ObjectScript | Caché ObjectScript | Class Utils.Check [ Abstract ]
{
ClassMethod SEDOL(x As %String) As %Boolean
{
// https://en.wikipedia.org/wiki/SEDOL
IF x'?1(7N,1U5UN1N) QUIT 0
IF x'=$TRANSLATE(x,"AEIOU") QUIT 0
SET cd=$EXTRACT(x,*), x=$EXTRACT(x,1,*-1)
SET wgt="1317391", t=0
FOR i=1:1:$LENGTH(x) {
SET n=$EXTRACT(x,i)
IF n'=+n SET n=$ASCI... | Give a code snippet in #Cach.C3.A9_ObjectScript
Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
55791... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates su... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | sqrt2=Function[n,{1,Transpose@{Array[2&,n],Array[1&,n]}}];
napier=Function[n,{2,Transpose@{Range[n],Prepend[Range[n-1],1]}}];
pi=Function[n,{3,Transpose@{Array[6&,n],Array[(2#-1)^2&,n]}}];
approx=Function[l,
N[Divide@@First@Fold[{{#2.#[[;;,1]],#2.#[[;;,2]]},#[[1]]}&,{{l[[2,1,1]]l[[1]]+l[[2,1,2]],l[[2,1,1]]},{l[[1]],1}... | Give a code snippet in #Mathematica_.2F_Wolfram_Language
continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }... | 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 .
| #TXR | TXR | (defvar x-centre -0.5)
(defvar y-centre 0.0)
(defvar width 4.0)
(defvar i-max 800)
(defvar j-max 600)
(defvar n 100)
(defvar r-max 2.0)
(defvar file "mandelbrot.pgm")
(defvar colour-max 255)
(defvar pixel-size (/ width i-max))
(defvar x-offset (- x-centre (* 0.5 pixel-size (+ i-max 1))))
(defvar y-offset (+ y-centre (*... | Give a code snippet in #TXR
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/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrat... | #PowerShell | PowerShell |
function Get-Time
{
<#
.SYNOPSIS
Gets a time string in the form: # wk, # d, # hr, # min, # sec
.DESCRIPTION
Gets a time string in the form: # wk, # d, # hr, # min, # sec
(Values of 0 are not displayed in the string.)
Days, Hours, Minutes or Seconds in any combination may be... | Give a code snippet in #PowerShell
Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ... | #SequenceL | SequenceL | fibonacci(n) :=
n when n < 2
else
fibonacci(n - 1) + fibonacci(n - 2); | Give a code snippet in #SequenceL
The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions... | christopher/rosetta-code | |
http://rosettacode.org/wiki/99_bottles_of_beer | 99 bottles of beer | Task
Display the complete lyrics for the song: 99 Bottles of Beer on the Wall.
The beer song
The lyrics follow this form:
99 bottles of beer on the wall
99 bottles of beer
Take one down, pass it around
98 bottles of beer on the wall
98 bottles of beer on the wall
98 bottles of beer
Take one dow... | #Crystal | Crystal | 99.downto(1) do |n|
puts "#{n} bottle#{n > 1 ? "s" : ""} of beer on the wall"
puts "#{n} bottle#{n > 1 ? "s" : ""} of beer"
puts "Take one down, pass it around" ... | Give a code snippet in #Crystal
Task
Display the complete lyrics for the song: 99 Bottles of Beer on the Wall.
The beer song
The lyrics follow this form:
99 bottles of beer on the wall
99 bottles of beer
Take one down, pass it around
98 bottles of beer on the wall
98 bottles of beer on the wall
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #JavaScript | JavaScript | var fso = new ActiveXObject("Scripting.FileSystemObject");
fso.GetFile('input.txt').Size;
fso.GetFile('c:/input.txt').Size; | Give a code snippet in #JavaScript
Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #zkl | zkl | fcn generate_voronoi_diagram(width,height,num_cells){
image,imgx,imgy:=PPM(width,height),width,height;
nx:=num_cells.pump(List,(0).random.fp(imgx));
ny:=num_cells.pump(List,(0).random.fp(imgy));
nr:=num_cells.pump(List,(0).random.fp(256)); // red
ng:=num_cells.pump(List,(0).random.fp(256)); // blue
... | Give a code snippet in #zkl
A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Rate_counter | Rate counter | Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.
Multiple approaches are allowed (even preferable), so long as they can accomplish these goals:
Run N seconds worth... | #Sidef | Sidef | var benchmark = frequire('Benchmark');
func job1 {
#...job1 code...
}
func job2 {
#...job2 code...
}
const COUNT = -1; # run for one CPU second
benchmark.timethese(COUNT, Hash.new('Job1' => job1, 'Job2' => job2)); | Give a code snippet in #Sidef
Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.
Multiple approaches are allowed (even preferable), so long as they can accomplish the... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Word_ladder | Word ladder | Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second.
Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used.
Demonstrate the following:
A boy can be made into ... | #Java | Java | import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.stream.IntStream;
public class WordLadd... | Give a code snippet in #Java
Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second.
Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used.
Demonstrate the follo... | 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... | #Nim | Nim | import strformat
func fusc(n: int): int =
if n == 0 or n == 1:
n
elif n mod 2 == 0:
fusc(n div 2)
else:
fusc((n - 1) div 2) + fusc((n + 1) div 2)
echo "The first 61 Fusc numbers:"
for i in 0..61:
write(stdout, fmt"{fusc(i)} ")
echo "\n\nThe Fusc numbers whose lengths are greater than those of pr... | Give a code snippet in #Nim
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 star... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #PicoLisp | PicoLisp | (de rot13-Ch (C)
(if
(or
(member C '`(apply circ (chop "ABCDEFGHIJKLMNOPQRSTUVWXYZ")))
(member C '`(apply circ (chop "abcdefghijklmnopqrstuvwxyz"))) )
(get @ 14)
C ) ) | Give a code snippet in #PicoLisp
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot... | 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... | #Niue | Niue | [ dup 1 > [ dup 1 - factorial * ] when ] 'factorial ;
( test )
4 factorial . ( => 24 )
10 factorial . ( => 3628800 ) | Give a code snippet in #Niue
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 nu... | christopher/rosetta-code | |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
... | #VBScript | VBScript | For i = 1 To 100
If i Mod 15 = 0 Then
WScript.Echo "FizzBuzz"
ElseIf i Mod 5 = 0 Then
WScript.Echo "Buzz"
ElseIf i Mod 3 = 0 Then
WScript.Echo "Fizz"
Else
WScript.Echo i
End If
Next | Give a code snippet in #VBScript
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzB... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Strip_block_comments | Strip block comments | A block comment begins with a beginning delimiter and ends with a ending delimiter, including the delimiters. These delimiters are often multi-character sequences.
Task
Strip block comments from program text (of a programming language much like classic C).
Your demos should at least handle simple, non-ne... | #VBA | VBA | 'strip block comment NESTED comments
'multi line comments
'and what if there are string literals with these delimeters?
'------------------------
'delimeters for Block Comment can be specified, exactly two characters each
'Three states: Block_Comment, String_Literal, Other_Text
'Globals:
Dim t As String 'target string
... | Give a code snippet in #VBA
A block comment begins with a beginning delimiter and ends with a ending delimiter, including the delimiters. These delimiters are often multi-character sequences.
Task
Strip block comments from program text (of a programming language much like classic C).
Your demos should a... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usua... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Characters.Latin_1;
procedure Bell is
begin
Put(Ada.Characters.Latin_1.BEL);
end Bell; | Give a code snippet in #Ada
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell with... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typica... | #Modula-2 | Modula-2 | MODULE complex;
IMPORT InOut;
TYPE Complex = RECORD R, Im : REAL END;
VAR z : ARRAY [0..3] OF Complex;
PROCEDURE ShowComplex (str : ARRAY OF CHAR; p : Complex);
BEGIN
InOut.WriteString (str); InOut.WriteString (" = ");
InOut.WriteReal (p.R, 6, 2);
IF... | Give a code snippet in #Modula-2
A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displa... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Function_definition | Function definition | A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are ... | #Raku | Raku | sub multiply { return @_[0] * @_[1]; } | Give a code snippet in #Raku
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract f... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hello_world/Standard_error | Hello world/Standard error | Hello world/Standard error is part of Short Circuit's Console Program Basics selection.
A common practice in computing is to send error messages
to a different output stream than normal text console messages.
The normal messages print to what is called "standard output" or "standard out".
The error messages print to ... | #Tcl | Tcl | puts stderr "Goodbye, World!" | Give a code snippet in #Tcl
Hello world/Standard error is part of Short Circuit's Console Program Basics selection.
A common practice in computing is to send error messages
to a different output stream than normal text console messages.
The normal messages print to what is called "standard output" or "standard out".
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usua... | #Objeck | Objeck | 7->As(Char)->PrintLine(); | Give a code snippet in #Objeck
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell w... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Universal_Turing_machine | Universal Turing machine | One of the foundational mathematical constructs behind computer science
is the universal Turing Machine.
(Alan Turing introduced the idea of such a machine in 1936–1937.)
Indeed one way to definitively prove that a language
is turing-complete
is to implement a universal Turing machine in it.
Task
Simulate such ... | #Lambdatalk | Lambdatalk |
{require lib_H} // associative arrays library
{def tm
{def tm.r
{lambda {:data :rules :state :end :blank :i :N}
{if {or {W.equal? :state :end} {> :N 400}} // recursion limited to 400
then :data
else {let { {:data :data} {:rules :rules}
{:state {H.get :state :rules... | Give a code snippet in #Lambdatalk
One of the foundational mathematical constructs behind computer science
is the universal Turing Machine.
(Alan Turing introduced the idea of such a machine in 1936–1937.)
Indeed one way to definitively prove that a language
is turing-complete
is to implement a universal Turing ma... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #XPL0 | XPL0 | proc Mat4x1Mul(M, V); \Multiply matrix M times column vector V
real M, \4x4 matrix [M] * [V] -> [V]
V; \column vector
real W(4); \working copy of column vector
int R; \row
[for R:= 0 to 4-1 do
W(R):= M(R,0)*V(0) + M(R,1)*V(1) + M(R,2)*V(2) + M(R,3)*V(3);
for R:= 0 to 4-1 do V(R):= W(R);
];
p... | Give a code snippet in #XPL0
Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/XML/Input | XML/Input | Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath.
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /... | #Common_Lisp | Common Lisp | (defparameter *xml-blob*
"<Students>
<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />
<Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />
<Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />
<Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">
<Pet T... | Give a code snippet in #Common_Lisp
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath.
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" G... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Averages/Mean_angle | Averages/Mean angle | When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle.
If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the ... | #Ruby | Ruby | require 'complex' # Superfluous in Ruby >= 2.0; complex is added to core.
def deg2rad(d)
d * Math::PI / 180
end
def rad2deg(r)
r * 180 / Math::PI
end
def mean_angle(deg)
rad2deg((deg.inject(0) {|z, d| z + Complex.polar(1, deg2rad(d))} / deg.length).arg)
end
[[350, 10], [90, 180, 270, 360], [10, 20, 30]].e... | Give a code snippet in #Ruby
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle.
If one wanted an average direction of the wind over two readings where the first readi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hash_from_two_arrays | Hash from two arrays | Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
| #Nim | Nim | import tables, sequtils
let keys = @['a','b','c']
let values = @[1, 2, 3]
let table = toTable zip(keys, values) | Give a code snippet in #Nim
Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Generic_swap | Generic swap | Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in t... | #Visual_FoxPro | Visual FoxPro | Since Visual FoxPro is not strongly typed, this will work with any data types.
| Give a code snippet in #Visual_FoxPro
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides g... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Active_Directory/Connect | Active Directory/Connect | The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
| #Haskell | Haskell | {-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import Data.Foldable (for_)
import qualified Data.Text.Encoding as Text (encodeUtf8)
import Ldap.Client (Attr(..), Filter(..))
import qualified Ldap.Client as Ldap (Dn(..), Host(..), search, with, typesOnly)
main :: IO ()
main = do
... | Give a code snippet in #Haskell
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet | Generate lower case ASCII alphabet | Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a sty... | #zkl | zkl | ["a".."z"] // lasy list
["a".."z"].walk() //-->L("a","b","c","d","e",...
"a".toAsc().pump(26,List,"toChar") // another way to create the list
"a".toAsc().pump(26,String,"toChar") // create a string
//-->"abcdefghijklmnopqrstuvwxyz"
Utils.Helpers.lowerLetters // string const | Give a code snippet in #zkl
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a re... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #Pike | Pike | write("%s\n", getenv("SHELL")); | Give a code snippet in #Pike
Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| christopher/rosetta-code | |
http://rosettacode.org/wiki/String_interpolation_(included) | String interpolation (included) |
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 |... | #Neko | Neko | /**
<doc><h2>String interpolation, in Neko</h2>
<p><a href="https://nekovm.org/doc/view/string/">NekoVM String Library</a></p>
</doc>
**/
var sprintf = $loader.loadprim("std@sprintf", 2)
$print(sprintf("Mary had a %s lamb\n", "little")) | Give a code snippet in #Neko
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/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... | #Delphi | Delphi | : \ ? = ~ / ! # $ % & * + - < > @ ^ ` | , ' ; | Give a code snippet in #Delphi
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/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.
| #Tcl | Tcl | package require tcltest 2
source palindrome.tcl; # Assume that this is what loads the implementation of ‘palindrome’
tcltest::test palindrome-1 {check for palindromicity} -body {
palindrome abcdedcba
} -result 1
tcltest::test palindrome-2 {check for non-palindromicity} -body {
palindrome abcdef
} -result 0
tc... | Give a code snippet in #Tcl
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/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available,... | #Nanoquery | Nanoquery | // create a fixed-length array (length 10)
arr = array(10)
// assign a value to the first position in the array and then display it
arr[0] = "hello, world!"
println arr[0]
// create a variable-length list
l = list()
// place the numbers 1-10 in the list
for i in range(1,10)
append l i
end
// display the list... | Give a code snippet in #Nanoquery
This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and r... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Box_the_compass | Box the compass | There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
Task description
Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
Use the function to print and display a table of Index, Compass... | #PicoLisp | PicoLisp | (scl 3)
(setq *Compass # Build lookup table
(let H -16.875
(mapcar
'((Str)
(cons
(inc 'H 11.25) # Heading in degrees
(pack # Compass point
(replace (chop Str)
"N" "north"
... | Give a code snippet in #PicoLisp
There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
Task description
Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
Use the function to print and... | 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 ... | #JavaScript | JavaScript |
/* Tile object: */
function Tile(pos, val, puzzle){
this.pos = pos;
this.val = val;
this.puzzle = puzzle;
this.merging = false;
this.getCol = () => Math.round(this.pos % 4);
this.getRow = () => Math.floor(this.pos / 4);
/* draw tile on a P5.js canvas: */
this.show = function(){
let padding ... | Give a code snippet in #JavaScript
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, ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Integer_comparison | Integer comparison |
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 |... | #CFEngine | CFEngine |
bundle agent __main__
{
vars:
# Change the values to test:
"first_integer" int => "10";
"second_integer" int => "9";
reports:
"The first integer ($(first_integer)) is less than the second integer ($(second_integer))."
if => islessthan( "$(first_integer)", "$(second_integer)" );
... | Give a code snippet in #CFEngine
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/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 ... | #Ol | Ol | ((lambda (s) (display (list s (list (quote quote) s)))) (quote (lambda (s) (display (list s (list (quote quote) s)))))) | Give a code snippet in #Ol
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
se... | 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... | #PL.2FI | PL/I | arithmetic_mean = sum(A)/dimension(A,1); | Give a code snippet in #PL.2FI
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 est... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Word_search | Word search | A word search puzzle typically consists of a grid of letters in which words are hidden.
There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards.
The words may ... | #Racket | Racket | #lang racket
;; ---------------------------------------------------------------------------------------------------
(module+ main
(display-puzzle (create-word-search))
(newline)
(parameterize ((current-min-words 50))
(display-puzzle (create-word-search #:n-rows 20 #:n-cols 20))))
;; ------------------------... | Give a code snippet in #Racket
A word search puzzle typically consists of a grid of letters in which words are hidden.
There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be sp... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
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
She... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
begin
writeln([] (1) < [] (1, 2)); # If the first list runs out of elements the result is TRUE.
writeln([] (1, 2) < [] (1)); # If the second list runs out of elements the result is FALSE.
writeln([] (1, 2) < [] (1, 2)); # If both... | Give a code snippet in #Seed7
sorting
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 |
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/String_matching | String matching |
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 |... | #Lua | Lua | s1 = "string"
s2 = "str"
s3 = "ing"
s4 = "xyz"
print( "s1 starts with s2: ", string.find( s1, s2 ) == 1 )
print( "s1 starts with s3: ", string.find( s1, s3 ) == 1, "\n" )
print( "s1 contains s3: ", string.find( s1, s3 ) ~= nil )
print( "s1 contains s3: ", string.find( s1, s4 ) ~= nil, "\n" )
print( "s1 ends wi... | Give a code snippet in #Lua
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
Co... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem | Kernighans large earthquake problem | Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based.
Problem
You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event.
Example lines from the file would be lines li... | #Snobol | Snobol | input(.quake, 1,, 'data.txt') :f(err)
num = '.0123456789'
line test = quake :f(end)
test span(num) . magnitude rpos(0) :f(line)
output = gt(magnitude,6) test :(line)
err output = 'Error!'
end | Give a code snippet in #Snobol
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based.
Problem
You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event.
Example lines... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ... | #Objective-C | Objective-C | #import <stdio.h>
BOOL iseven(int x)
{
return (x&1) == 0;
}
@interface EthiopicMult : NSObject
+ (int)mult: (int)plier by: (int)plicand;
+ (int)halve: (int)a;
+ (int)double: (int)a;
@end
@implementation EthiopicMult
+ (int)mult: (int)plier by: (int)plicand
{
int r = 0;
while(plier >= 1) {
if ( !iseven(p... | Give a code snippet in #Objective-C
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders,... | 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.
| #PureBasic | PureBasic | Dim MyArray(9)
Define a, sum=0, prod=1
For a = 0 To ArraySize(MyArray()) ; Create a list of some random numbers
MyArray(a) = 1 + Random(9) ; Insert a number [1...10] in current element
Next
For a = 0 To ArraySize(MyArray()) ; Calculate Sum and Product of this Array
sum + MyArray(a)
prod * My... | Give a code snippet in #PureBasic
Task
Compute the sum and product of an array of integers.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Deming%27s_Funnel | Deming's Funnel | W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to ... | #Kotlin | Kotlin | // version 1.1.3
typealias Rule = (Double, Double) -> Double
val dxs = doubleArrayOf(
-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0.709, 0.129, -1.093... | Give a code snippet in #Kotlin
W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. 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
Write a function to compute the arithmetic-geomet... | #C.23 | C# | namespace RosettaCode.ArithmeticGeometricMean
{
using System;
using System.Collections.Generic;
using System.Globalization;
internal static class Program
{
private static double ArithmeticGeometricMean(double number,
double otherNumber,... | Give a code snippet in #C.23
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. 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
Write a function to... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort | Sorting algorithms/Pancake 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
... | #Phix | Phix | with javascript_semantics
function pancake_sort(sequence s)
s = deep_copy(s)
for i=length(s) to 2 by -1 do
integer m = largest(s[1..i],true)
if m<i then
if m>1 then
s[1..m] = reverse(s[1..m])
end if
s[1..i] = reverse(s[1..i])
end if
... | Give a code snippet in #Phix
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/Death_Star | Death Star |
Task
Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction.
(This will basically produce a shape like a "death star".)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | RegionPlot3D[x^2 + y^2 + z^2 < 1 && (x + 1.7)^2 + y^2 + z^2 > 1,
{x, -1, 1}, {y, -1, 1}, {z, -1, 1},
Boxed -> False, Mesh -> False, Axes -> False, Background -> Black, PlotPoints -> 100] | Give a code snippet in #Mathematica_.2F_Wolfram_Language
Task
Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction.
(This will basically produce a shape like a "death star".)
Related tasks
draw a sphere
draw a cuboid
draw a rotat... | 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... | #uBasic.2F4tH | uBasic/4tH | PRINT "Comb sort:"
n = FUNC (_InitArray)
PROC _ShowArray (n)
PROC _Combsort (n)
PROC _ShowArray (n)
PRINT
END
_Combsort PARAM (1) ' Combsort subroutine
LOCAL(4)
b@ = a@
c@ = 1
DO WHILE (b@ > 1) + c@
b@ = (b@ * 10) / 13
IF (b@ = 9) + (b@ = 10) THEN b@ = 11
IF b@... | Give a code snippet in #uBasic.2F4tH
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 co... | 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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Fan | Fan | **
** Generates a square Sierpinski gasket
**
class SierpinskiCarpet
{
public static Bool inCarpet(Int x, Int y){
while(x!=0 && y!=0){
if (x % 3 == 1 && y % 3 == 1)
return false;
x /= 3;
y /= 3;
}
return true;
}
static Int pow(Int n, Int exp)
{
rslt := 1
exp.times... | Give a code snippet in #Fan
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/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Creat... | #Liberty_BASIC | Liberty BASIC | txt$ = "Hello World! "
txtLength = len(txt$)
direction=1
NoMainWin
open "Rosetta Task: Animation" for graphics_nsb as #demo
#demo "Trapclose [quit]"
#demo "down"
#demo "Font Verdana 20 Bold"
#demo "When leftButtonUp [changedirection]"
timer 150 , [draw]
wait
[draw]
... | Give a code snippet in #Liberty_BASIC
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/For_with_a_specified_step | Loops/For with a specified step |
Task
Demonstrate a for-loop where the step-value is greater than one.
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 b... | #Maxima | Maxima | for i: 1 step 2 thru 10 do print(i);
/* 1
3
5
7 */ | Give a code snippet in #Maxima
Task
Demonstrate a for-loop where the step-value is greater than one.
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/In... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/For_with_a_specified_step | Loops/For with a specified step |
Task
Demonstrate a for-loop where the step-value is greater than one.
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 b... | #Python | Python | for i in xrange(2, 9, 2):
print "%d," % i,
print "who do we appreciate?" | Give a code snippet in #Python
Task
Demonstrate a for-loop where the step-value is greater than one.
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/In... | 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)
| #zkl | zkl | const RANDOM_PATH="/dev/urandom";
fin,buf:=File(RANDOM_PATH,"r"), fin.read(4);
fin.close(); // GC would also close the file
println(buf.toBigEndian(0,4)); // 4 bytes @ offset 0 | Give a code snippet in #zkl
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/Loops/Nested | Loops/Nested | Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over
[
1
,
…
,
20
]
{\displaystyle [1,\ldots ,20]}
.
The loops iterate rows and columns of the array printing the elements until the value
20
{\displaystyle 20}
is met.
Specifically, this task als... | #Oz | Oz | declare
fun {CreateMatrix Width Height}
Matrix = {List.make Height}
in
for Row in Matrix do
Row = {List.make Width}
for X in Row do
X = {OS.rand} mod 20 +1
end
end
Matrix
end
proc {PrintMatrix Matrix}
%% print until we see 20
for Row in Matrix break:Oute... | Give a code snippet in #Oz
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over
[
1
,
…
,
20
]
{\displaystyle [1,\ldots ,20]}
.
The loops iterate rows and columns of the array printing the elements until the value
20
{\displaystyle 20}
is met.
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pythagoras_tree | Pythagoras tree |
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem.
Task
Construct a Pythagoras tree of order 7 using only vectors (no rotation or ... | #Racket | Racket | #lang racket
(require racket/draw pict)
(define (draw-pythagoras-tree order x0 y0 x1 y1)
(λ (the-dc dx dy)
(define (inr order x0 y0 x1 y1)
(when (positive? order)
(let* ((y0-1 (- y0 y1))
(x1-0 (- x1 x0))
(x2 (+ x1 y0-1))
(y2 (+ y1 x1-0))
... | Give a code snippet in #Racket
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem.
Task
Construct a Pythagoras tree of order 7 usi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/HTTP | HTTP | Task
Access and print a URL's content (the located resource) to the console.
There is a separate task for HTTPS Requests.
| #D | D |
void main() {
import std.stdio, std.net.curl;
writeln(get("http://google.com"));
}
| Give a code snippet in #D
Task
Access and print a URL's content (the located resource) to the console.
There is a separate task for HTTPS Requests.
| 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 ... | #Go | Go | package main
import (
"fmt"
"strings"
)
func ms(txt string, sep []string) (ans []string) {
for txt > "" {
sepMatch := ""
posMatch := len(txt)
for _, s := range sep {
if p := strings.Index(txt, s); p >= 0 && p < posMatch {
sepMatch = s
p... | Give a code snippet in #Go
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 t... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Floyd-Warshall_algorithm | Floyd-Warshall algorithm | The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights.
Task
Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel ... | #OCaml | OCaml | (*
Floyd-Warshall algorithm.
See https://en.wikipedia.org/w/index.php?title=Floyd%E2%80%93Warshall_algorithm&oldid=1082310013
*)
module Square_array =
(* Square arrays with 1-based indexing. *)
struct
type 'a t =
{
n : int;
r : 'a Array.t
}
let make n fill =
... | Give a code snippet in #OCaml
The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights.
Task
Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already be... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sum_of_elements_below_main_diagonal_of_matrix | Sum of elements below main diagonal of matrix | Task
Find and display the sum of elements that are below the main diagonal of a matrix.
The matrix should be a square matrix.
─── Matrix to be used: ───
[[1,3,7,8,10],
[2,4,16,14,4],
[3,1,9,18,11],
[12,14,17,18,20],
[7,1,3,9,5]]
| #PL.2FM | PL/M | 100H: /* SUM THE ELEMENTS BELOW THE MAIN DIAGONAL OF A MATRIX */
/* CP/M BDOS SYSTEM CALL, IGNORE THE RETURN VALUE */
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
... | Give a code snippet in #PL.2FM
Task
Find and display the sum of elements that are below the main diagonal of a matrix.
The matrix should be a square matrix.
─── Matrix to be used: ───
[[1,3,7,8,10],
[2,4,16,14,4],
[3,1,9,18,11],
[12,14,17,18,20],
[7,1,3,9,5]]
| christopher/rosetta-code | |
http://rosettacode.org/wiki/P-value_correction | P-value correction | Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate.
This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1].
The adjusted p-values are sometimes called "q... | #Java | Java | import java.util.Arrays;
import java.util.Comparator;
public class PValueCorrection {
private static int[] seqLen(int start, int end) {
int[] result;
if (start == end) {
result = new int[end + 1];
for (int i = 0; i < result.length; ++i) {
result[i] = i + 1;
... | Give a code snippet in #Java
Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate.
This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1].
The adjusted p-... | 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, ... | #jq | jq | def count(stream; cond):
reduce stream as $i (0; if $i|cond then .+1 else . end);
def Months: [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
# tostring
def birthday: "\(Months[.month-1]) \(.day)";
# Input: a Birthday
def mont... | Give a code snippet in #jq
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 Alb... | christopher/rosetta-code | |
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12 | First power of 2 that has leading decimal digits of 12 | (This task is taken from a Project Euler problem.)
(All numbers herein are expressed in base ten.)
27 = 128 and 7 is
the first power of 2 whose leading decimal digits are 12.
The next power of 2 whose leading decimal digits
are 12 is 80,
280 = 1208925819614629174706176.
Define ... | #Perl | Perl | use strict;
use warnings;
use feature 'say';
use feature 'state';
use POSIX qw(fmod);
use Perl6::GatherTake;
use constant ln2ln10 => log(2) / log(10);
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
sub ordinal_digit {
my($d) = $_[0] =~ /(.)$/;
$d eq '1' ? 'st' : $d eq '2' ? 'nd' :... | Give a code snippet in #Perl
(This task is taken from a Project Euler problem.)
(All numbers herein are expressed in base ten.)
27 = 128 and 7 is
the first power of 2 whose leading decimal digits are 12.
The next power of 2 whose leading decimal digits
are 12 is 80,
280 = 1208925... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Playfair_cipher | Playfair cipher | Playfair cipher
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Implement a Playfair cipher for encryption and decryption.
The user must be able to choose J = I or no Q in the alphabet.
The output of the encrypted and decrypted message ... | #Wren | Wren | import "/dynamic" for Enum
import "/str" for Str, Char
import "/trait" for Stepped
import "/ioutil" for Input
var PlayfairOption = Enum.create("PlayfairOption", ["NO_Q", "I_EQUALS_J"])
class Playfair {
construct new(keyword, pfo) {
_pfo = pfo
// build_table
_table = List.filled(5, null)
... | Give a code snippet in #Wren
Playfair cipher
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Implement a Playfair cipher for encryption and decryption.
The user must be able to choose J = I or no Q in the alphabet.
The output of the en... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Self_numbers | Self numbers | A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or d... | #Wren | Wren | var sieve = Fn.new {
var sv = List.filled(2*1e9+9*9+1, false)
var n = 0
var s = [0] * 8
for (a in 0..1) {
for (b in 0..9) {
s[0] = a + b
for (c in 0..9) {
s[1] = s[0] + c
for (d in 0..9) {
s[2] = s[1] + d ... | Give a code snippet in #Wren
A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the... | #ANTLR | ANTLR |
grammar rpnC ;
//
// rpn Calculator
//
// Nigel Galloway - April 7th., 2012
//
@members {
Stack<Double> s = new Stack<Double>();
}
rpn : (WS* (num|op) (WS | WS* NEWLINE {System.out.println(s.pop());}))*;
num : '-'? Digit+ ('.' Digit+)? {s.push(Double.parseDouble($num.text));};
Digit : '0'..'9';
op : '-' {double x =... | Give a code snippet in #ANTLR
Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RP... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) sq... | #C.2B.2B | C++ | #include <iostream>
#define HEIGHT 4
#define WIDTH 4
struct Shape {
public:
char xCoord;
char yCoord;
char height;
char width;
char **figure;
};
struct Glider : public Shape {
static const char GLIDER_SIZE = 3;
Glider( char x , char y );
~Glider();
};
struct Blinker : public Shape ... | Give a code snippet in #C.2B.2B
The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead,... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5 | Sum multiples of 3 and 5 | Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| #C | C | #include <stdio.h>
#include <stdlib.h>
unsigned long long sum35(unsigned long long limit)
{
unsigned long long sum = 0;
for (unsigned long long i = 0; i < limit; i++)
if (!(i % 3) || !(i % 5))
sum += i;
return sum;
}
int main(int argc, char **argv)
{
unsigned long long limit;
... | Give a code snippet in #C
Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| 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... | #Golfscript | Golfscript | {.!{1}{,{)}%{*}*}if}:fact;
5fact puts # test | Give a code snippet in #Golfscript
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 o... | 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... | #Fortran | Fortran | program typedemo
type rational ! Type declaration
integer :: numerator
integer :: denominator
end type rational
type( rational ), parameter :: zero = rational( 0, 1 ) ! Variables initialized
type( rational ), parameter :: one = rational( 1, ... | Give a code snippet in #Fortran
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.
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Stem-and-leaf_plot | Stem-and-leaf plot | Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits:
12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 11... | #Ceylon | Ceylon | "Run the module `thestemandleafplot`."
shared void run() {
value data ="12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35
113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114
126 53 114 96 25... | Give a code snippet in #Ceylon
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits:
12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Barnsley_fern | Barnsley fern |
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
Task
Create this fractal fern, using the following transformations:
ƒ1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
ƒ2 (chosen 85% of the time)
... | #Processing | Processing | void setup() {
size(640, 640);
background(0, 0, 0);
}
float x = 0;
float y = 0;
void draw() {
for (int i = 0; i < 100000; i++) {
float xt = 0;
float yt = 0;
float r = random(100);
if (r <= 1) {
xt = 0;
yt = 0.16*y;
} else if (r <= 8) {
xt = 0.20*x - 0.26*y;
yt... | Give a code snippet in #Processing
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
Task
Create this fractal fern, using the following transformations:
ƒ1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #Lua | Lua | for n in pairs(_G) do print(n) end | Give a code snippet in #Lua
Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Trav... | #ALGOL_W | ALGOL W | % inserts a new value after the specified element of a list %
procedure insert( reference(ListI) value list
; integer value newValue
) ;
next(list) := ListI( newValue, next(list) );
% declare a variable to hold a list ... | Give a code snippet in #ALGOL_W
Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definit... | 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 ... | #8th | 8th |
quote *
Hi
there
* .
| Give a code snippet in #8th
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/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
... | #F.23 | F# |
let rec qsort = function
hd :: tl ->
let less, greater = List.partition ((>=) hd) tl
List.concat [qsort less; [hd]; qsort greater]
| _ -> []
| Give a code snippet in #F.23
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/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Trav... | #ALGOL_68 | ALGOL 68 | MODE STRINGLIST = STRUCT(STRING value, REF STRINGLIST next);
STRINGLIST list := ("Big",
LOC STRINGLIST := ("fjords",
LOC STRINGLIST := ("vex",
LOC STRINGLIST := ("quick",
LOC STRINGLIST := ("waltz",
LOC STRINGLIST := ("nymph",NIL))))));
PROC insert = (REF STRINGLIST list, node)VOID: (
... | Give a code snippet in #ALGOL_68
Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element defini... | 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.
| #Rust | Rust | fn main() {
let a_vec = vec![1, 2, 3, 4, 5];
let b_vec = vec![6; 5];
let c_vec = concatenate_arrays(&a_vec, &b_vec);
println!("{:?} ~ {:?} => {:?}", a_vec, b_vec, c_vec);
}
fn concatenate_arrays<T: Clone>(x: &[T], y: &[T]) -> Vec<T> {
let mut concat = x.to_vec();
concat.extend_from_slice(y... | Give a code snippet in #Rust
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/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #Neko | Neko | /*
ROT-13 in Neko
*/
/* Assume ASCII encoding */
var rotate13 = function(c) {
if (c >= 65 && c <= 77) || (c >= 97 && c <= 109)
c += 13
else
if (c >= 78 && c <= 90) || (c >= 110 && c <= 122)
c -= 13
return c
}
var rot13 = function(s) {
var r = $scopy(s)
var len = $ssi... | Give a code snippet in #Neko
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 ... | 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.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program inputLoop.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/************************************... | Give a code snippet in #ARM_Assembly
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 | |
http://rosettacode.org/wiki/Abbreviations,_easy | Abbreviations, easy | This task is an easier (to code) variant of the Rosetta Code task: Abbreviations, simple.
For this task, the following command table will be used:
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
... | #AutoHotkey | AutoHotkey | ; Setting up command table as one string
str =
(
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
Join SPlit SPLTJOIN LOAD Locate... | Give a code snippet in #AutoHotkey
This task is an easier (to code) variant of the Rosetta Code task: Abbreviations, simple.
For this task, the following command table will be used:
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down ... | christopher/rosetta-code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.