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/Accumulator_factory | Accumulator factory | A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat... | #Icon_and_Unicon | Icon and Unicon | procedure main()
a := genAcc(3)
b := genAcc(5)
write(" " ,center("a",5), " ", center("b", 5))
write("genAcc: ", right(a(4),5), " ", right(b(4), 5))
write("genAcc: ", right(a(2),5), " ", right(b(3),5))
write("genAcc: ", right(a(4.5),5)," ", right(b(1.3),5))
end
procedure genAcc(n) ... | Give a code snippet in #Icon_and_Unicon
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric ... | 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 ... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
' The biggest integer which FB supports natively is 8 bytes so unable
' to calculate 1 millionth Hamming number without using an external
' "bigint" library such as GMP
Function min(x As Integer, y As Integer) As Integer
Return IIf(x < y, x, y)
End Function
Function hamming(n As Integer) As I... | Give a code snippet in #FreeBASIC
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 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/String_length | String length | Task
Find the character and byte length of a string.
This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters.
By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters.
F... | #AutoHotkey | AutoHotkey | Msgbox % StrLen("Hello World") | Give a code snippet in #AutoHotkey
Task
Find the character and byte length of a string.
This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters.
By character, we mean an individual Unicode code point, not a user-visible grapheme... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which ... | #MAXScript | MAXScript | fn isPalindrome s =
(
local reversed = ""
for i in s.count to 1 by -1 do reversed += s[i]
return reversed == s
) | Give a code snippet in #MAXScript
A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibl... | christopher/rosetta-code | |
http://rosettacode.org/wiki/GUI_enabling/disabling_of_controls | GUI enabling/disabling of controls | In addition to fundamental GUI component interaction, an application should
dynamically enable and disable GUI components, to give some guidance to the
user, and prohibit (inter)actions which are inappropriate in the current state
of the application.
Task
Similar to the task GUI component interaction, write a progr... | #Fantom | Fantom | using fwt
using gfx
class Main
{
public static Void main ()
{
Window
{
textField := Text
{
text = "0"
}
incButton := Button
{
text = "increment"
onAction.add |Event e|
{
if (textField.text != "")
{
try
... | Give a code snippet in #Fantom
In addition to fundamental GUI component interaction, an application should
dynamically enable and disable GUI components, to give some guidance to the
user, and prohibit (inter)actions which are inappropriate in the current state
of the application.
Task
Similar to the task GUI comp... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Cramer%27s_rule | Cramer's rule | linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1... | #Sidef | Sidef | func cramers_rule(A, terms) {
gather {
for i in ^A {
var Ai = A.map{.map{_}}
for j in ^terms {
Ai[j][i] = terms[j]
}
take(Ai.det)
}
} »/» A.det
}
var matrix = [
[2, -1, 5, 1],
[3, 2, 2, -6],
[1, 3, 3, -1],
[5... | Give a code snippet in #Sidef
linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Gamma_function | Gamma function | Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.
The Gamma funct... | #Scilab | Scilab | function x=gammal(z) // Lanczos'
lz=[ 1.000000000190015 ..
76.18009172947146 -86.50532032941677 24.01409824083091 ..
-1.231739572450155 1.208650973866179e-3 -5.395239384953129e-6 ]
if z < 0.5 then
x=%pi/sin(%pi*z)-gammal(1-z)
else
z=z-1.0
b=z+5.5
... | Give a code snippet in #Scilab
Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/li... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Extend_your_language | Extend your language | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other langua... | #Clay | Clay | alias if2(cond1:Bool,
cond2:Bool,
both,
first,
second,
neither)
{
var res1 = cond1;
var res2 = cond2;
if (res1 and res2) return both;
if (res1) return first;
if (res2) return second;
return neither;
}
| Give a code snippet in #Clay
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Last_Friday_of_each_month | Last Friday of each month | Task
Write a program or a script that returns the date of the last Fridays of each month of a given year.
The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_fridays 2012
2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
20... | #J | J | require 'dates'
last_fridays=: 12 {. [: ({:/.~ }:"1)@(#~ 5 = weekday)@todate (i.366) + todayno@,&1 1 | Give a code snippet in #J
Task
Write a program or a script that returns the date of the last Fridays of each month of a given year.
The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_fridays 2012
2012-01-27
2012-02-24
2012-03-... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Fork | Fork | Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
| #R | R |
p <- parallel::mcparallel({
Sys.sleep(1)
cat("\tChild pid: ", Sys.getpid(), "\n")
TRUE
})
cat("Main pid: ", Sys.getpid(), "\n")
parallel::mccollect(p)
p <- parallel:::mcfork()
if (inherits(p, "masterProcess")) {
Sys.sleep(1)
cat("\tChild pid: ", Sys.getpid(), "\n")
pa... | Give a code snippet in #R
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to ... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
const func float: computePrice (in float: x) is func
result
var float: price is 0.0;
begin
if x >= 0.0 and x < 0.06 then
price := 0.10;
elsif x < 0.11 then
price := 0.18;
elsif x < 0.36 then
price := flt(((trunc(x * 100.0) - 11) di... | Give a code snippet in #Seed7
A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/24_game/Solve | 24 game/Solve | task
Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game.
Show examples of solutions generated by the program.
Related task
Arithmetic Evaluator
| #Racket | Racket |
(define (in-variants n1 o1 n2 o2 n3 o3 n4)
(let ([o1n (object-name o1)]
[o2n (object-name o2)]
[o3n (object-name o3)])
(with-handlers ((exn:fail:contract:divide-by-zero? (λ (_) empty-sequence)))
(in-parallel
(list (o1 (o2 (o3 n1 n2) n3) n4)
(o1 (o2 n1 (o3 n2 n3)) n4... | Give a code snippet in #Racket
task
Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game.
Show examples of solutions generated by the program.
Related task
Arithmetic Evaluator
| 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... | #AppleScript | AppleScript | use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
use scripting additions
on letterFrequencyinFile(theFile)
-- Read the file as an NSString, letting the system guess the encoding.
set fileText to current application's class "NSString"'s stringWithContentsOfFile:(POSIX ... | Give a code snippet in #AppleScript
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1... | #Python | Python | def binomialCoeff(n, k):
result = 1
for i in range(1, k+1):
result = result * (n-i+1) / i
return result
if __name__ == "__main__":
print(binomialCoeff(5, 3)) | Give a code snippet in #Python
This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hailstone_sequence | Hailstone sequence | The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conje... | #Oz | Oz | declare
fun {HailstoneSeq N}
N > 0 = true %% assert
if N == 1 then [1]
elseif {IsEven N} then N|{HailstoneSeq N div 2}
else N|{HailstoneSeq 3*N+1}
end
end
HSeq27 = {HailstoneSeq 27}
{Length HSeq27} = 112
{List.take HSeq27 4} = [27 82 41 124]
{List.drop HS... | Give a code snippet in #Oz
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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... | #Nim | Nim | import os, strutils, tables
const Morse = {'A': ".-", 'B': "-...", 'C': "-.-.", 'D': "-..", 'E': ".",
'F': "..-.", 'G': "--.", 'H': "....", 'I': "..", 'J': ".---",
'K': "-.-", 'L': ".-..", 'M': "--", 'N': "-.", 'O': "---",
'P': ".--.",... | Give a code snippet in #Nim
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 u... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Metronome | Metronome |
The task is to implement a metronome.
The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable.
For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an ext... | #Phix | Phix | --
-- demo\rosetta\virtunome.exw
--
-- Originally by ghaberek
-- Translated from win32lib by Pete Lomax
--
-- I will note that accuracy drops sharply above 5 beats per second.
--
with javascript_semantics -- needs some work though, usual sizing stuff [DEV]
-- NB: don't break Morse_code.... | Give a code snippet in #Phix
The task is to implement a metronome.
The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable.
For the purpose of this task, it is acceptable to play sound files for production... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Multi-dimensional_array | Multi-dimensional array | For the purposes of this task, the actual memory layout or access method of this data structure is not mandated.
It is enough to:
State the number and extent of each index to the array.
Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value.
... | #X86-64_Assembly | X86-64 Assembly |
option casemap:none
printf proto :qword, :vararg
exit proto :dword
ROW_LEN equ (4*4)
MEM_SIZE equ 4
.data
;; A 2d array - 2 rows, 4 columns
;; int twodimen[2][4] = { {0,1,2,3},
;; {4,5,6,7}};
twodimen db 48 dup (0)
tpl db "%d",13,10,0
.code
main proc
l... | Give a code snippet in #X86-64_Assembly
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated.
It is enough to:
State the number and extent of each index to the array.
Provide specific, ordered, integer indices for all dimensions of the array together with ... | 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:... | #Nim | Nim | import md5
echo toMD5("The quick brown fox jumped over the lazy dog's back") | Give a code snippet in #Nim
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 Wi... | 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 ... | #bash | bash | #!/bin/bash
mapfile < $0
printf "%s" "${MAPFILE[@]}" | Give a code snippet in #bash
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
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pythagorean_triples | Pythagorean triples | A Pythagorean triple is defined as three positive integers
(
a
,
b
,
c
)
{\displaystyle (a,b,c)}
where
a
<
b
<
c
{\displaystyle a<b<c}
, and
a
2
+
b
2
=
c
2
.
{\displaystyle a^{2}+b^{2}=c^{2}.}
They are called primitive triples if
a
,
b
,
c
{\displaystyle a,b,c}
are co-prime,... | #Phix | Phix | with javascript_semantics
atom total, prim, maxPeri = 10
procedure tri(atom s0, s1, s2)
atom p = s0 + s1 + s2
if p<=maxPeri then
prim += 1
total += floor(maxPeri/p)
tri( s0+2*(-s1+s2), 2*( s0+s2)-s1, 2*( s0-s1+s2)+s2);
tri( s0+2*( s1+s2), 2*( s0+s2)+s1, 2*( s0+s1+s2)+s2);
t... | Give a code snippet in #Phix
A Pythagorean triple is defined as three positive integers
(
a
,
b
,
c
)
{\displaystyle (a,b,c)}
where
a
<
b
<
c
{\displaystyle a<b<c}
, and
a
2
+
b
2
=
c
2
.
{\displaystyle a^{2}+b^{2}=c^{2}.}
They are called primitive triples if
a
,
b
,
c
{\displ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Collections | Collections | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Collections are abstractions to represent sets of values.
In statically-typed languages, the values are typically of a common data type.
Task
Create a collection, and add a fe... | #D | D | int[3] array;
array[0] = 5;
// array.length = 4; // compile-time error | Give a code snippet in #D
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Collections are abstractions to represent sets of values.
In statically-typed languages, the values are typically of a common data type.
Task
Create... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Flipping_bits_game | Flipping bits game | The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any 1 ... | #Perl | Perl | #!perl
use strict;
use warnings qw(FATAL all);
my $n = shift(@ARGV) || 4;
if( $n < 2 or $n > 26 ) {
die "You can't play a size $n game\n";
}
my $n2 = $n*$n;
my (@rows, @cols);
for my $i ( 0 .. $n-1 ) {
my $row = my $col = "\x00" x $n2;
vec($row, $i * $n + $_, 8) ^= 1 for 0 .. $n-1;
vec($col, $i + $_ * $n, 8) ... | Give a code snippet in #Perl
The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card mu... | #Java | Java | public enum Pip { Two, Three, Four, Five, Six, Seven,
Eight, Nine, Ten, Jack, Queen, King, Ace } | Give a code snippet in #Java
Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current co... | 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
| #ATS | ATS |
(*
** Solution to Draw_a_sphere.dats
*)
(* ****** ****** *)
//
#include
"share/atspre_define.hats" // defines some names
#include
"share/atspre_staload.hats" // for targeting C
#include
"share/HATS/atspre_staload_libats_ML.hats" // for ...
#include
"share/HATS/atslib_staload_libats_libc.hats" // for libc
//
(* ****... | Give a code snippet in #ATS
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 Deat... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Percentage_difference_between_images | Percentage difference between images | basic bitmap storage
Useful for comparing two JPEG images saved with a different compression ratios.
You can use these pictures for testing (use the full-size version of each):
50% quality JPEG
100% quality JPEG
link to full size 50% image
link to full size 100% image
The expected difference for these two... | #REBOL | REBOL | rebol [
Title: "Percent Image Difference"
URL: http://rosettacode.org/wiki/Percentage_of_difference_between_2_images
]
; Load from local storage. Un/comment as preferred.
; a: load-image %lenna50.jpg
; b: load-image %lenna100.jpg
; Download from rosettacode.org.
a: load-image http://rosettacode.org/mw/images/3/3c... | Give a code snippet in #REBOL
basic bitmap storage
Useful for comparing two JPEG images saved with a different compression ratios.
You can use these pictures for testing (use the full-size version of each):
50% quality JPEG
100% quality JPEG
link to full size 50% image
link to full size 100% image
The ex... | 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)
... | #Nix | Nix | with (import <nixpkgs> { }).lib;
with builtins;
let
fizzbuzz = { x ? 1 }:
''
${if (mod x 15 == 0) then
"FizzBuzz"
else if (mod x 3 == 0) then
"Fizz"
else if (mod x 5 == 0) then
"Buzz"
else
(toString x)}
'' + (if (x < 100) then
fizzbuzz { x = x + 1;... | Give a code snippet in #Nix
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Binary_search | Binary search | A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm.
As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p... | #Simula | Simula | BEGIN
INTEGER PROCEDURE BINARYSEARCHREC(A, LVALUE);
INTEGER ARRAY A;
INTEGER LVALUE; ! VALUE IS A KEY WORD ;
BEGIN
INTEGER PROCEDURE SEARCH(LOW, HIGH);
INTEGER LOW, HIGH;
BEGIN
INTEGER MID;
! INVARIANTS: VALUE > A[I] FOR ALL I < LOW
... | Give a code snippet in #Simula
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm.
As an analogy, consider the children's game "guess a number." The scorer has a secret ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime | Add a variable to a class instance at runtime | Demonstrate how to dynamically add variables to an object (a class instance) at runtime.
This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re... | #Morfa | Morfa |
import morfa.base;
template <T>
public struct Dynamic
{
var data: Dict<text, T>;
}
// convenience to create new Dynamic instances
template <T>
public property dynamic(): Dynamic<T>
{
return Dynamic<T>(new Dict<text,T>());
}
// introduce replacement operator for . - a quoting ` operator
public operator `... | Give a code snippet in #Morfa
Demonstrate how to dynamically add variables to an object (a class instance) at runtime.
This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metapr... | 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... | #Dyalect | Dyalect | func mcnugget(limit) {
var sv = Array.Empty(limit + 1, false)
for s in 0^6..limit {
for n in s^9..limit {
for t in n^20..limit {
sv[t] = true
}
}
}
for i in limit^-1..0 {
if !sv[i] {
print("Maximum non-McNuggets number is \(i)")... | Give a code snippet in #Dyalect
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 Mc... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Four_bit_adder | Four bit adder | Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made using two nots, two ands ... | #Perl | Perl | sub dec2bin { sprintf "%04b", shift }
sub bin2dec { oct "0b".shift }
sub bin2bits { reverse split(//, substr(shift,0,shift)); }
sub bits2bin { join "", map { 0+$_ } reverse @_ }
sub bxor {
my($a, $b) = @_;
(!$a & $b) | ($a & !$b);
}
sub half_adder {
my($a, $b) = @_;
( bxor($a,$b), $a & $b );
}
sub full_ad... | Give a code snippet in #Perl
Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made u... | 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... | #AppleScript | AppleScript | set n to 25
set array to {}
repeat with i from 1 to n
set end of array to i
end repeat
copy {array, array} to {unshuffled, shuffled}
repeat with i from n to 1 by -1
set j to (((random number) * (i - 1)) as integer) + 1
set shuffled's item i to array's item j
if j ≠ i's contents then set array's item j to array's ... | Give a code snippet in #AppleScript
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 f... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
W... | #Euphoria | Euphoria | sequence first = "ABC"
sequence newOne = first | Give a code snippet in #Euphoria
This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empt... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Number_names | Number names | Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than positive integers (like zero, negat... | #Inform_7 | Inform 7 | say 32767 in words; | Give a code snippet in #Inform_7
Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than p... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Show_ASCII_table | Show ASCII table | Task
Show the ASCII character set from values 32 to 127 (decimal) in a table format.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioin... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure Ascii_Table is
N : Integer;
begin
for R in 0 .. 15 loop
for C in 0 .. 5 loop
N := 32 + 16 * C + R;
Put (N, 3);
Put (" : ");
case N is
when 32 =>
... | Give a code snippet in #Ada
Task
Show the ASCII character set from values 32 to 127 (decimal) in a table format.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I b... | christopher/rosetta-code | |
http://rosettacode.org/wiki/I_before_E_except_after_C | I before E except after C | The phrase "I before E, except after C" is a
widely known mnemonic which is supposed to help when spelling English words.
Task
Using the word list from http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
check if the two sub-clauses of the phrase are plausible individually:
"I before E when not pre... | #UNIX_Shell | UNIX Shell | #!/bin/sh
matched() {
grep -Poe "$1" unixdict.txt | wc -l
}
check() {
local num_for="$(matched "$3")"
local num_against="$(matched "$2")"
if [ "$num_for" -le "$(expr 2 \* "$num_against")" ]; then
echo "Clause $1 not plausible ($num_for examples; $num_against counterexamples)"
return 1
else
ech... | Give a code snippet in #UNIX_Shell
The phrase "I before E, except after C" is a
widely known mnemonic which is supposed to help when spelling English words.
Task
Using the word list from http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
check if the two sub-clauses of the phrase are plausible indivi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/24_game | 24 game | The 24 Game tests one's mental arithmetic.
Task
Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.
The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T... | #HicEst | HicEst | DIMENSION digits(4), input_digits(100), difference(4)
CHARACTER expression*100, prompt*100, answers='Wrong,Correct,', protocol='24 game.txt'
1 digits = CEILING( RAN(9) )
2 DLG(Edit=expression, Text=digits, TItle=prompt)
READ(Text=expression, ItemS=n) input_digits
IF(n == 4) THEN
ALIAS(input_digits,1, ... | Give a code snippet in #HicEst
The 24 Game tests one's mental arithmetic.
Task
Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.
The program should prompt for the player to enter an arithmetic expression using just those, and all of those four d... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named o... | #OCaml | OCaml | type entity = { name : string }
let create_entity () = { name = "Entity" }
let print_entity x = print_endline x.name
let create_person () = { name = "Cletus" }
let instance1 = create_person ()
let instance2 = create_entity ()
(* Serialize *)
let out_chan = open_out_bin "objects.dat";;
output_value out_chan instan... | Give a code snippet in #OCaml
Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each o... | 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 ... | #ABAP | ABAP | REPORT R NO STANDARD PAGE HEADING LINE-SIZE 67.
DATA:A(440),B,C,N(3) TYPE N,I TYPE I,S.
A+000 = 'REPORT R NO STANDARD PAGE HEADING LINE-SIZE 6\7.1DATA:A'.
A+055 = '(440),B,C,N(\3) TYPE N,I TYPE I,S.?1DO 440 TIMES.3C = A'.
A+110 = '+I.3IF B = S.5IF C CA `\\\?\1\3\5\7`.7B = C.5ELSEIF C ='.
A+165 = ' `\``.7WRITE ```` NO-G... | Give a code snippet in #ABAP
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
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
... | #Axe | Axe | Disp "TIME:"
input→A
0→T
length(A)→L
For(I,1,L)
If {A}<'0' or {A}>'9'
Disp "NOT A NUMBER",i
Return
End
T*10+{A}-'0'→T
A++
End
Disp "SLEEPING...",i
Pause T
Disp "AWAKE",i | Give a code snippet in #Axe
Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread f... | christopher/rosetta-code | |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #XPL0 | XPL0 | def N=8; \board size (NxN)
int R, C; \row and column of board
char B(N,N); \board
include c:\cxpl\codes;
proc Try; \Try adding a queen to the board
int R; \row, for each level of recursion
func Okay;
\Returns 'true' if no row, column, or diagonal from square R,C has a queen
... | Give a code snippet in #XPL0
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's to... | christopher/rosetta-code | |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the follow... | #Yabasic | Yabasic | 10 n=10:READ w:DIM x(w+1),x2(w+1):FOR i=1 to w:READ x(i):NEXT
20 FOR k=1 TO n
30 FOR j=1 TO w
40 IF x(j) THEN PRINT "#"; ELSE PRINT "_"; END IF
50 IF x(j-1)+x(j)+x(j+1)=2 THEN x2(j)=1 ELSE x2(j)=0 END IF
60 NEXT:PRINT
70 FOR j=1 TO w:x(j)=x2(j):NEXT
80 NEXT
90 DATA 20,0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0 | Give a code snippet in #Yabasic
Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the curre... | christopher/rosetta-code | |
http://rosettacode.org/wiki/String_case | String case | Task
Take the string alphaBETA and demonstrate how to convert it to:
upper-case and
lower-case
Use the default encoding of a string literal or plain ASCII if there is no string literal in your language.
Note: In some languages alphabets toLower and toUpper is not reversable.
Show any additional... | #Jsish | Jsish | var msg = "alphaBETA";
;msg;
;msg.toUpperCase();
;msg.toLowerCase();
;msg.toTitle();
;msg.toLocaleUpperCase();
;msg.toLocaleLowerCase(); | Give a code snippet in #Jsish
Task
Take the string alphaBETA and demonstrate how to convert it to:
upper-case and
lower-case
Use the default encoding of a string literal or plain ASCII if there is no string literal in your language.
Note: In some languages alphabets toLower and toUpper is not r... | christopher/rosetta-code | |
http://rosettacode.org/wiki/HTTPS/Authenticated | HTTPS/Authenticated | The goal of this task is to demonstrate HTTPS requests with authentication.
Implementations of this task should not use client certificates for this: that is the subject of another task.
| #Kotlin | Kotlin | // version 1.2.0
import java.net.Authenticator
import java.net.PasswordAuthentication
import javax.net.ssl.HttpsURLConnection
import java.net.URL
import java.io.InputStreamReader
import java.io.BufferedReader
object PasswordAuthenticator : Authenticator() {
override fun getPasswordAuthentication() =
Pas... | Give a code snippet in #Kotlin
The goal of this task is to demonstrate HTTPS requests with authentication.
Implementations of this task should not use client certificates for this: that is the subject of another task.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not... | #Ruby | Ruby | $ include "seed7_05.s7i";
const proc: snusp (in string: sourceCode, in integer: memSize, inout file: input, inout file: output) is func
local
var array string: instructions is 0 times "";
var array char: memory is 0 times ' ';
var integer: dataPointer is 1;
var integer: instrPtrRow is 0;
var int... | Give a code snippet in #Ruby
Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Ranking_methods | Ranking methods |
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 | competitors=:<;._1;._2]0 :0
44 Solomon
42 Jason
42 Errol
41 Garry
41 Bernard
41 Barry
39 Stephen
)
scores=: {."1
standard=: 1+i.~
modified=: 1+i:~
dense=: #/.~ # #\@~.
ordinal=: #\
fractional=: #/.~ # ] (+/%#)/. #\
rank=:1 :'<"0@u@:scores,.]' | 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/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... | #Vlang | Vlang | fn compute_perfect(n i64) bool {
mut sum := i64(0)
for i := i64(1); i < n; i++ {
if n%i == 0 {
sum += i
}
}
return sum == n
}
// following fntion satisfies the task, returning true for all
// perfect numbers representable in the argument type
fn is_perfect(n i64) bool {
... | Give a code snippet in #Vlang
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/Nim_game | Nim game | Nim game
You are encouraged to solve this task according to the task description, using any language you may know.
Nim is a simple game where the second player ─── if they know the trick ─── will always win.
The game has only 3 rules:
start with 12 tokens
each player takes 1, 2, or 3 tokens in tur... | #AsciiDots | AsciiDots |
%$LMRTX
.-$"Nim Dots"-$""-
/$_"Number must be "\
T /----~------\ |
*M /---+-*-[o] | |
R [-]\ .>#3-+[>][<]-1#<.| |
... | Give a code snippet in #AsciiDots
Nim game
You are encouraged to solve this task according to the task description, using any language you may know.
Nim is a simple game where the second player ─── if they know the trick ─── will always win.
The game has only 3 rules:
start with 12 tokens
each player ta... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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 ... | #Aime | Aime | v_text("Goodbye, World!\n"); | Give a code snippet in #Aime
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/Recaman%27s_sequence | Recaman's sequence | The Recamán's sequence generates Natural numbers.
Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated.
If the conditions don't hold then a(n) = a(n-1) + n.
Task
Generate and show here the... | #ALGOL_W | ALGOL W | begin
% calculate Recaman's sequence values %
% a hash table element - holds n, A(n) and a link to the next element with the %
% same hash value %
record AValue ( integer eN, eAn ; referen... | Give a code snippet in #ALGOL_W
The Recamán's sequence generates Natural numbers.
Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated.
If the conditions don't hold then a(n) = a(n-1) + n.
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Repeat_a_string | Repeat a string | Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****").
Other tasks re... | #ReScript | ReScript | Js.log(Js.String2.repeat("ha", 5)) | Give a code snippet in #ReScript
Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Man_or_boy_test | Man or boy test | Man or boy test
You are encouraged to solve this task according to the task description, using any language you may know.
Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguis... | #PicoLisp | PicoLisp | (de a (K X1 X2 X3 X4 X5)
(let (@K (cons K) B (cons)) # Explicit frame
(set B
(curry (@K B X1 X2 X3 X4) ()
(a (dec @K) (car B) X1 X2 X3 X4) ) )
(if (gt0 (car @K)) ((car B)) (+ (X4) (X5))) ) )
(a 10 '(() 1) '(() -1) '(() -1) '(() 1) '(() 0)) | Give a code snippet in #PicoLisp
Man or boy test
You are encouraged to solve this task according to the task description, using any language you may know.
Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number | Factors of a Mersenne number | A Mersenne number is a number in the form of 2P-1.
If P is prime, the Mersenne number may be a Mersenne prime
(if P is not prime, the Mersenne number is also not prime).
In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy,... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function isPrime(n As Integer) As Boolean
If n Mod 2 = 0 Then Return n = 2
If n Mod 3 = 0 Then Return n = 3
Dim d As Integer = 5
While d * d <= n
If n Mod d = 0 Then Return False
d += 2
If n Mod d = 0 Then Return False
d += 4
Wend
Return True
End Function
' test 929 plu... | Give a code snippet in #FreeBASIC
A Mersenne number is a number in the form of 2P-1.
If P is prime, the Mersenne number may be a Mersenne prime
(if P is not prime, the Mersenne number is also not prime).
In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor befo... | 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 |... | #R | R | print("insert number a")
a <- scan(what=numeric(0), nmax=1)
print("insert number b")
b <- scan(what=numeric(0), nmax=1)
if ( a < b ) {
print("a is less than b")
} else if ( a > b ) {
print("a is greater than b")
} else if ( a == b ) { # could be simply else of course...
print("a and b are the same")
} | Give a code snippet in #R
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
Conc... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Echo_server | Echo server | Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from local... | #X86_Assembly | X86 Assembly |
; x86_64 Linux NASM
global _start
%define af_inet 2
%define sock_stream 1
%define default_proto 0
%define sol_sock 1
%define reuse_addr 2
%define reuse_port 15
%define server_port 9001
%define addr_any 0
%define family_offset 0
%define port_offset 2
%define addr_offset 4
%define unused_offset 8
%define addr_len... | Give a code snippet in #X86_Assembly
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only neces... | christopher/rosetta-code | |
http://rosettacode.org/wiki/String_case | String case | Task
Take the string alphaBETA and demonstrate how to convert it to:
upper-case and
lower-case
Use the default encoding of a string literal or plain ASCII if there is no string literal in your language.
Note: In some languages alphabets toLower and toUpper is not reversable.
Show any additional... | #Raven | Raven | 'alphaBETA' upper
'alhpaBETA' lower | Give a code snippet in #Raven
Task
Take the string alphaBETA and demonstrate how to convert it to:
upper-case and
lower-case
Use the default encoding of a string literal or plain ASCII if there is no string literal in your language.
Note: In some languages alphabets toLower and toUpper is not r... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Bitmap/Histogram | Bitmap/Histogram | Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, wh... | #Kotlin | Kotlin | // version 1.2.10
import java.io.File
import java.awt.image.BufferedImage
import javax.imageio.ImageIO
const val BLACK = 0xff000000.toInt()
const val WHITE = 0xffffffff.toInt()
fun luminance(argb: Int): Int {
val red = (argb shr 16) and 0xFF
val green = (argb shr 8) and 0xFF
val blue = argb and 0... | Give a code snippet in #Kotlin
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must h... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Program_termination | Program termination |
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks... | #Go | Go | func main() {
if problem {
return
}
} | Give a code snippet in #Go
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/de... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #Dyalect | Dyalect | var switchWins = 0
var stayWins = 0
for plays in 0..1000000 {
var doors = [0 ,0, 0]
var winner = rnd(max: 3)
doors[winner] = 1
var choice = rnd(max: 3)
var shown = rnd(max: 3)
while doors[shown] == 1 || shown == choice {
shown = rnd(max: 3)
}
stayWins += doors[choice]
s... | Give a code snippet in #Dyalect
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for t... | 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 ... | #C.2B.2B | C++ | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
int digit_product(int base, int n) {
int product = 1;
for (; n != 0; n /= base)
product *= n % base;
return product;
}
int prime_factor_sum(int n) {
int sum = 0;
for (; (n & 1) == 0; n >>= 1)
sum += 2;... | Give a code snippet in #C.2B.2B
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 number... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Yahoo!_search_interface | Yahoo! search interface | Create a class for searching Yahoo! results.
It must implement a Next Page method, and read URL, Title and Content from results.
| #Ruby | Ruby | require 'open-uri'
require 'hpricot'
SearchResult = Struct.new(:url, :title, :content)
class SearchYahoo
@@urlinfo = [nil, 'ca.search.yahoo.com', 80, '/search', nil, nil]
def initialize(term)
@term = term
@page = 1
@results = nil
@url = URI::HTTP.build(@@urlinfo)
end
def next_result
... | Give a code snippet in #Ruby
Create a class for searching Yahoo! results.
It must implement a Next Page method, and read URL, Title and Content from results.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Pierpont_primes | Pierpont primes | A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v .
A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v .
The term "Pierpont primes" is generally understood to mean the first definition, but will be c... | #M2000_Interpreter | M2000 Interpreter | Module Pierpoint_Primes {
Form 80
Set Fast !
const NPP=50
dim pier(1 to 2, 1 to NPP), np(1 to 2) = 0
def long x = 1, j
while np(1)<=NPP or np(2)<=NPP
x++
j = @is_pierpont(x)
if j>0 Else Continue
if j mod 2 = 1 then np(1)++ :if np(1) <= NPP then... | Give a code snippet in #M2000_Interpreter
A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v .
A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v .
The term "Pierpont primes" is generally understood ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation | Horner's rule for polynomial evaluation | A fast scheme for evaluating a polynomial such as:
−
19
+
7
x
−
4
x
2
+
6
x
3
{\displaystyle -19+7x-4x^{2}+6x^{3}\,}
when
x
=
3
{\displaystyle x=3\;}
.
is to arrange the computation as follows:
(
(
(
(
0
)
x
+
6
)
x
+
(
−
4
)
)
x
+
7
)
x
+
(
−
19
)
{\displaystyle ((((0)x+6)x+(-4))x... | #ERRE | ERRE |
PROGRAM HORNER
! 2 3
! polynomial is -19+7x-4x +6x
!
DIM C[3]
PROCEDURE HORNER(C[],X->RES)
LOCAL I%,V
FOR I%=UBOUND(C,1) TO 0 STEP -1 DO
V=V*X+C[I%]
END FOR
RES=V
END PROCEDURE
BEGIN
C[]=(-19,7,-4,6)
HORNER(C[],3->RES)
PRINT(RES)
END PROGRAM
| Give a code snippet in #ERRE
A fast scheme for evaluating a polynomial such as:
−
19
+
7
x
−
4
x
2
+
6
x
3
{\displaystyle -19+7x-4x^{2}+6x^{3}\,}
when
x
=
3
{\displaystyle x=3\;}
.
is to arrange the computation as follows:
(
(
(
(
0
)
x
+
6
)
x
+
(
−
4
)
)
x
+
7
)
x
+
(
−
19
)
{\d... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #BASIC | BASIC | #INCLUDE "datetime.bi"
DECLARE FUNCTION julian(AS DOUBLE) AS INTEGER
SeasonNames:
DATA "Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"
Weekdays:
DATA "Setting Orange", "Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle"
DaysPreceding1stOfMonth:
' jan feb mar apr may jun jul aug sep oct n... | Give a code snippet in #BASIC
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| 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... | #Lua | Lua | function love.load()
text = "Hello World! "
length = string.len(text)
update_time = 0.3
timer = 0
right_direction = true
local width, height = love.graphics.getDimensions( )
local size = 100
local font = love.graphics.setNewFont( size )
local twidth = font:getWidth( text )
local theight = font:getHe... | Give a code snippet in #Lua
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 demo... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | local :dog "Benjamin"
local :Dog "Samba"
local :DOG "Bernie"
!print( "There are three dogs named " dog ", " Dog " and " DOG "." ) | Give a code snippet in #D.C3.A9j.C3.A0_Vu
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
... | #Babel | Babel | main:
{((0 0) (0 1) (0 2)
(0 3) (0 4) (1 0)
(1 1) (1 2) (1 3)
(1 4) (2 0) (2 1)
(2 2) (2 3) (3 0)
(3 1) (3 2) (4 0))
{ dup
"A(" << { %d " " . << } ... ") = " <<
reverse give
ack
%d cr << } ... }
ack!:
{ dup zero?
{ <-> dup ... | Give a code snippet in #Babel
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Formatted_numeric_output | Formatted numeric output | Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
| #Factor | Factor | USE: formatting
7.125 "%09.3f\n" printf | Give a code snippet in #Factor
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/XML/XPath | XML/XPath | Perform the following three XPath queries on the XML Document below:
//item[1]: Retrieve the first "item" element
//price/text(): Perform an action on each "price" element (print it out)
//name: Get an array of all the "name" elements
XML Document:
<inventory title="OmniCorp Store #45x10^3">
<section name="heal... | #JavaScript | JavaScript | //create XMLDocument object from file
var xhr = new XMLHttpRequest();
xhr.open('GET', 'file.xml', false);
xhr.send(null);
var doc = xhr.responseXML;
//get first <item> element
var firstItem = doc.evaluate( '//item[1]', doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue;
alert( firstItem.textConten... | Give a code snippet in #JavaScript
Perform the following three XPath queries on the XML Document below:
//item[1]: Retrieve the first "item" element
//price/text(): Perform an action on each "price" element (print it out)
//name: Get an array of all the "name" elements
XML Document:
<inventory title="OmniCorp St... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Constrained_genericity | Constrained genericity | Constrained genericity or bounded quantification means
that a parametrized type or function (see parametric polymorphism)
can only be instantiated on types fulfilling some conditions,
even if those conditions are not used in that function.
Say a type is called "eatable" if you can call the function eat on it.
Write a ... | #Common_Lisp | Common Lisp | (defclass food () ())
(defclass inedible-food (food) ())
(defclass edible-food (food) ())
(defgeneric eat (foodstuff)
(:documentation "Eat the foodstuff."))
(defmethod eat ((foodstuff edible-food))
"A specialized method for eating edible-food."
(format nil "Eating ~w." foodstuff))
(defun eatable-p (thin... | Give a code snippet in #Common_Lisp
Constrained genericity or bounded quantification means
that a parametrized type or function (see parametric polymorphism)
can only be instantiated on types fulfilling some conditions,
even if those conditions are not used in that function.
Say a type is called "eatable" if you can ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Reflection/Get_source | Reflection/Get source | Task
The goal is to get the source code or file path and line number where a programming object (e.g. module, class, function, method) is defined.
| #6502_Assembly | 6502 Assembly | LDA #<foo
sta $00
LDA #>foo
sta $01
jsr PrintBytecode
foo:
;do stuff
rts
PrintBytecode:
ldy #0
lda $01 ;high byte of starting address of the source
jsr PrintHex
;unimplemented routine that separates the "nibbles" of the accumulator,
; adds $30 or $37 to each depending on if it's 0-9 or A-F respectively, which... | Give a code snippet in #6502_Assembly
Task
The goal is to get the source code or file path and line number where a programming object (e.g. module, class, function, method) is defined.
| 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.
| #Frink | Frink | println[newJava["java.io.File", "input.txt"].length[]]
println[newJava["java.io.File", "/input.txt"].length[]] | Give a code snippet in #Frink
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/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 ... | #R | R | J_n_S <- function(stones ="aAAbbbb", jewels = "aA") {
stones <- unlist(strsplit(stones, split = "")) # obtain a character vector
jewels <- unlist(strsplit(jewels, split = ""))
count <- sum(stones %in% jewels)
}
print(J_n_S("aAAbbbb", "aA"))
print(J_n_S("ZZ", "z"))
print(J_n_S("lgGKJGljglghGLGHlhglghoIPOgfdtrdD... | Give a code snippet in #R
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/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is c... | #zkl | zkl | var BN=Import("zklBigNum");
BN(1)+2 //--> BN(3) | Give a code snippet in #zkl
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrat... | #XPL0 | XPL0 | char Str(80);
func Duration(Sec); \Convert seconds to compound duration
int Sec, Amt, Unit, DoComma, I, Quot;
[Amt:= [7*24*60*60, 24*60*60, 60*60, 60, 1];
Unit:= [" wk", " d", " hr", " min", " sec"];
DoComma:= false;
for I:= 0 to 4 do
[Quot:= Sec/Amt(I);
Sec:= rem(0);
if Quot # 0 then
[if DoComma t... | Give a code snippet in #XPL0
Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Random_number_generator_(included) | Random number generator (included) | The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not t... | #FreeBASIC | FreeBASIC | randomInteger = rnd(expr)
| Give a code snippet in #FreeBASIC
The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algo... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Pike | Pike | array(int) addsub(int x, int y)
{
return ({ x+y, x-y });
}
[int z, int w] = addsub(5,4); | Give a code snippet in #Pike
Task
Show how to return more than one value from a function.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of point... | #Delphi | Delphi |
unit Main;
interface
uses
Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.ExtCtrls;
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormPaint(Sender: TObject);
end;
var
Form1: TForm1;
Points: TArray<TPoint>;
implementa... | Give a code snippet in #Delphi
Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" ci... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Entropy/Narcissist | Entropy/Narcissist |
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| #Java | Java |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class EntropyNarcissist {
private static final String FILE_NAME = "src/EntropyNarcissist.java";
public static void main(String[] args) {
... | Give a code snippet in #Java
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Index_finite_lists_of_positive_integers | Index finite lists of positive integers | It is known that the set of finite lists of positive integers is countable.
This means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers.
Task
Implement such a mapping:
write a function rank which assigns an integer to any finite, arbi... | #Quackery | Quackery | [ $ "" swap
witheach
[ number$
char A join join ]
11 base put
$->n drop
base release ] is rank ( [ --> n )
[ 11 base put
number$
base release
[] $ "" rot
witheach
[ dup char A = iff
[ drop
$->n drop join
$ "" ]
... | Give a code snippet in #Quackery
It is known that the set of finite lists of positive integers is countable.
This means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers.
Task
Implement such a mapping:
write a function rank which assi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Best_shuffle | Best shuffle | Task
Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible.
A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative... | #Action.21 | Action! | PROC BestShuffle(CHAR ARRAY orig,res)
BYTE i,j,len
CHAR tmp
len=orig(0)
SCopy(res,orig)
FOR i=1 TO len
DO
FOR j=1 TO len
DO
IF i#j AND orig(i)#res(j) AND orig(j)#res(i) THEN
tmp=res(i) res(i)=res(j) res(j)=tmp
FI
OD
OD
RETURN
PROC Test(CHAR ARRAY orig)
CHAR ARRAY res(... | Give a code snippet in #Action.21
Task
Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible.
A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every t... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers | Sort a list of object identifiers |
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
... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | in = {"1.3.6.1.4.1.11.2.17.19.3.4.0.10",
"1.3.6.1.4.1.11.2.17.5.2.0.79", "1.3.6.1.4.1.11.2.17.19.3.4.0.4",
"1.3.6.1.4.1.11150.3.4.0.1", "1.3.6.1.4.1.11.2.17.19.3.4.0.1",
"1.3.6.1.4.1.11150.3.4.0"};
in = StringSplit[#, "."] & /@ in;
in = Map[ToExpression, in, {2}];
Column[StringRiffle[ToString /@ #, "."] & /... | Give a code snippet in #Mathematica_.2F_Wolfram_Language
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Chat_server | Chat server | Task
Write a server for a minimal text based chat.
People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
| #Ada | Ada | with Ada.Containers.Vectors;
with Ada.Command_Line; use Ada.Command_Line;
with Ada.Exceptions; use Ada.Exceptions;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Sockets; use Sockets;
procedure Chat_Server is
package Client_Vectors is new Ada.Contai... | Give a code snippet in #Ada
Task
Write a server for a minimal text based chat.
People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Last_Friday_of_each_month | Last Friday of each month | Task
Write a program or a script that returns the date of the last Fridays of each month of a given year.
The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_fridays 2012
2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
20... | #Ada | Ada | with Ada.Text_IO, GNAT.Calendar.Time_IO, Ada.Command_Line,
Ada.Calendar.Formatting, Ada.Calendar.Arithmetic;
procedure Last_Weekday_In_Month is
procedure Put_Line(T: Ada.Calendar.Time) is
use GNAT.Calendar.Time_IO;
begin
Ada.Text_IO.Put_Line(Image(Date => T, Picture => ISO_Date));
end Put_Lin... | Give a code snippet in #Ada
Task
Write a program or a script that returns the date of the last Fridays of each month of a given year.
The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_fridays 2012
2012-01-27
2012-02-24
2012-0... | 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... | #Wren | Wren | class Approx {
construct new(nu, sigma) {
_nu = nu
_sigma = sigma
}
static new(a) {
if (a is Approx) return Approx.new(a.nu, a.sigma)
if (a is Num) return Approx.new(a, 0)
}
nu { _nu }
sigma { _sigma }
+(a) {
if (a is Approx) return Approx... | Give a code snippet in #Wren
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/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #TUSCRIPT | TUSCRIPT | $$ MODE TUSCRIPT
STATUS = CREATE ("tape.file",tape-o,-std-)
PRINT STATUS | Give a code snippet in #TUSCRIPT
The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| 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 ... | #Raku | Raku | class Square {
has Complex ($.position, $.edge);
method size { $!edge.abs }
method svg-polygon {
qq[<polygon points="{join ' ', map
{ ($!position + $_ * $!edge).reals.join(',') },
0, 1, 1+1i, 1i}" style="fill:lime;stroke=black" />]
}
method left-child {
self.new:
position => $!position + i*$!ed... | Give a code snippet in #Raku
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Compare_length_of_two_strings | Compare length of two strings |
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 | function test(list)
table.sort(list, function(a,b) return #a > #b end)
for _,s in ipairs(list) do print(#s, s) end
end
test{"abcd", "123456789", "abcdef", "1234567"} | 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/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Standard_ML | Standard ML | val mtime = OS.FileSys.modTime filename; (* returns a Time.time data structure *)
(* unfortunately it seems like you have to set modification & access times together *)
OS.FileSys.setTime (filename, NONE); (* sets modification & access time to now *)
(* equivalent to: *)
OS.FileSys.setTime (filename, SOME (Time.now (... | Give a code snippet in #Standard_ML
Task
Get and set the modification time of a file.
| 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... | #CLU | CLU | % Recursive nugget iterator.
% This yields all the nugget numbers of the given box sizes from start to max.
gen_nuggets = iter (start, max: int, sizes: sequence[int]) yields (int)
si = sequence[int]
if si$empty(sizes) then
yield(start)
else
for i: int in int$from_to_by(start, max, si$botto... | Give a code snippet in #CLU
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 McNugg... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #F.23 | F# | Microsoft F# Interactive, (c) Microsoft Corporation, All Rights Reserved
F# Version 1.9.6.2, compiling for .NET Framework Version v2.0.50727
Please send bug reports to fsbugs@microsoft.com
For help type #help;;
> let f a b sep = String.concat sep [a; ""; b] ;;
val f : string -> string -> string -> string
> f "R... | Give a code snippet in #F.23
Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously... | #Phix | Phix | with javascript_semantics
include builtins\base64.e
string s = "Rosetta Code Base64 decode data task"
string e = encode_base64(s)
?e
?decode_base64(e)
| Give a code snippet in #Phix
See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output wit... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out... | #Python | Python | print ord('a') # prints "97"
print chr(97) # prints "a" | Give a code snippet in #Python
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Con... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Elixir | Elixir |
def project do
[app: :repo
version: "0.1.0-dev",
name: "REPO",
source_url: "https://github.com/USER/REPO",
homepage_url: "http://YOUR_PROJECT_HOMEPAGE"
deps: deps]
end
| Give a code snippet in #Elixir
See also
Related task: Comments
Related task: Here_document
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Variables | Variables | Task
Demonstrate a language's methods of:
variable declaration
initialization
assignment
datatypes
scope
referencing, and
other variable related facilities
| #Arturo | Arturo | num: 10
str: "hello world"
arrA: [1 2 3]
arrB: ["one" "two" "three"]
arrC: [1 "two" [3 4 5]]
arrD: ["one" true [ print "something" ]]
dict: [
name: "john"
surname: "doe"
function: $[][
print "do sth"
]
]
inspect symbols | Give a code snippet in #Arturo
Task
Demonstrate a language's methods of:
variable declaration
initialization
assignment
datatypes
scope
referencing, and
other variable related facilities
| christopher/rosetta-code | |
http://rosettacode.org/wiki/String_comparison | String 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 |... | #Quackery | Quackery | /O> ( compare two strings for equality )
... $ "abc" $ "xyz" =
... echo ( 0 = false, 1 = true )
...
0
Stack empty.
/O> ( compare two strings for inequality )
... $ "abc" $ "xyz" !=
... echo ( 0 = false, 1 = true )
...
1
Stack empty.
//O> ( compare two strings to see if one is lexically ordered before the other )
..... | Give a code snippet in #Quackery
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/Color_wheel | Color wheel | Task
Write a function to draw a HSV color wheel completely with code.
This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel (as procedurally drawing is super slow). This does help you understand how color wheels work and ... | #AppleScript | AppleScript |
choose color default color {0, 0, 0, 0}
| Give a code snippet in #AppleScript
Task
Write a function to draw a HSV color wheel completely with code.
This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel (as procedurally drawing is super slow). This does help you ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1... | #Swift | Swift | func factorial<T: BinaryInteger>(_ n: T) -> T {
guard n != 0 else {
return 1
}
return stride(from: n, to: 0, by: -1).reduce(1, *)
}
func binomial<T: BinaryInteger>(_ x: (n: T, k: T)) -> T {
let nFac = factorial(x.n)
let kFac = factorial(x.k)
return nFac / (factorial(x.n - x.k) * kFac)
}
print("b... | Give a code snippet in #Swift
This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response | Keyboard input/Obtain a Y or N response |
Task
Obtain a valid Y or N response from the keyboard.
The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing Y or N key-press from being evaluated.
The response should be obtained as soon as Y or N are pressed, and there should be no need t... | #PL.2FI | PL/I | yn: Proc Options(main):
Dcl sysin stream input;
Dcl sysprint stream output;
Dcl c Char(1);
Put Skip List('Please enter Y or N');
Get Edit(c)(a(1));
Select(c);
When('Y','y','J','j')
Put Skip List('YES');
When('N','n')
Put Skip List('NO');
Otherwise
Put Skip List('Undecided?');
End;
End... | Give a code snippet in #PL.2FI
Task
Obtain a valid Y or N response from the keyboard.
The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing Y or N key-press from being evaluated.
The response should be obtained as soon as Y or N are presse... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Smith_numbers | Smith numbers | Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1.
By definition, all primes are excluded as they (naturally) satisfy this condition!
Smith numbers are also known as joke numbers.... | #PicoLisp | PicoLisp | (de factor (N)
(make
(let (D 2 L (1 2 2 . (4 2 4 2 4 6 2 6 .)) M (sqrt N))
(while (>= M D)
(if (=0 (% N D))
(setq M (sqrt (setq N (/ N (link D)))))
(inc 'D (pop 'L)) ) )
(link N) ) ) )
(de sumdigits (N)
(sum format (chop N)) )
(de smith (X)
(m... | Give a code snippet in #PicoLisp
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1.
By definition, all primes are excluded as they (naturally) satisfy this condition!
Smith numbers a... | christopher/rosetta-code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.