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/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that i... | #Racket | Racket | #lang racket
(define radians (/ pi 4))
(define degrees 45)
(displayln (format "~a ~a" (sin radians) (sin (* degrees (/ pi 180)))))
(displayln (format "~a ~a" (cos radians) (cos (* degrees (/ pi 180)))))
(displayln (format "~a ~a" (tan radians) (tan (* degrees (/ pi 180)))))
(define arcsin (asin (sin radians)))
... | Give a code snippet in #Racket
Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that eval... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Mad_Libs | Mad Libs |
This page uses content from Wikipedia. The original article was at Mad Libs. 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)
Mad Libs is a phrasal template word game where one player prompts another... | #Raku | Raku | print S:g[ '<' (.*?) '>' ] = %.{$0} //= prompt "$0? " given slurp; | Give a code snippet in #Raku
This page uses content from Wikipedia. The original article was at Mad Libs. 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)
Mad Libs is a phrasal template word game wh... | christopher/rosetta-code | |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "osfiles.s7i";
include "time.s7i";
const proc: main is func
local
var time: modificationTime is time.value;
begin
modificationTime := getMTime("data.txt");
setMTime("data.txt", modificationTime);
end func; | Give a code snippet in #Seed7
Task
Get and set the modification time of a file.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Include_a_file | Include a file | Task
Demonstrate the language's ability to include source code from other files.
See Also
Compiler/Simple file inclusion pre processor
| #SNOBOL4 | SNOBOL4 | -INCLUDE "path/to/filename.inc" | Give a code snippet in #SNOBOL4
Task
Demonstrate the language's ability to include source code from other files.
See Also
Compiler/Simple file inclusion pre processor
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches ... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
const type: floatList is array float;
const func float: median (in floatList: floats) is func
result
var float: median is 0.0;
local
var floatList: sortedFloats is 0 times 0.0;
begin
sortedFloats := sort(floats);
if odd(length(sortedFloats)) the... | Give a code snippet in #Seed7
Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Archimedean_spiral | Archimedean spiral |
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.
An Archimedean spiral can be described by the equation:
r
=
a
+
b
θ
{\displaystyle \,r=a+b\theta }
with real numbers a and b.
Task
Draw an Archimedean spiral.
| #Lua | Lua |
a=1
b=2
cycles=40
step=0.001
x=0
y=0
function love.load()
x = love.graphics.getWidth()/2
y = love.graphics.getHeight()/2
end
function love.draw()
love.graphics.print("a="..a,16,16)
love.graphics.print("b="..b,16,32)
for i=0,cycles*math.pi,step do
love.graphics.points(x+(a + b*... | Give a code snippet in #Lua
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.
An Archimedean spiral can be described by the equation:
r
=
a
+
b
θ
{\displaystyle \,r=a+b\theta }
with real numbers a and b.
Task
Draw an Archimedean spiral.
| 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... | #AutoHotkey | AutoHotkey | MyFunc( "Val=0, w=1024, Text=The Quick Brown Fox, newVar=I'm New" )
MyFunc( _overrides="" ) {
Static x=5, y=5, w=100, h=100, Count
Name:="AutoHotkey", Type:="Scripting", Text:="qwerty", Val:=True
Loop, Parse, _overrides,`,=, %A_Space% ; Override routine for Local/Static variables
A_Index & 1 ? (_:=A_LoopFie... | Give a code snippet in #AutoHotkey
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/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
| #Liberty_BASIC | Liberty BASIC | print "Hello world!" | Give a code snippet in #Liberty_BASIC
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Peaceful_chess_queen_armies | Peaceful chess queen armies | In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour.
⇖
⇑
⇗
⇐
⇐
♛
⇒
⇒
⇙
⇓
⇘
⇙
⇓
⇘
⇓
The goal of Peaceful chess queen armies is to arrange m black queens and m white queens ... | #D | D | import std.array;
import std.math;
import std.stdio;
import std.typecons;
enum Piece {
empty,
black,
white,
}
alias position = Tuple!(int, "i", int, "j");
bool place(int m, int n, ref position[] pBlackQueens, ref position[] pWhiteQueens) {
if (m == 0) {
return true;
}
bool placingB... | Give a code snippet in #D
In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour.
⇖
⇑
⇗
⇐
⇐
♛
⇒
⇒
⇙
⇓
⇘
⇙
⇓
⇘
⇓
The goal of Peaceful chess queen armies is to arrange m black... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other... | #VBScript | VBScript |
Function IsDirEmpty(path)
IsDirEmpty = False
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(path)
If objFolder.Files.Count = 0 And objFolder.SubFolders.Count = 0 Then
IsDirEmpty = True
End If
End Function
'Test
WScript.StdOut.WriteLine IsDirEmpty("C:\Temp")
WScript.S... | Give a code snippet in #VBScript
Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature | Numerical integration/Gauss-Legendre Quadrature |
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting function
W
(
x
)
{\displaystyle ... | #PL.2FI | PL/I | (subscriptrange, size, fofl):
Integration_Gauss: procedure options (main);
declare (n, k) fixed binary;
declare r(*,*) float (18) controlled;
declare (z, a, b, exact) float (18);
do n = 1 to 20;
a = -3; b = 3;
if allocation(r) > 0 then free r;
allocate r(2, n); r = 0;
call gaussquad(n, r);
... | Give a code snippet in #PL.2FI
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting functi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #PARI.2FGP | PARI/GP | system("ls") | Give a code snippet in #PARI.2FGP
Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Go_Fish | Go Fish | Write a program to let the user play Go Fish against a computer opponent. Use the following rules:
Each player is dealt nine cards to start with.
On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of a given rank to ask for more.
If t... | #Raku | Raku |
Red [
Title: "Go Fish"
Author: "gltewalt"
]
chand: [] ;-- c and p = computer and player
cguesses: []
phand: []
cbooks: 0
pbooks: 0
gf: {
***************
* GO FISH *
***************
}
pip: ["a" "2" "3" "4" "5" "6" "7" "8" "9" "10" "j" "q" "k"] ;-- suits are not relevant
pile: [] ;-- whe... | Give a code snippet in #Raku
Write a program to let the user play Go Fish against a computer opponent. Use the following rules:
Each player is dealt nine cards to start with.
On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of a giv... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Farey_sequence | Farey sequence | The Farey sequence Fn of order n is the sequence of completely reduced fractions between 0 and 1 which, when in lowest terms, have denominators less than or equal to n, arranged in order of increasing size.
The Farey sequence is sometimes incorrectly called a Farey series.
Each Farey se... | #Sidef | Sidef | func farey_count(n) { # A005728
1 + sum(1..n, {|k| euler_phi(k) })
}
func farey(n) {
var seq = [0]
var (a,b,c,d) = (0,1,1,n)
while (c <= n) {
var k = (n+b)//d
(a,b,c,d) = (c, d, k*c - a, k*d - b)
seq << a/b
}
return seq
}
say "Farey sequence for order 1 throug... | Give a code snippet in #Sidef
The Farey sequence Fn of order n is the sequence of completely reduced fractions between 0 and 1 which, when in lowest terms, have denominators less than or equal to n, arranged in order of increasing size.
The Farey sequence is sometimes incorrectly called a ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat... | #REXX | REXX | /*REXX program finds the mode (most occurring element) of a vector. */
/* ════════vector═══════════ ═══show vector═══ ═════show result═════ */
v= 1 8 6 0 1 9 4 6 1 9 9 9 ; say 'vector='v; say 'mode='mode(v); say
v= 1 2 3 4 5 6 7 8 9 11 10 ; say 've... | Give a code snippet in #REXX
Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if pos... | 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... | #PARI.2FGP | PARI/GP | sleep(ms)={
while((ms-=gettime()) > 0,);
};
dot()=print1(Strchr([7]));sleep(250);
dash()=print1(Strchr([7]));sleep(10);print1(Strchr([7]));sleep(10);print1(Strchr([7]));sleep(250);
Morse(s)={
s=Vec(s);
for(i=1,#s,
if(s[i] == ".", dot(),
if(s[i] == "-", dash(), sleep(250))
)
)
};
Morse("...---...... | Give a code snippet in #PARI.2FGP
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 ig... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Rhonda_numbers | Rhonda numbers | A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors.
These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property.
25662 is ... | #Sidef | Sidef | func is_rhonda_number(n, base = 10) {
base.is_composite || return false
n > 0 || return false
n.digits(base).prod == base*n.factor.sum
}
for b in (2..16 -> grep { .is_composite }) {
say ("First 10 Rhonda numbers to base #{b}: ",
10.by { is_rhonda_number(_, b) })
} | Give a code snippet in #Sidef
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors.
These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows th... | #11l | 11l | V date = Time(2020, 2, 3)
print(‘First 15 palindrome dates after 2020-02-02 are:’)
V count = 0
L count < 15
V date_formatted = date.format(‘YYYYMMDD’)
I date_formatted == reversed(date_formatted)
print(‘date = ’date.format(‘YYYY-MM-DD’))
count++
date += TimeDelta(days' 1) | Give a code snippet in #11l
Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program ... | 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... | #langur | langur | val .factorial = f fold(f .x x .y, pseries .n)
writeln .factorial(7) | Give a code snippet in #langur
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/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #J | J | '£'
£
'札幌'
札幌 | Give a code snippet in #J
Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort | Sorting algorithms/Bead sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
runSample(arg)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method bead_sort(harry = Rexx[]) public static binary returns Rexx[]
MIN_ = 'MIN'
MAX_ = 'MAX'
beads = Rexx 0
beads[MIN_] = 0
... | Give a code snippet in #NetRexx
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/Integer_sequence | Integer sequence | Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integer... | #TUSCRIPT | TUSCRIPT | $$ MODE TUSCRIPT
LOOP n=0,999999999
n=n+1
ENDLOOP | Give a code snippet in #TUSCRIPT
Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations... | 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... | #Plain_English | Plain English | To run:
Start up.
Put 11 into a counter.
Loop.
If the counter is below 0, break.
Convert the counter to a string.
Write the string on the console.
Repeat.
Wait for the escape key.
Shut down.
To decide if a counter is below a number:
Subtract 1 from the counter.
If the counter is less than the number, say yes.
Say no. | Give a code snippet in #Plain_English
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
Loop... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pi... | #Raku | Raku | my ($x,$y) = 1280,720;
my @colors = 0, 1;
spurt "pinstripes.pgm", qq:to/EOH/ orelse .die;
P5
# pinstripes.pgm
$x $y
1
EOH
my $img = open "pinstripes.pgm", :a, :bin orelse .die;
my $vzones = $y div 4;
for 1..4 -> $w {
my $stripes = ceiling $x / $w / +@colors;
my $line = Buf.new: (flat((... | Give a code snippet in #Raku
Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display,... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Greatest_subsequential_sum | Greatest subsequential sum | Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be th... | #Icon_and_Unicon | Icon and Unicon | procedure main()
L1 := [-1,-2,3,5,6,-2,-1,4,-4,2,-1] # sample list
L := [-1,1,2,3,4,-11]|||L1 # prepend a local maximum into the mix
write(ximage(maxsubseq(L)))
end
link ximage # to show lists
procedure maxsubseq(L) #: return the subsequence of L with maximum positive sum
l... | Give a code snippet in #Icon_and_Unicon
Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all ele... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation langu... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function calcStandardDeviation(number As Double) As Double
Static a() As Double
Redim Preserve a(0 To UBound(a) + 1)
Dim ub As UInteger = UBound(a)
a(ub) = number
Dim sum As Double = 0.0
For i As UInteger = 0 To ub
sum += a(i)
Next
Dim mean As Double = sum / (ub + 1)
Dim dif... | Give a code snippet in #FreeBASIC
Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the f... | 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
| #COBOL | COBOL |
IDENTIFICATION DIVISION.
PROGRAM-ID. RANDOM.
AUTHOR. Bill Gunshannon
INSTALLATION. Home.
DATE-WRITTEN. 14 January 2022.
************************************************************
** Program Abstract:
** Able to get the Mean to be really close to 1.0 but
... | Give a code snippet in #COBOL
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... | 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 ... | #Applesoft_BASIC | Applesoft BASIC | 10 DEF FN MULTIPLY(P) = P(P) * P(P+1)
20 P(1) = 611 : P(2) = 78 : PRINT FN MULTIPLY(1) | Give a code snippet in #Applesoft_BASIC
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Stata | Stata | function map(f,a) {
nr = rows(a)
nc = cols(a)
b = J(nr,nc,.)
for (i=1;i<=nr;i++) {
for (j=1;j<=nc;j++) b[i,j] = (*f)(a[i,j])
}
return(b)
}
function maps(f,a) {
nr = rows(a)
nc = cols(a)
b = J(nr,nc,"")
for (i=1;i<=nr;i++) {
for (j=1;j<=nc;j++) b[i,j] = (*f)(a[i,j])
}
return(b)
}
function square(x) {... | Give a code snippet in #Stata
Task
Take a combined set of elements and apply a function to each element.
| 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... | #Oz | Oz | declare
%% maps items to tuples of
%% Weight(hectogram), Value and available Pieces
Problem = knapsack('map':9#150#1
'compass':13#35#1
'water':153#200#2
'sandwich':50#60#2
'glucose':15#60#2
'tin':68#45#3
... | Give a code snippet in #Oz
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/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Raku | Raku | use NativeCall;
class utimbuf is repr('CStruct') {
has int $.actime;
has int $.modtime;
submethod BUILD(:$atime, :$mtime) {
$!actime = $atime;
$!modtime = $mtime.to-posix[0].round;
}
}
sub sysutime(Str, utimbuf --> int32) is native is symbol('utime') {*}
sub MAIN (Str $file) {
... | Give a code snippet in #Raku
Task
Get and set the modification time of a file.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Population_count | Population count | Population count
You are encouraged to solve this task according to the task description, using any language you may know.
The population count is the number of 1s (ones) in the binary representation of a non-negative integer.
Population count is also known as:
pop count
popcount
sideways sum
... | #ALGOL_W | ALGOL W | begin
% returns the population count (number of bits on) of the non-negative integer n %
integer procedure populationCount( integer value n ) ;
begin
integer v, count;
v := n;
count := 0;
while v > 0 do begin
if ... | Give a code snippet in #ALGOL_W
Population count
You are encouraged to solve this task according to the task description, using any language you may know.
The population count is the number of 1s (ones) in the binary representation of a non-negative integer.
Population count is also known as:
pop cou... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #Standard_ML | Standard ML |
OS.Process.system "logger \"Log event\" " ;
| Give a code snippet in #Standard_ML
Task
Write script status to the Windows Event Log
| 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... | #EasyLang | EasyLang | func mean . f[] r .
for i range len f[]
s += f[i]
.
r = s / len f[]
.
f[] = [ 1 2 3 4 5 6 7 8 ]
call mean f[] r
print r | Give a code snippet in #EasyLang
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 e... | 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... | #Factor | Factor | USING: io kernel locals math sequences unicode.categories ;
IN: rosetta-code.caesar-cipher
:: cipher ( n s -- s' )
[| c |
c Letter? [
c letter? CHAR: a CHAR: A ? :> a
c a - n + 26 mod a +
]
[ c ] if
] :> shift
s [ shift call ] map ;
: encrypt ( n s -- s' )... | Give a code snippet in #Factor
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 t... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element ins... | #Rust | Rust | use std::collections::HashMap;
fn main() {
let mut olympic_medals = HashMap::new();
olympic_medals.insert("United States", (1072, 859, 749));
olympic_medals.insert("Soviet Union", (473, 376, 355));
olympic_medals.insert("Great Britain", (246, 276, 284));
olympic_medals.insert("Germany", (252, 260, 2... | Give a code snippet in #Rust
Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, E... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Fur... | #Delphi | Delphi |
program Arithmetic_Rational;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
Boost.Rational;
var
sum: TFraction;
max: Integer = 1 shl 19;
candidate, max2, factor: Integer;
begin
for candidate := 2 to max - 1 do
begin
sum := Fraction(1, candidate);
max2 := Trunc(Sqrt(candidate));
for factor ... | Give a code snippet in #Delphi
Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator ... | 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
)
)
,
... | #Octave | Octave | function r = F(n)
for i = 1:length(n)
if (n(i) == 0)
r(i) = 1;
else
r(i) = n(i) - M(F(n(i)-1));
endif
endfor
endfunction
function r = M(n)
for i = 1:length(n)
if (n(i) == 0)
r(i) = 0;
else
r(i) = n(i) - F(M(n(i)-1));
endif
endfor
endfunction | Give a code snippet in #Octave
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/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... | #Crystal | Crystal | File.write("input.txt", "a\nb\nc")
lines = Channel(String).new
spawn do
File.each_line("input.txt") do |line|
lines.send(line)
end
lines.close
end
while line = lines.receive?
puts line
end
File.delete("input.txt") | Give a code snippet in #Crystal
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 diffe... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Colour_bars/Display | Colour bars/Display | Task
Display a series of vertical color bars across the width of the display.
The color bars should either use:
the system palette, or
the sequence of colors:
black
red
green
blue
magenta
cyan
yellow
white
| #J | J | load 'viewmat'
size=: 2{.".wd'qm' NB. J6
size=: getscreenwh_jgtk_ '' NB. J7
'rgb'viewmat (|.size){. (>.&.(%&160)|.size)$ 20# 256#.255*#:i.8 | Give a code snippet in #J
Task
Display a series of vertical color bars across the width of the display.
The color bars should either use:
the system palette, or
the sequence of colors:
black
red
green
blue
magenta
cyan
yellow
white
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #FutureBasic | FutureBasic |
include "Tlbx agl.incl"
include "Tlbx glut.incl"
output file "Rotating Sphere"
local fn SphereDraw
'~'1
begin globals
dim as double sRotation // 'static' var
end globals
// Speed of rotation
sRotation += 2.9
glMatrixMode( _GLMODELVIEW )
glLoadIdentity()
// Position parameters: x axis, y axis, z axis
// Set... | Give a code snippet in #FutureBasic
Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
dra... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
R... | #Pure_Data | Pure Data |
#N canvas 1 51 450 300 10;
#X obj 66 67 gemwin;
#X obj 239 148 cuboid 2 3 4;
#X obj 239 46 gemhead;
#X obj 239 68 scale 0.3;
#X msg 66 45 lighting 1 \, create \, 1;
#X obj 61 118 gemhead;
#X obj 61 140 world_light;
#X msg 294 90 1;
#X obj 239 90 t a b;
#X obj 239 118 accumrotate;
#X connect 2 0 3 0;
#X connect 3 0 8 ... | Give a code snippet in #Pure_Data
Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projectio... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Happy_numbers | Happy numbers | From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not inclu... | #CLU | CLU | sum_dig_sq = proc (n: int) returns (int)
sum_sq: int := 0
while n > 0 do
sum_sq := sum_sq + (n // 10) ** 2
n := n / 10
end
return (sum_sq)
end sum_dig_sq
is_happy = proc (n: int) returns (bool)
nn: int := sum_dig_sq(n)
while nn ~= n cand nn ~= 1 do
n := sum_dig_sq(n)
... | Give a code snippet in #CLU
From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Vampire_number | Vampire number | A vampire number is a natural decimal number with an even number of digits, that can be factored into two integers.
These two factors are called the fangs, and must have the following properties:
they each contain half the number of the decimal digits of the original number
together they consist of exactl... | #11l | 11l | -V Pow10 = (0..18).map(n -> Int64(10) ^ n)
F isOdd(n)
R (n [&] 1) != 0
F fangs(n)
[(Int64, Int64)] r
V nDigits = sorted(String(n))
I isOdd(nDigits.len)
R r
V fangLen = nDigits.len I/ 2
V inf = Pow10[fangLen - 1]
L(d) inf .< inf * 10
I n % d != 0
L.continue
V q = n... | Give a code snippet in #11l
A vampire number is a natural decimal number with an even number of digits, that can be factored into two integers.
These two factors are called the fangs, and must have the following properties:
they each contain half the number of the decimal digits of the original number
to... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Archimedean_spiral | Archimedean spiral |
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.
An Archimedean spiral can be described by the equation:
r
=
a
+
b
θ
{\displaystyle \,r=a+b\theta }
with real numbers a and b.
Task
Draw an Archimedean spiral.
| #SAS | SAS | data xy;
h=constant('pi')/40;
do i=0 to 400;
t=i*h;
x=(1+t)*cos(t);
y=(1+t)*sin(t);
output;
end;
keep x y;
run;
proc sgplot;
series x=x y=y;
run; | Give a code snippet in #SAS
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.
An Archimedean spiral can be described by the equation:
r
=
a
+
b
θ
{\displaystyle \,r=a+b\theta }
with real numbers a and b.
Task
Draw an Archimedean spiral.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Patience_sort | Sorting algorithms/Patience sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #PicoLisp | PicoLisp | (de leftmost (Lst N H)
(let L 1
(while (<= L H)
(use (X)
(setq X (/ (+ L H) 2))
(if (>= (caar (nth Lst X)) N)
(setq H (dec X))
(setq L (inc X)) ) ) )
L ) )
(de patience (Lst)
(let (L (cons (cons (car Lst))) C 1 M NIL)
(for N (cdr Ls... | Give a code snippet in #PicoLisp
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/The_Name_Game | The Name Game | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary... | #Haskell | Haskell |
-- The Name Game, Ethan Riley, 22nd May 2018
import Data.Char
isVowel :: Char -> Bool
isVowel c
| char == 'A' = True
| char == 'E' = True
| char == 'I' = True
| char == 'O' = True
| char == 'U' = True
| otherwise = False
where char = toUpper c
isSpecial :: Char -> Bool
isSpecial c ... | Give a code snippet in #Haskell
Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be l... | christopher/rosetta-code | |
http://rosettacode.org/wiki/JortSort | JortSort |
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
... | #J | J | jortsort=: -: /:~ | Give a code snippet in #J
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... | 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... | #J | J | rot13=: {&((65 97+/~i.2 13) |.@[} i.256)&.(a.&i.) | Give a code snippet in #J
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 enc... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Luca... | #Go | Go | package main
import "fmt"
func computePerfect(n int64) bool {
var sum int64
for i := int64(1); i < n; i++ {
if n%i == 0 {
sum += i
}
}
return sum == n
}
// following function satisfies the task, returning true for all
// perfect numbers representable in the argument typ... | Give a code snippet in #Go
Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Polymorphic_copy | Polymorphic copy | An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x were unknown, then y could not be d... | #Elena | Elena | import extensions;
class T
{
Name = "T";
T clone() = new T();
}
class S : T
{
Name = "S";
T clone() = new S();
}
public program()
{
T original := new S();
T clone := original.clone();
console.printLine(original.Name);
console.printLine(clone.Name)
} | Give a code snippet in #Elena
An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x were... | christopher/rosetta-code | |
http://rosettacode.org/wiki/List_comprehensions | List comprehensions | A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name.
Some attributes of a list comprehension are:
They should be distinct from (nested) for loops and the use of map and filter functio... | #Wrapl | Wrapl | ALL WITH x <- 1:to(n), y <- x:to(n), z <- y:to(n) DO (x^2 + y^2 = z^2) & [x, y, z]; | Give a code snippet in #Wrapl
A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name.
Some attributes of a list comprehension are:
They should be distinct from (nested) for loops and th... | 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.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function sum35 (n As UInteger) As UInteger
If n = 0 Then Return 0
Dim As UInteger i, sum = 0
For i = 1 To n
If (i Mod 3 = 0) OrElse (i Mod 5 = 0) Then sum += i
Next
Return sum
End Function
Print "Sum of positive integers below 1000 divisible by 3 or 5 is : "; sum35(999)
Print
Print ... | Give a code snippet in #FreeBASIC
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/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an avera... | #Kotlin | Kotlin | // version 1.0.6
fun initMovingAverage(p: Int): (Double) -> Double {
if (p < 1) throw IllegalArgumentException("Period must be a positive integer")
val list = mutableListOf<Double>()
return {
list.add(it)
if (list.size > p) list.removeAt(0)
list.average()
}
}
fun main(args: ... | Give a code snippet in #Kotlin
Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Ada | Ada | with Ada.Text_IO;
procedure Cantor_Set is
subtype Level_Range is Integer range 1 .. 5;
Image : array (Level_Range) of String (1 .. 81) := (others => (others => ' '));
procedure Cantor (Level : Natural; Length : Natural; Start : Natural) is
begin
if Level in Level_Range then
Image (Level... | Give a code snippet in #Ada
Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Hamming_numbers | Hamming numbers | Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming numbers, in increasing order. In ... | #Elixir | Elixir | defmodule Hamming do
def generater do
queues = [{2, queue}, {3, queue}, {5, queue}]
Stream.unfold({1, queues}, fn {n, q} -> next(n, q) end)
end
defp next(n, queues) do
queues = Enum.map(queues, fn {m, queue} -> {m, push(queue, m*n)} end)
min = Enum.map(queues, fn {_, queue} -> top(queue) end)... | Give a code snippet in #Elixir
Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming num... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sudoku | Sudoku | Task
Solve a partially filled-in normal 9x9 Sudoku grid and display the result in a human-readable format.
references
Algorithmics of Sudoku may help implement this.
Python Sudoku Solver Computerphile video.
| #Befunge | Befunge | 99*>1-:0>:#$"0"\# #~`#$_"0"-\::9%:9+00p3/\9/:99++10p3vv%2g\g01<
2%v|:p+9/9\%9:\p\g02\1p\g01\1:p\g00\1:+8:\p02+*93+*3/<>\20g\g#:
v<+>:0\`>v >\::9%:9+00p3/\9/:99++10p3/3*+39*+20p\:8+::00g\g2%\^
v^+^pppp$_:|v<::<_>1-::9%\9/9+g.::9%!\3%+>>#v_>" "v..v,<<<+55<<
03!$v9:_>1v$>9%\v^|:<_v#<%<9<:<<_v#+%*93\!::<,,"|"<\/>:#^_>>>v^
... | Give a code snippet in #Befunge
Task
Solve a partially filled-in normal 9x9 Sudoku grid and display the result in a human-readable format.
references
Algorithmics of Sudoku may help implement this.
Python Sudoku Solver Computerphile video.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Compile-time_calculation | Compile-time calculation | Some programming languages allow calculation of values at compile time.
Task
Calculate 10! (ten factorial) at compile time.
Print the result when the program is run.
Discuss what limitations apply to compile-time calculations in your language.
| #Forth | Forth | : fac ( n -- n! ) 1 swap 1+ 2 max 2 ?do i * loop ;
: main ." 10! = " [ 10 fac ] literal . ;
see main
: main
.\" 10! = " 3628800 . ; ok | Give a code snippet in #Forth
Some programming languages allow calculation of values at compile time.
Task
Calculate 10! (ten factorial) at compile time.
Print the result when the program is run.
Discuss what limitations apply to compile-time calculations in your language.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Knuth_shuffle | Knuth shuffle | The Knuth shuffle (a.k.a. the Fisher-Yates shuffle) is an algorithm for randomly shuffling the elements of an array.
Task
Implement the Knuth shuffle for an integer array (or, if possible, an array of any type).
Specification
Given an array items with indices ranging from 0 to last, the algorithm can be d... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program knuthshuffle64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstante... | Give a code snippet in #AArch64_Assembly
The Knuth shuffle (a.k.a. the Fisher-Yates shuffle) is an algorithm for randomly shuffling the elements of an array.
Task
Implement the Knuth shuffle for an integer array (or, if possible, an array of any type).
Specification
Given an array items with indices rang... | christopher/rosetta-code | |
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas | The Twelve Days of Christmas | Task
Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
Other tasks related to string operations:
Metrics
Array length
Stri... | #Crystal | Crystal | days = "first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth".split " "
gifts = "A partridge in a pear tree
Two turtle doves and
Three french hens
Four calling birds
Five golden rings
Six geese a-laying
Seven swans a-swimming
Eight maids a-milking
Nine ladies dancing
Ten lords a-leaping
Ele... | Give a code snippet in #Crystal
Task
Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
Other tasks related to string operati... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #Factor | Factor | USING: interpolate kernel math math.parser qw sequences ;
CONSTANT: table
{
{ 0 3 1 7 5 9 8 6 4 2 }
{ 7 0 9 2 1 5 4 8 6 3 }
{ 4 2 0 6 8 7 1 3 5 9 }
{ 1 7 5 0 9 8 3 4 2 6 }
{ 6 1 2 3 0 4 5 9 7 8 }
{ 3 6 7 4 2 0 9 5 8 1 }
{ 5 8 6 9 7 2 0 1 3 4 }
{ 8 9 4 5 3 6 2 0 1 7 }
{ 9 4 3 8 6 1 ... | Give a code snippet in #Factor
The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Five_weekends | Five weekends | The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at leas... | #AutoHotkey | AutoHotkey | Year := 1900
End_Year := 2100
31_Day_Months = 01,03,05,07,08,10,12
While Year <= End_Year
{
Loop, Parse, 31_Day_Months, CSV
{
FormatTime, Day, %Year%%A_LoopField%01, dddd
IfEqual, Day, Friday
{
All_Months_With_5_Weekends .= A_LoopField . "/" . Year ", "
... | Give a code snippet in #AutoHotkey
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property ... | 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 .
| #Factor | Factor |
! with ("::") or without (":") generalizations:
! : [a..b] ( steps a b -- a..b ) 2dup swap - 4 nrot 1 - / <range> ;
:: [a..b] ( steps a b -- a..b ) a b b a - steps 1 - / <range> ;
: >char ( n -- c )
dup -1 = [ drop 32 ] [ 26 mod CHAR: a + ] if ;
! iterates z' = z^2 + c, Factor does complex numbers!
: iter ( ... | Give a code snippet in #Factor
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/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... | #Objeck | Objeck | class JaroDistance {
function : Main(args : String[]) ~ Nil {
Jaro("MARTHA", "MARHTA")->PrintLine();
Jaro("DIXON", "DICKSONX")->PrintLine();
Jaro("JELLYFISH", "SMELLYFISH")->PrintLine();
}
function : Jaro(s : String, t : String) ~ Float {
s_len := s->Size();
t_len := t->Size();
if (s_... | Give a code snippet in #Objeck
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 a... | christopher/rosetta-code | |
http://rosettacode.org/wiki/McNuggets_problem | McNuggets problem | Wikipedia
The McNuggets version of the coin problem was introduced by Henri Picciotto,
who included it in his algebra textbook co-authored with Anita Wah. Picciotto
thought of the application in the 1980s while dining with his son at
McDonald's, working the problem out on a napkin. A McNugget number is
the total number... | #Comal | Comal | 0010 limit#:=100
0020 DIM nugget#(0:limit#)
0030 FOR a#:=0 TO limit# STEP 6 DO
0040 FOR b#:=a# TO limit# STEP 9 DO
0050 FOR c#:=b# TO limit# STEP 20 DO nugget#(c#):=TRUE
0060 ENDFOR b#
0070 ENDFOR a#
0080 FOR i#:=limit# TO 0 STEP -1 DO
0090 IF NOT nugget#(i#) THEN
0100 PRINT "Maximum non-McNuggets number:... | Give a code snippet in #Comal
Wikipedia
The McNuggets version of the coin problem was introduced by Henri Picciotto,
who included it in his algebra textbook co-authored with Anita Wah. Picciotto
thought of the application in the 1980s while dining with his son at
McDonald's, working the problem out on a napkin. A McNu... | 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... | #REXX | REXX | /*REXX program solves a (Pascal's) "Pyramid of Numbers" puzzle given four values. */
/* ╔══════════════════════════════════════════════════╗
║ answer ║
║ / ║
║ mid / ... | Give a code snippet in #REXX
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/Mian-Chowla_sequence | Mian-Chowla sequence | The Mian–Chowla sequence is an integer sequence defined recursively.
Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences.
The sequence starts with:
a1 = 1
then for n > 1, an is the smallest positive integer such that every pairwise sum
ai + aj
is distinct, fo... | #Factor | Factor | USING: fry hash-sets io kernel math prettyprint sequences sets ;
: next ( seq sums speculative -- seq' sums' speculative' )
dup reach [ + ] with map over dup + suffix! >hash-set pick
over intersect null?
[ swapd union [ [ suffix! ] keep ] dip swap ] [ drop ] if
1 + ;
: mian-chowla ( n -- seq )
[... | Give a code snippet in #Factor
The Mian–Chowla sequence is an integer sequence defined recursively.
Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences.
The sequence starts with:
a1 = 1
then for n > 1, an is the smallest positive integer such that every pairwi... | 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... | #Lasso | Lasso | infinity
'<br />'
infinity -> type | Give a code snippet in #Lasso
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/Y_combinator | Y combinator | In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's stat... | #Forth | Forth | \ Address of an xt.
variable 'xt
\ Make room for an xt.
: xt, ( -- ) here 'xt ! 1 cells allot ;
\ Store xt.
: !xt ( xt -- ) 'xt @ ! ;
\ Compile fetching the xt.
: @xt, ( -- ) 'xt @ postpone literal postpone @ ;
\ Compile the Y combinator.
: y, ( xt1 -- xt2 ) >r :noname @xt, r> compile, postpone ; ;
\ Make a new instan... | Give a code snippet in #Forth
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a va... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, ... | #Klingphix | Klingphix | :mypower
dup not (
[ drop sign dup 0 equal [ drop 1 ] if ]
[ power ]
) if
;
0 0 mypower print nl
"End " input | Give a code snippet in #Klingphix
Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 ... | 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.
| #Picat | Picat | main =>
Reader = open("file.txt"),
while(not at_end_of_stream(Reader))
L = read_line(Reader),
println(L)
end,
close(Reader). | Give a code snippet in #Picat
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/Peano_curve | Peano curve |
Task
Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
| #VBA | VBA | Const WIDTH = 243 'a power of 3 for a evenly spaced curve
Dim n As Long
Dim points() As Single
Dim flag As Boolean
'Store the coordinate pairs (x, y) generated by Peano into
'a SafeArrayOfPoints with lineto. The number of points
'generated depend on WIDTH. Peano is called twice. Once
'to count the number of points, and... | Give a code snippet in #VBA
Task
Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
| 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... | #Python | Python |
# Python Program to evaluate
# Mobius def M(N) = 1 if N = 1
# M(N) = 0 if any prime factor
# of N is contained twice
# M(N) = (-1)^(no of distinct
# prime factors)
# Python Program to
# evaluate Mobius def
# M(N) = 1 if N = 1
# M(N) = 0 if any
# prime factor of
# N is contained twice
# M(N) = (-1)^(no of
# distinct p... | Give a code snippet in #Python
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Reverse_words_in_a_string | Reverse words in a string | Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); t... | #SenseTalk | SenseTalk | set poem to {{
---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------
}}
repeat with each line in poem
put (each word of it) reversed joined b... | Give a code snippet in #SenseTalk
Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #Julia | Julia | const ESC = "\u001B" # escape code
print("$ESC[?25l") # hide the cursor
print("Enter anything, press RETURN: ") # prompt shown
input = readline() # but no cursor
print("$ESC[0H$ESC[0J$ESC[?25h") # reset, visible again
sleep(3)
println()
| Give a code snippet in #Julia
The task is to hide the cursor and show it again.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same 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 the same
indicate if or which character is different from the previous character
display each string and its length (as the... | #Python | Python | '''Determine if a string has all the same characters'''
from itertools import groupby
# firstDifferingCharLR :: String -> Either String Dict
def firstDifferingCharLR(s):
'''Either a message reporting that no character changes were
seen, or a dictionary with details of the first character
(if an... | 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 the same
indicate if or which character is different from the previous character
display each... | christopher/rosetta-code | |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning:... | #Raku | Raku | use Digest::MD5;
say Digest::MD5.md5_hex: "The quick brown fox jumped over the lazy dog's back"; | Give a code snippet in #Raku
Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the W... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Numeric_error_propagation | Numeric error propagation | If f, a, and b are values with uncertainties σf, σa, and σb, and c is a constant;
then if f is derived from a, b, and c in the following ways,
then σf can be calculated as follows:
Addition/Subtraction
If f = a ± c, or f = c ± a then σf = σa
If f = a ± b then... | #REXX | REXX | /*REXX program calculates the distance between two points (2D) with error propagation. */
parse arg a b . /*obtain arguments from the CL*/
if a=='' | a=="," then a= '100±1.1, 50±1.2' /*Not given? Then use default.*/
if b=='' | b=="," then b= '200±2.2, 100±2.3' ... | Give a code snippet in #REXX
If f, a, and b are values with uncertainties σf, σa, and σb, and c is a constant;
then if f is derived from a, b, and c in the following ways,
then σf can be calculated as follows:
Addition/Subtraction
If f = a ± c, or f = c ± a then ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Bernoulli_numbers | Bernoulli numbers | Bernoulli numbers are used in some series expansions of several functions (trigonometric, hyperbolic, gamma, etc.), and are extremely important in number theory and analysis.
Note that there are two definitions of Bernoulli numbers; this task will be using the modern usage (as per The National Institute of S... | #jq | jq | # def negate:
# def lessOrEqual(x; y): # x <= y
# def long_add(x;y): # x+y
# def long_minus(x;y): # x-y
# def long_multiply(x;y) # x*y
# def long_divide(x;y): # x/y => [q,r]
# def long_div(x;y) # integer division
# def long_mod(x;y) # %
# In all cases, x and y must be strings
def negate: (- tonumbe... | Give a code snippet in #jq
Bernoulli numbers are used in some series expansions of several functions (trigonometric, hyperbolic, gamma, etc.), and are extremely important in number theory and analysis.
Note that there are two definitions of Bernoulli numbers; this task will be using the modern usage (as per ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Letter_frequency | Letter frequency | Task
Open a text file and count the occurrences of each letter.
Some of these programs count all characters (including punctuation),
but some only count letters A to Z.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequen... | #Java | Java | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
public class LetterFreq {
public static int[] countLetters(String filename) throws IOException{
int[] freqs = new int[26];
BufferedReader in = new BufferedReader(new FileReader(filename));
String line... | Give a code snippet in #Java
Task
Open a text file and count the occurrences of each letter.
Some of these programs count all characters (including punctuation),
but some only count letters A to Z.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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... | #Forth | Forth | : fsqrt2 1 s>f 0> if 2 s>f else fdup then ;
: fnapier dup dup 1 > if 1- else drop 1 then s>f dup 1 < if drop 2 then s>f ;
: fpi dup 2* 1- dup * s>f 0> if 6 else 3 then s>f ;
( n -- f1 f2)
: cont.fraction ( xt n -- f)
1 swap 1+ 0 s>f \ ... | Give a code snippet in #Forth
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 wri... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Permutations_by_swapping | Permutations by swapping | Task
Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.
Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd.
Show the permutations and signs ... | #AutoHotkey | AutoHotkey | Permutations_By_Swapping(str, list:=""){
ch := SubStr(str, 1, 1) ; get left-most charachter of str
for i, line in StrSplit(list, "`n") ; for each line in list
loop % StrLen(line) + 1 ; loop each possible position
Newlist .= RegExReplace(line, mod(i,2) ? "(?=.{" A_Index-1 "}$)" : "^.{" A_Index-1 ... | Give a code snippet in #AutoHotkey
Task
Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.
Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for od... | christopher/rosetta-code | |
http://rosettacode.org/wiki/ABC_problem | ABC problem | ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all sid... | #Common_Lisp | Common Lisp |
(defun word-possible-p (word blocks)
(cond
((= (length word) 0) t)
((null blocks) nil)
(t (let*
((c (aref word 0))
(bs (remove-if-not #'(lambda (b)
(find c b :test #'char-equal))
blocks)))
(some #'identity
... | Give a code snippet in #Common_Lisp
ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete a... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
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 l... | #Salmon | Salmon | while (true)
"SPAM"!; | Give a code snippet in #Salmon
Task
Print out SPAM followed by a newline in an infinite loop.
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
Loo... | 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 |... | #REXX | REXX | /*REXX program demonstrates some basic character string testing (for matching). */
parse arg A B /*obtain A and B from the command line.*/
say 'string A = ' A /*display string A to the terminal.*/
say 'string B = ' B ... | Give a code snippet in #REXX
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/General_FizzBuzz | General FizzBuzz | Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be ... | #Ursa | Ursa | #
# general fizzbuzz
#
decl int<> factors
decl string<> words
decl int max
# get the max number
out ">" console
set max (in int console)
# get the factors
decl string input
set input " "
while (not (= input ""))
out ">" console
set input (in string console)
if (not (= input ""))
... | Give a code snippet in #Ursa
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with... | christopher/rosetta-code | |
http://rosettacode.org/wiki/15_puzzle_game | 15 puzzle game |
Task
Implement the Fifteen Puzzle Game.
The 15-puzzle is also known as:
Fifteen Puzzle
Gem Puzzle
Boss Puzzle
Game of Fifteen
Mystic Square
14-15 Puzzle
and some others.
Related Tasks
15 Puzzle Solver
16 Puzzle Game
| #PureBasic | PureBasic |
#difficulty=10 ;higher is harder
#up="u"
#down="d"
#left="l"
#right="r"
OpenConsole("15 game"):EnableGraphicalConsole(1)
Global Dim Game.i(3,3)
Global hole.point
Procedure NewBoard()
num.i=0
For j=0 To 3
For i=0 To 3
Game(i,j)=num
num+1
Next i
Next j
EndProcedure
... | Give a code snippet in #PureBasic
Task
Implement the Fifteen Puzzle Game.
The 15-puzzle is also known as:
Fifteen Puzzle
Gem Puzzle
Boss Puzzle
Game of Fifteen
Mystic Square
14-15 Puzzle
and some others.
Related Tasks
15 Puzzle Solver
16 Puzzle Game
| christopher/rosetta-code | |
http://rosettacode.org/wiki/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)
... | #Emacs_Lisp | Emacs Lisp | (defun fizzbuzz (n)
(cond ((and (zerop (% n 5)) (zerop (% n 3))) "FizzBuzz")
((zerop (% n 3)) "Fizz")
((zerop (% n 5)) "Buzz")
(t n)))
;; loop & print from 0 to 100
(dotimes (i 101)
(message "%s" (fizzbuzz i))) | Give a code snippet in #Emacs_Lisp
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 Fiz... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
... | #Run_BASIC | Run BASIC | x$ = str$( 5^(4^(3^2)))
print "Length:";len( x$)
print left$( x$, 20); "......"; right$( x$, 20) | Give a code snippet in #Run_BASIC
Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
... | 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 ... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 DEF FN e(a)=a-INT (a/2)*2-1
20 DEF FN h(a)=INT (a/2)
30 DEF FN d(a)=2*a
40 LET x=17: LET y=34: LET tot=0
50 IF x<1 THEN GO TO 100
60 PRINT x;TAB (4);
70 IF FN e(x)=0 THEN LET tot=tot+y: PRINT y: GO TO 90
80 PRINT "---"
90 LET x=FN h(x): LET y=FN d(y): GO TO 50
100 PRINT TAB (4);"===",TAB (4);tot | Give a code snippet in #ZX_Spectrum_Basic
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 remai... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Smalltalk | Smalltalk | [ 4 + 5 ] value. | Give a code snippet in #Smalltalk
Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if app... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Abelian_sandpile_model/Identity | Abelian sandpile model/Identity | Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that
contain a number from 0 to 3 inclusive. (The numbers are said to represent
grains of sand in each area of the sandpile).
E.g. s1 =
1 2 0
2 1 1
0 1 3
and s2 =
2 1 3
1 0 1
0 1 0
Addition on sandpiles is done by a... | #Lua | Lua | sandpile.__index = sandpile
sandpile.new = function(self, vals)
local inst = setmetatable({},sandpile)
inst.cell, inst.dim = {}, #vals
for r = 1, inst.dim do
inst.cell[r] = {}
for c = 1, inst.dim do
inst.cell[r][c] = vals[r][c]
end
end
return inst
end
sandpile.add = function(self, other)
l... | Give a code snippet in #Lua
Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that
contain a number from 0 to 3 inclusive. (The numbers are said to represent
grains of sand in each area of the sandpile).
E.g. s1 =
1 2 0
2 1 1
0 1 3
and s2 =
2 1 3
1 0 1
0 1 0
Addit... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible,... | #zkl | zkl | const HOST="tycho.usno.navy.mil", PORT=80, dir="/cgi-bin/timer.pl";
get:="GET %s HTTP/1.0\r\nHost: %s:%s\r\n\r\n".fmt(dir,HOST,PORT);
server:=Network.TCPClientSocket.connectTo(HOST,PORT);
server.write(get); // send request to web serer
data:=server.read(True); // read data from web server
data.seek(data.find("U... | Give a code snippet in #zkl
Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Cut_a_rectangle | Cut a rectangle | A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths for 2 × 2 and 4 × 3 rectangles... | #Julia | Julia |
const count = [0]
const dir = [[0, -1], [-1, 0], [0, 1], [1, 0]]
function walk(y, x, h, w, grid, len, next)
if y == 0 || y == h || x == 0 || x == w
count[1] += 2
return
end
t = y * (w + 1) + x
grid[t + 1] += UInt8(1)
grid[len - t + 1] += UInt8(1)
for i in 1:4
if grid[... | Give a code snippet in #Julia
A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Unicode_variable_names | Unicode variable names | Task
Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables.
Show how to:
Set a variable with a name including the 'Δ', (delta character), to 1
Increment it
Print its value.
Related task
Case-sensitivity of identif... | #Crystal | Crystal | Δ = 1
Δ += 1
puts Δ | Give a code snippet in #Crystal
Task
Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables.
Show how to:
Set a variable with a name including the 'Δ', (delta character), to 1
Increment it
Print its value.
Related ta... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Equilibrium_index | Equilibrium index | An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
:
A
0
=
−
7
{\displaystyle A_{0}=-7}
A
1
=
1
{\displaystyle A_{1}=1}
... | #Oforth | Oforth | : equilibrium(l)
| ls rs i e |
0 ->ls
l sum ->rs
ListBuffer new l size loop: i [
l at(i) ->e
rs e - dup ->rs ls == ifTrue: [ i over add ]
ls e + ->ls
] ; | Give a code snippet in #Oforth
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
:
A
0
=
−
7
{\displaystyle A_{0}=-7}
A
1
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #PicoLisp | PicoLisp | (out "output.txt") # Empty output
(call 'mkdir "docs") # Call external
(out "/output.txt")
(call 'mkdir "/docs") | Give a code snippet in #PicoLisp
In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
... | #PL.2FM | PL/M | 100H:
DECLARE ORDER LITERALLY '4';
/* CP/M BDOS CALL */
BDOS: PROCEDURE (FN, ARG);
DECLARE FN BYTE, ARG ADDRESS;
GO TO 5;
END BDOS;
PUT$CHAR: PROCEDURE (CHAR);
DECLARE CHAR BYTE;
CALL BDOS(2, CHAR);
END PUT$CHAR;
/* PRINT SIERPINSKI TRIANGLE */
DECLARE (X, Y, SIZE) BYTE;
SIZE = SHL(1, ORDER);
... | Give a code snippet in #PL.2FM
Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hough_transform | Hough transform | Task
Implement the Hough transform, which is used as part of feature extraction with digital images.
It is a tool that makes it far easier to identify straight lines in the source image, whatever their orientation.
The transform maps each point in the target image,
(
ρ
,
θ
)
{\displaystyle (\rho ,\theta )}
, ... | #Perl | Perl | use strict;
use warnings;
use Imager;
use constant pi => 3.14159265;
sub hough {
my($im) = shift;
my($width) = shift || 460;
my($height) = shift || 360;
$height = 2 * int $height/2;
$height = 2 * int $height/2;
my($xsize, $ysize) = ($im->getwidth, $im->getheight);
my $ht = Image... | Give a code snippet in #Perl
Task
Implement the Hough transform, which is used as part of feature extraction with digital images.
It is a tool that makes it far easier to identify straight lines in the source image, whatever their orientation.
The transform maps each point in the target image,
(
ρ
,
θ
)
{\dis... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Ada | Ada | with Ada.Text_Io; use Ada.Text_Io;
generic
SortName : in String;
type DataType is (<>);
type SortArrayType is array (Integer range <>) of DataType;
with procedure Sort (SortArray : in out SortArrayType;
Comp, Write, Ex : in out Natural);
package Instrument is
-- This generic p... | Give a code snippet in #Ada
See also
Related task: Comments
Related task: Here_document
| christopher/rosetta-code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.